text:
#include "SymbianMFDBufRequester.h"
#include "MapUtility.h"
#include <utf.h>
#include <f32file.h>

void
SymbianFileHandler::init()
{
   // Open the file for reading.
   openFile();
   m_initialized = true;
   m_state = IDLE;
   if ( m_status == KErrNone ) {
      setPos( 0 );
      CActiveScheduler::Add(this);
   }
}

SymbianFileHandler::SymbianFileHandler( RFs& fileServer,
                                        const char* fileName,
                                        int createFile,
                                        int initNow,
                                        int readOnly )
    : FileHandler( fileName ),
      CActive( EPriorityNormal ),
      //CActive( EPriorityHigh ),
      m_fileServer( fileServer ),
      m_dataPtr( NULL, 0 ),
      m_createFile( createFile ),
      m_readOnly( readOnly )
{
   m_status = KErrNone;

   // Convert the filename to unicode. Needed for lots of operations.
   m_fileName16 = MapUtility::utf8ToUnicode( fileName );

   m_initialized = false;
   if ( initNow ) {
      init();
   }
}

SymbianFileHandler::~SymbianFileHandler()
{
   if ( IsActive() ) {
      Cancel();
   }
   if ( status() == 0 && m_initialized ) {
      m_file.Close();
   }
   // Delete the HBufC
   delete m_fileName16;
}

int
SymbianFileHandler::status() const
{
   if ( m_status == KErrNone ) {
      return 0;
   } else {
      return -1;
   }
}

bool
SymbianFileHandler::openFile()
{
   m_status = KErrNone;
   if ( m_createFile ) {
      // Create the directory where the file should be if it does not
      // exist.
      TParsePtrC parser( *m_fileName16 );
      // And make the dir
      m_status = m_fileServer.MkDirAll( parser.DriveAndPath() );
   }

   if( m_status == KErrNone || m_status == KErrAlreadyExists )
   // Try to open the file.
   {
      m_status = m_file.Open( m_fileServer, *m_fileName16,
                              m_readOnly ? EFileRead | EFileShareReadersOnly : EFileWrite );
      if ( m_status != KErrNone ) {
         // Seems like we must close the file now.
         m_file.Close();
      } else {
         return true;
      }
   }

   // Try creating it if we should
   if ( m_createFile ) {
      // Now we will have read/write file even if we should open it
      // read only.
      m_status = m_file.Create( m_fileServer, *m_fileName16, EFileWrite );
   }

   return m_status == KErrNone;
}

void
SymbianFileHandler::clearFile()
{
   if ( ! m_initialized ) {
      init();
   }
   m_file.Close();
   // Delete file.
   m_fileServer.Delete( *m_fileName16 );
   // And create empty file.
   m_status = m_file.Create( m_fileServer, *m_fileName16, EFileWrite );
}

int
SymbianFileHandler::read( uint8* bytes,
                          int maxLength,
                          FileHandlerListener* listener )
{
   if ( ! m_initialized ) {
      init();
   }

   m_state = READING;
   m_dataPtr.Set( bytes, maxLength, maxLength );
   m_currentListener = listener;

   if ( listener ) {
      m_file.Read( m_dataPtr, iStatus );
      SetActive();
      return 0;
   } else {
      TRequestStatus status;
      m_file.Read( m_dataPtr, status );
      User::WaitForRequest( status );
      m_state = IDLE;
      if ( status == KErrNone ) {
         return m_dataPtr.Length();
      } else {
         return -1;
      }
   }
}

int
SymbianFileHandler::write( const uint8* bytes,
                           int length,
                           FileHandlerListener* listener )
{
   if ( ! m_initialized ) {
      init();
   }
   m_state = WRITING;
   m_dataPtr.Set( const_cast<unsigned char*>(bytes), length, length );
   m_currentListener = listener;
   if ( listener ) {
      m_file.Write( m_dataPtr, iStatus );
      SetActive();
      return 0;
   } else {
      TRequestStatus status;
      m_file.Write( m_dataPtr, status );
      User::WaitForRequest( status );
      m_state = IDLE;
      if ( status == KErrNone ) {
         return length;
      } else {
         return -1;
      }
   }
}

void
SymbianFileHandler::cancel()
{
   if ( IsActive() ) {
      Cancel();
   }
}

void
SymbianFileHandler::setPos( int pos )
{
   if ( ! m_initialized ) {
      init();
   }
   if ( pos >= 0 ) {
      int tmpPos = pos;
      m_file.Seek( ESeekStart , tmpPos );
   } else {
      int tmpPos = 0;
      m_file.Seek( ESeekEnd, tmpPos );
   }
}

void
SymbianFileHandler::setSize( int size )
{
   if ( ! m_initialized ) {
      init();
   }

   m_file.SetSize( size );
}

int
SymbianFileHandler::tell()
{
   if ( ! m_initialized ) {
      init();
   }
   int tmpPos = 0;
   m_file.Seek( ESeekCurrent, tmpPos );
   return tmpPos;
}

uint32
SymbianFileHandler::getModificationDate() const
{
   // The day the unix time starts. Used to get the time down
   // to a reasonable value.
   TDateTime epoch( 1970, EJanuary, 01, 0 , 0 , 0 , 0);
   TTime aTime( epoch );
   TInt res = m_fileServer.Modified( *m_fileName16, aTime );
   if ( res != KErrNone ) {
      return MAX_UINT32;
   }
   TTimeIntervalMicroSeconds interval = aTime.MicroSecondsFrom( epoch );
   return LOW( interval.Int64() / 1000000 );
}

uint32
SymbianFileHandler::getAvailableSpace() const
{
   // Sometimes Symbian makes life tricky.
   TChar driveChar = (*m_fileName16)[0];
   TInt currentDrive;
   int ctdRes = m_fileServer.CharToDrive( driveChar, currentDrive);
   if ( ctdRes != KErrNone ) {
      // Something went wrong. Use the default drive.
      currentDrive = KDefaultDrive;
   }
   TVolumeInfo volume;
   TInt res = m_fileServer.Volume( volume, currentDrive );
   if ( res != KErrNone ) {
      return MAX_UINT32;
   }
   // Check if we have _a lot_ of space.
   if ( volume.iFree > TInt64(TInt(MAX_INT32)) ) {
      return MAX_INT32;
   } else {
      return LOW(volume.iFree);
   }
}

int
SymbianFileHandler::getFileSize()
{
   if ( m_initialized ) {
      // It seems to be faster to use FileHandler::getFileSize()
      // (using Seek) if the file is already opened.
      return FileHandler::getFileSize();
   } else {
      // Get the filesize without opening the file to reduce the
      // startup delay.
      TEntry fileEntry;
      if ( m_fileServer.Entry( *m_fileName16, fileEntry ) != KErrNone ) {
         // Ouch. Didn't work.
         return 0;
      }
      return fileEntry.iSize;
   }
}

void
SymbianFileHandler::RunL()
{
   if ( iStatus != KErrNone ) {
   }
   switch ( m_state ) {
      case IDLE:
         break;
      case READING:
         m_state = IDLE;
         if ( iStatus == KErrNone ) {
            m_currentListener->readDone( m_dataPtr.Length() );
         } else {
            m_currentListener->readDone( -1 );
         }
         break;
      case WRITING:
         m_state = IDLE;
         if ( iStatus == KErrNone ) {
            m_currentListener->writeDone( m_dataPtr.Length() );
         } else {
            m_currentListener->writeDone( -1 );
         }
   }
}

void
SymbianFileHandler::DoCancel()
{

}

// -- SymbianMFDBufRequester

const char*
SymbianMFDBufRequester::createUTF8Path( const TDesC& unicodePath )
{
   // Paths may be max 256 in Symbian.
   TBuf<256> unicodePathBuf;
   unicodePathBuf.Copy( unicodePath );
   TBuf8<256> aUtf8;
   CnvUtfConverter::ConvertFromUnicodeToUtf8(aUtf8,
                                             unicodePathBuf);
   const char* tmpPtr = reinterpret_cast<const char*>(aUtf8.PtrZ());

   m_utf8Path = new char[ strlen(tmpPtr) + 1 ];
   strcpy(m_utf8Path, tmpPtr);
   // Remove trailing slashes.
   while ( m_utf8Path[ strlen( m_utf8Path ) - 1 ]  == '\\' ) {
      m_utf8Path[ strlen( m_utf8Path ) - 1 ] = '\0';
   }
   return m_utf8Path;
}


text:
package com.gemstone.gemfire.internal.net;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * The SocketUtils class is utility class for performing operations on Sockets and ServerSockets.
 *

 * @author John Blum
 * @see java.net.ServerSocket
 * @see java.net.Socket
 * @since 7.0
 */
public abstract class SocketUtils {

  /**
   * Closes the specified Socket silently ignoring any IOException, guarding against null Object references.
   *

   * @param socket the Socket to close.
   * @return boolean value indicating whether the Socket was successfully closed.  If the Socket Object reference
   * is null, then this method will return true.
   * @see java.net.Socket#close()
   */
  public static boolean close(final Socket socket) {
    if (socket != null) {
      try {
        socket.close();
      }
      catch (IOException ignore) {
        return false;
      }
    }

    return true;
  }

  /**
   * Closes the specified ServerSocket silently ignoring any IOException, guarding against null Object references.
   *

   * @param serverSocket the ServerSocket to close.
   * @return boolean value indicating whether the ServerSocket was successfully closed.  If the ServerSocket Object
   * reference is null, then this method will return true.
   * @see java.net.ServerSocket#close()
   */
  public static boolean close(final ServerSocket serverSocket) {
    if (serverSocket != null) {
      try {
        serverSocket.close();
      }
      catch (IOException ignore) {
        return false;
      }
    }

    return true;
  }

}

redpajama_set_name: RedPajamaGithub


text:
package org.sourcepit.b2.model.module;

/**
 * @author Bernd
 */
public class PluginsFacetTest extends AbstractProjectFacetTest<PluginProject, PluginsFacet> {
   @Override
   protected PluginsFacet createFacet() {
      return ModuleModelFactory.eINSTANCE.createPluginsFacet();
   }

   @Override
   protected PluginProject createProject() {
      return ModuleModelFactory.eINSTANCE.createPluginProject();
   }
}


text:
require "spec_helper"

describe SpreeShopifyImporter::Importers::ProductImporterJob, type: :job do
  subject { described_class.new }

  describe "#perfrom" do
    let(:resource) { double("ShopifyProduct") }

    it "calls a importer service" do
      expect(SpreeShopifyImporter::Importers::ProductImporter).to receive(:new).and_call_original
      expect_any_instance_of(SpreeShopifyImporter::Importers::ProductImporter).to receive(:import!)

      subject.perform(resource)
    end
  end
end


text:
namespace trace {
namespace service {

// Forward declaration.
class BufferPool;
class Session;

// A Buffer extends the RPC defined CallTraceBuffer structure with the
// extra bits needed by the internals of the Call Trace service.
struct Buffer : public ::CallTraceBuffer {
  // A buffer is always in one of the following states.
  enum BufferState {
    kAvailable,
    kInUse,
    kPendingWrite,
    kBufferStateMax,
  };

  // Type used to identify a buffer. The first and second values in the
  // pair are the numeric id of the shared memory handle and the buffer
  // offset, respectively. See the GetID() method, below.
  typedef std::pair<unsigned long, unsigned long> ID;

  // Utility to get the ID for any buffer instance.
  static ID GetID(const CallTraceBuffer& buffer) {
    return std::make_pair(buffer.shared_memory_handle, buffer.buffer_offset);
  }

  // We augment the buffer with some additional state.
  Session* session;
  BufferPool* pool;
  BufferState state;
};

// A BufferPool manages a collection of buffers that all belong to the same
// shared memory allocation.
class BufferPool {
 public:
  BufferPool();
  ~BufferPool();

  // Allocates and maps a shared memory segment sufficiently large for
  // @p num_buffers, each of size @p buffer_size.
  bool Init(Session* session, size_t num_buffers, size_t buffer_size);

  // Updates each buffer in buffers_ with @p client_handle, which should be
  // a copy of handle_, valid in the client process these buffers are to be
  // shared with.
  // @p num_buffers, each of size @p buffer_size.
  void SetClientHandle(HANDLE client_handle);

  Buffer* begin() { return &buffers_[0]; }
  Buffer* end() { return begin() + buffers_.size(); }

  // Returns this pools shared memory segment handle.
  HANDLE handle() const { return handle_.Get(); }

 private:
  typedef std::vector<Buffer> BufferCollection;
  // Sadly ScopedHandle is not const correct.
  mutable base::win::ScopedHandle handle_;
  BufferCollection buffers_;

  DISALLOW_COPY_AND_ASSIGN(BufferPool);
};

}  // namespace service
}  // namespace trace

#endif  // SYZYGY_TRACE_SERVICE_BUFFER_POOL_H_


text:
package model;

public class Contact {

	private String email;
	private String phone;

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}
}


text:
<Type Name="ImageSource" FullName="Xamarin.Forms.ImageSource">
  <TypeSignature Language="C#" Value="public abstract class ImageSource : Xamarin.Forms.Element" />
  <TypeSignature Language="ILAsm" Value=".class public auto ansi abstract beforefieldinit ImageSource extends Xamarin.Forms.Element" />
  <AssemblyInfo>
    <AssemblyName>Xamarin.Forms.Core</AssemblyName>
    <AssemblyVersion>1.0.0.0</AssemblyVersion>
    <AssemblyVersion>1.1.0.0</AssemblyVersion>
    <AssemblyVersion>1.2.0.0</AssemblyVersion>
    <AssemblyVersion>1.3.0.0</AssemblyVersion>
    <AssemblyVersion>1.4.0.0</AssemblyVersion>
    <AssemblyVersion>1.5.0.0</AssemblyVersion>
    <AssemblyVersion>2.0.0.0</AssemblyVersion>
  </AssemblyInfo>
  <Base>
    <BaseTypeName>Xamarin.Forms.Element</BaseTypeName>
  </Base>
  <Interfaces>
  </Interfaces>
  <Attributes>
    <Attribute>
      <AttributeName>Xamarin.Forms.TypeConverter(typeof(Xamarin.Forms.ImageSourceConverter))</AttributeName>
    </Attribute>
  </Attributes>
  <Docs>
    Abstract class whose implementors load images from files or the Web.
    <remarks>To be added.</remarks>
  </Docs>
  <Members>
    <Member MemberName=".ctor">
      <MemberSignature Language="C#" Value="protected ImageSource ();" />
      <MemberSignature Language="ILAsm" Value=".method familyhidebysig specialname rtspecialname instance void .ctor() cil managed" />
      <MemberType>Constructor</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>2.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <Parameters />
      <Docs>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="Cancel">
      <MemberSignature Language="C#" Value="public virtual System.Threading.Tasks.Task<bool> Cancel ();" />
      <MemberSignature Language="ILAsm" Value=".method public hidebysig newslot virtual instance class System.Threading.Tasks.Task`1<bool> Cancel() cil managed" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.0.0.0</AssemblyVersion>
        <AssemblyVersion>1.1.0.0</AssemblyVersion>
        <AssemblyVersion>1.2.0.0</AssemblyVersion>
        <AssemblyVersion>1.3.0.0</AssemblyVersion>
        <AssemblyVersion>1.4.0.0</AssemblyVersion>
        <AssemblyVersion>1.5.0.0</AssemblyVersion>
        <AssemblyVersion>2.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.Threading.Tasks.Task<System.Boolean></ReturnType>
      </ReturnValue>
      <Parameters />
      <Docs>
        Request a cancel of the ImageSource loading.
        <returns>An awaitable Task. The result of the Task indicates if the Task was successfully cancelled.</returns>
        <remarks>Calling Cancel() multiple times will throw an exception.</remarks>
      </Docs>
    </Member>
    <Member MemberName="CancellationTokenSource">
      <MemberSignature Language="C#" Value="protected System.Threading.CancellationTokenSource CancellationTokenSource { get; }" />
      <MemberSignature Language="ILAsm" Value=".property instance class System.Threading.CancellationTokenSource CancellationTokenSource" />
      <MemberType>Property</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.0.0.0</AssemblyVersion>
        <AssemblyVersion>1.1.0.0</AssemblyVersion>
        <AssemblyVersion>1.2.0.0</AssemblyVersion>
        <AssemblyVersion>1.3.0.0</AssemblyVersion>
        <AssemblyVersion>1.4.0.0</AssemblyVersion>
        <AssemblyVersion>1.5.0.0</AssemblyVersion>
        <AssemblyVersion>2.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.Threading.CancellationTokenSource</ReturnType>
      </ReturnValue>
      <Docs>
        Gets the CancellationTokenSource.
        <value>
        </value>
        <remarks>Used by inheritors to implement cancellable loads.</remarks>
      </Docs>
    </Member>
    <Member MemberName="FromFile">
      <MemberSignature Language="C#" Value="public static Xamarin.Forms.ImageSource FromFile (string file);" />
      <MemberSignature Language="ILAsm" Value=".method public static hidebysig class Xamarin.Forms.ImageSource FromFile(string file) cil managed" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.0.0.0</AssemblyVersion>
        <AssemblyVersion>1.1.0.0</AssemblyVersion>
        <AssemblyVersion>1.2.0.0</AssemblyVersion>
        <AssemblyVersion>1.3.0.0</AssemblyVersion>
        <AssemblyVersion>1.4.0.0</AssemblyVersion>
        <AssemblyVersion>1.5.0.0</AssemblyVersion>
        <AssemblyVersion>2.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>Xamarin.Forms.ImageSource</ReturnType>
      </ReturnValue>
      <Parameters>
        <Parameter Name="file" Type="System.String" />
      </Parameters>
      <Docs>
        <param name="file">The name of a file that contains a valid image.</param>
        Returns a new <see cref="T:Xamarin.Forms.FileImageSource" /> that reads from <paramref name="file" />.
        <returns>To be added.</returns>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="FromResource">
      <MemberSignature Language="C#" Value="public static Xamarin.Forms.ImageSource FromResource (string resource);" />
      <MemberSignature Language="ILAsm" Value=".method public static hidebysig class Xamarin.Forms.ImageSource FromResource(string resource) cil managed" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.0.0.0</AssemblyVersion>
        <AssemblyVersion>1.1.0.0</AssemblyVersion>
        <AssemblyVersion>1.2.0.0</AssemblyVersion>
        <AssemblyVersion>1.3.0.0</AssemblyVersion>
        <AssemblyVersion>1.4.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>Xamarin.Forms.ImageSource</ReturnType>
      </ReturnValue>
      <Parameters>
        <Parameter Name="resource" Type="System.String" />
      </Parameters>
      <Docs>
        <param name="resource">A string representing the id of the EmbeddedResource to load.</param>
        Creates an ImageSource for an EmbeddedResource included in the Assembly from which the call to FromResource is made.
        <returns>A newly created ImageSource.</returns>
        <remarks>
        </remarks>
      </Docs>
    </Member>
    <Member MemberName="FromResource">
      <MemberSignature Language="C#" Value="public static Xamarin.Forms.ImageSource FromResource (string resource, System.Reflection.Assembly sourceAssembly = null);" />
      <MemberSignature Language="ILAsm" Value=".method public static hidebysig class Xamarin.Forms.ImageSource FromResource(string resource, class System.Reflection.Assembly sourceAssembly) cil managed" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.5.0.0</AssemblyVersion>
        <AssemblyVersion>2.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>Xamarin.Forms.ImageSource</ReturnType>
      </ReturnValue>
      <Parameters>
        <Parameter Name="resource" Type="System.String" />
        <Parameter Name="sourceAssembly" Type="System.Reflection.Assembly" />
      </Parameters>
      <Docs>
        <param name="resource">The name of a valid image resource in <paramref name="sourceAssembly" />.</param>
        <param name="sourceAssembly">The source assembly in which to search for the image.</param>
        Creates a <see cref="T:Xamarin.Forms.ImageSource" /> from the specified resource in the specified source assembly.
        <returns>To be added.</returns>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="FromResource">
      <MemberSignature Language="C#" Value="public static Xamarin.Forms.ImageSource FromResource (string resource, Type resolvingType);" />
      <MemberSignature Language="ILAsm" Value=".method public static hidebysig class Xamarin.Forms.ImageSource FromResource(string resource, class System.Type resolvingType) cil managed" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.5.0.0</AssemblyVersion>
        <AssemblyVersion>2.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>Xamarin.Forms.ImageSource</ReturnType>
      </ReturnValue>
      <Parameters>
        <Parameter Name="resource" Type="System.String" />
        <Parameter Name="resolvingType" Type="System.Type" />
      </Parameters>
      <Docs>
        <param name="resource">The name of a valid image resource in the assembly to which <paramref name="resolvingType" /> belongs.</param>
        <param name="resolvingType">A type from the assembly in which to look up the image resource with <paramref name="resource" />.</param>
        Creates a <see cref="T:Xamarin.Forms.ImageSource" /> from the specified resource in the specified source assembly.
        <returns>To be added.</returns>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="FromStream">
      <MemberSignature Language="C#" Value="public static Xamarin.Forms.ImageSource FromStream (Func<System.IO.Stream> stream);" />
      <MemberSignature Language="ILAsm" Value=".method public static hidebysig class Xamarin.Forms.ImageSource FromStream(class System.Func`1<class System.IO.Stream> stream) cil managed" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.0.0.0</AssemblyVersion>
        <AssemblyVersion>1.1.0.0</AssemblyVersion>
        <AssemblyVersion>1.2.0.0</AssemblyVersion>
        <AssemblyVersion>1.3.0.0</AssemblyVersion>
        <AssemblyVersion>1.4.0.0</AssemblyVersion>
        <AssemblyVersion>1.5.0.0</AssemblyVersion>
        <AssemblyVersion>2.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>Xamarin.Forms.ImageSource</ReturnType>
      </ReturnValue>
      <Parameters>
        <Parameter Name="stream" Type="System.Func<System.IO.Stream>" />
      </Parameters>
      <Docs>
        <param name="stream">A stream that supplies image data.</param>
        Returns a new <see cref="T:Xamarin.Forms.StreamImageSource" /> that reads from <paramref name="stream" />.
        <returns>To be added.</returns>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="FromUri">
      <MemberSignature Language="C#" Value="public static Xamarin.Forms.ImageSource FromUri (Uri uri);" />
      <MemberSignature Language="ILAsm" Value=".method public static hidebysig class Xamarin.Forms.ImageSource FromUri(class System.Uri uri) cil managed" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.0.0.0</AssemblyVersion>
        <AssemblyVersion>1.1.0.0</AssemblyVersion>
        <AssemblyVersion>1.2.0.0</AssemblyVersion>
        <AssemblyVersion>1.3.0.0</AssemblyVersion>
        <AssemblyVersion>1.4.0.0</AssemblyVersion>
        <AssemblyVersion>1.5.0.0</AssemblyVersion>
        <AssemblyVersion>2.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>Xamarin.Forms.ImageSource</ReturnType>
      </ReturnValue>
      <Parameters>
        <Parameter Name="uri" Type="System.Uri" />
      </Parameters>
      <Docs>
        <param name="uri">A URI that identifies a valid image.</param>
        Returns a new <see cref="T:Xamarin.Forms.UriImageSource" /> that reads from <paramref name="uri" />.
        <returns>To be added.</returns>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="OnLoadingCompleted">
      <MemberSignature Language="C#" Value="protected void OnLoadingCompleted (bool cancelled);" />
      <MemberSignature Language="ILAsm" Value=".method familyhidebysig instance void OnLoadingCompleted(bool cancelled) cil managed" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.0.0.0</AssemblyVersion>
        <AssemblyVersion>1.1.0.0</AssemblyVersion>
        <AssemblyVersion>1.2.0.0</AssemblyVersion>
        <AssemblyVersion>1.3.0.0</AssemblyVersion>
        <AssemblyVersion>1.4.0.0</AssemblyVersion>
        <AssemblyVersion>1.5.0.0</AssemblyVersion>
        <AssemblyVersion>2.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.Void</ReturnType>
      </ReturnValue>
      <Parameters>
        <Parameter Name="cancelled" Type="System.Boolean" />
      </Parameters>
      <Docs>
        <param name="cancelled">A bool indicating if the source was cancelled.</param>
        Called by inheritors to indicate the end of the loading of the source.
        <remarks>OnLoadingCompleted should follow a OnLoadingStarted.</remarks>
      </Docs>
    </Member>
    <Member MemberName="OnLoadingStarted">
      <MemberSignature Language="C#" Value="protected void OnLoadingStarted ();" />
      <MemberSignature Language="ILAsm" Value=".method familyhidebysig instance void OnLoadingStarted() cil managed" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.0.0.0</AssemblyVersion>
        <AssemblyVersion>1.1.0.0</AssemblyVersion>
        <AssemblyVersion>1.2.0.0</AssemblyVersion>
        <AssemblyVersion>1.3.0.0</AssemblyVersion>
        <AssemblyVersion>1.4.0.0</AssemblyVersion>
        <AssemblyVersion>1.5.0.0</AssemblyVersion>
        <AssemblyVersion>2.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.Void</ReturnType>
      </ReturnValue>
      <Parameters />
      <Docs>
        Called by inheritors to indicate the beginning of a loading operation.
        <remarks>OnLoadingCompleted should follow a OnLoadingStarted.</remarks>
      </Docs>
    </Member>
    <Member MemberName="OnSourceChanged">
      <MemberSignature Language="C#" Value="protected void OnSourceChanged ();" />
      <MemberSignature Language="ILAsm" Value=".method familyhidebysig instance void OnSourceChanged() cil managed" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.0.0.0</AssemblyVersion>
        <AssemblyVersion>1.1.0.0</AssemblyVersion>
        <AssemblyVersion>1.2.0.0</AssemblyVersion>
        <AssemblyVersion>1.3.0.0</AssemblyVersion>
        <AssemblyVersion>1.4.0.0</AssemblyVersion>
        <AssemblyVersion>1.5.0.0</AssemblyVersion>
        <AssemblyVersion>2.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.Void</ReturnType>
      </ReturnValue>
      <Parameters />
      <Docs>
        Called by inheritors to indicate that the source changed..
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="op_Implicit">
      <MemberSignature Language="C#" Value="public static Xamarin.Forms.ImageSource op_Implicit (string source);" />
      <MemberSignature Language="ILAsm" Value=".method public static hidebysig specialname class Xamarin.Forms.ImageSource op_Implicit(string source) cil managed" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.0.0.0</AssemblyVersion>
        <AssemblyVersion>1.1.0.0</AssemblyVersion>
        <AssemblyVersion>1.2.0.0</AssemblyVersion>
        <AssemblyVersion>1.3.0.0</AssemblyVersion>
        <AssemblyVersion>1.4.0.0</AssemblyVersion>
        <AssemblyVersion>1.5.0.0</AssemblyVersion>
        <AssemblyVersion>2.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>Xamarin.Forms.ImageSource</ReturnType>
      </ReturnValue>
      <Parameters>
        <Parameter Name="source" Type="System.String" />
      </Parameters>
      <Docs>
        <param name="source">A string that represents an image location.</param>
        Allows implicit casting from a string that represents an absolute URI.
        <returns>To be added.</returns>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="op_Implicit">
      <MemberSignature Language="C#" Value="public static Xamarin.Forms.ImageSource op_Implicit (Uri uri);" />
      <MemberSignature Language="ILAsm" Value=".method public static hidebysig specialname class Xamarin.Forms.ImageSource op_Implicit(class System.Uri uri) cil managed" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.0.0.0</AssemblyVersion>
        <AssemblyVersion>1.1.0.0</AssemblyVersion>
        <AssemblyVersion>1.2.0.0</AssemblyVersion>
        <AssemblyVersion>1.3.0.0</AssemblyVersion>
        <AssemblyVersion>1.4.0.0</AssemblyVersion>
        <AssemblyVersion>1.5.0.0</AssemblyVersion>
        <AssemblyVersion>2.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>Xamarin.Forms.ImageSource</ReturnType>
      </ReturnValue>
      <Parameters>
        <Parameter Name="uri" Type="System.Uri" />
      </Parameters>
      <Docs>
        <param name="uri">A absolute URI that specifies an image location.</param>
        Allows implicit casting from <see cref="T:System.Uri" /> objects that were created with an absolute URI.
        <returns>To be added.</returns>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="Xamarin.Forms.IElement.Parent">
      <MemberSignature Language="C#" Value="Xamarin.Forms.Element Xamarin.Forms.IElement.Parent { get; set; }" />
      <MemberSignature Language="ILAsm" Value=".property instance class Xamarin.Forms.Element Xamarin.Forms.IElement.Parent" />
      <MemberType>Property</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.0.0.0</AssemblyVersion>
        <AssemblyVersion>1.1.0.0</AssemblyVersion>
        <AssemblyVersion>1.2.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>Xamarin.Forms.Element</ReturnType>
      </ReturnValue>
      <Docs>
        Gets or sets the element to which this <see cref="T:Xamarin.Forms.ImageSource" /> object belongs.
        <value>To be added.</value>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="Xamarin.Forms.IElement.XamlParent">
      <MemberSignature Language="C#" Value="WeakReference<Xamarin.Forms.Element> Xamarin.Forms.IElement.XamlParent { get; set; }" />
      <MemberSignature Language="ILAsm" Value=".property instance class System.WeakReference`1<class Xamarin.Forms.Element> Xamarin.Forms.IElement.XamlParent" />
      <MemberType>Property</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.0.0.0</AssemblyVersion>
        <AssemblyVersion>1.1.0.0</AssemblyVersion>
        <AssemblyVersion>1.2.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.WeakReference<Xamarin.Forms.Element></ReturnType>
      </ReturnValue>
      <Docs>
        Gets or sets a weak reference to the parent of this <see cref="T:Xamarin.Forms.ImageSource" /> object.
        <value>To be added.</value>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
  </Members>
</Type>


text:
package org.rustlang.oxide.text;

import org.eclipse.jface.text.rules.IWordDetector;

/**
 * TODO: Document class.
 */
public class EmptyCommentDetector implements IWordDetector {
    EmptyCommentDetector() {
    }

    @Override
    public boolean isWordStart(final char c) {
        return c == '/';
    }

    @Override
    public boolean isWordPart(final char c) {
        return c == '*' || c == '/';
    }
}


text:
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'rspec'
require 'ldap-binder'
# Uncomment this line if you're using pry-plus
# require 'pry-rescue/rspec'

# Requires supporting files with custom matchers and macros, etc,
# in ./support/ and its subdirectories.
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f}

RSpec.configure do |config|
  config.mock_with :rspec

end


text:
package org.jboss.hal.db;

import jsinterop.annotations.JsOverlay;
import jsinterop.annotations.JsType;
import jsinterop.base.Js;
import jsinterop.base.JsPropertyMap;

import static jsinterop.annotations.JsPackage.GLOBAL;
import static org.jboss.hal.resources.UIConstants.OBJECT;

@JsType(isNative = true, namespace = GLOBAL, name = OBJECT)
public interface Document extends JsPropertyMap<Object> {

    @JsOverlay
    static Document of(String id) {
        Document document = Js.cast(JsPropertyMap.of());
        document.set("_id", id);
        return document;
    }

    @JsOverlay
    default String getId() {
        return getAny("_id").asString();
    }
}


text:
<?php

/**
 * Class of creation database driver class.
 *
 * @package   Tsukiyo
 * @author    Satoshi Nishimura <nishim314@gmail.com>
 */
class Tsukiyo_Driver_Factory
{
    static private $dbs = array();

    static public function factory($dsn){
        // If same dsn, return same object.
        if (isset(self::$dbs[$dsn]))
            return self::$dbs[$dsn];

        list($driver, $other) = explode(':', $dsn, 2);

        $driverFile = '';
        switch ($driver){
        case 'pgsql':
            $driverFile = 'Pgsql.php';
            $driverName = 'Pgsql';
            break;
        case 'sqlite':
            $driverFile = 'Sqlite.php';
            $driverName = 'Sqlite';
            break;
        }

        if (!$driverFile)
            throw new Tsukiyo_Exception('Database Driver not found.');

        $driverFilePath = dirname(__FILE__) . '/' . $driverFile;

        if (!file_exists($driverFilePath))
            throw new Exception('Database Driver File not found.');

        $className = preg_replace('/Factory$/', '', __CLASS__) . $driverName;
        require_once $driverFilePath;
        self::$dbs[$dsn] = new $className($dsn);
        return self::$dbs[$dsn];
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace binance_dotnet.enums
{
    public enum OrderSides
    {
        BUY,
        SELL
    }
}


text:
<?php

namespace yii\behaviors;

use Yii;
use yii\base\InvalidConfigException;
use yii\db\BaseActiveRecord;
use yii\helpers\ArrayHelper;
use yii\helpers\Inflector;
use yii\validators\UniqueValidator;

/**
 * SluggableBehavior automatically fills the specified attribute with a value that can be used a slug in a URL.
 *
 * Note: This behavior relies on php-intl extension for transliteration. If it is not installed it
 * falls back to replacements defined in [[\yii\helpers\Inflector::$transliteration]].
 *
 * To use SluggableBehavior, insert the following code to your ActiveRecord class:
 *
 * ```php
 * use yii\behaviors\SluggableBehavior;
 *
 * public function behaviors()
 * {
 *     return [
 *         [
 *             'class' => SluggableBehavior::class,
 *             'attribute' => 'title',
 *             // 'slugAttribute' => 'slug',
 *         ],
 *     ];
 * }
 * ```
 *
 * By default, SluggableBehavior will fill the `slug` attribute with a value that can be used a slug in a URL
 * when the associated AR object is being validated.
 *
 * Because attribute values will be set automatically by this behavior, they are usually not user input and should therefore
 * not be validated, i.e. the `slug` attribute should not appear in the [[\yii\base\Model::rules()|rules()]] method of the model.
 *
 * If your attribute name is different, you may configure the [[slugAttribute]] property like the following:
 *
 * ```php
 * public function behaviors()
 * {
 *     return [
 *         [
 *             'class' => SluggableBehavior::class,
 *             'slugAttribute' => 'alias',
 *         ],
 *     ];
 * }
 * ```
 *
 * @author Alexander Kochetov <creocoder@gmail.com>
 * @author Paul Klimov <klimov.paul@gmail.com>
 * @since 2.0
 */
class SluggableBehavior extends AttributeBehavior
{
    /**
     * @var string the attribute that will receive the slug value
     */
    public $slugAttribute = 'slug';
    /**
     * @var string|array|null the attribute or list of attributes whose value will be converted into a slug
     * or `null` meaning that the `$value` property will be used to generate a slug.
     */
    public $attribute;
    /**
     * @var callable|string|null the value that will be used as a slug. This can be an anonymous function
     * or an arbitrary value or null. If the former, the return value of the function will be used as a slug.
     * If `null` then the `$attribute` property will be used to generate a slug.
     * The signature of the function should be as follows,
     *
     * ```php
     * function ($event)
     * {
     *     // return slug
     * }
     * ```
     */
    public $value;
    /**
     * @var bool whether to generate a new slug if it has already been generated before.
     * If true, the behavior will not generate a new slug even if [[attribute]] is changed.
     * @since 2.0.2
     */
    public $immutable = false;
    /**
     * @var bool whether to ensure generated slug value to be unique among owner class records.
     * If enabled behavior will validate slug uniqueness automatically. If validation fails it will attempt
     * generating unique slug value from based one until success.
     */
    public $ensureUnique = false;
    /**
     * @var bool whether to skip slug generation if [[attribute]] is null or an empty string.
     * If true, the behaviour will not generate a new slug if [[attribute]] is null or an empty string.
     * @since 2.0.13
     */
    public $skipOnEmpty = false;
    /**
     * @var array configuration for slug uniqueness validator. Parameter 'class' may be omitted - by default
     * [[UniqueValidator]] will be used.
     * @see UniqueValidator
     */
    public $uniqueValidator = [];
    /**
     * @var callable|null slug unique value generator. It is used in case [[ensureUnique]] enabled and generated
     * slug is not unique. This should be a PHP callable with following signature:
     *
     * ```php
     * function ($baseSlug, $iteration, $model)
     * {
     *     // return uniqueSlug
     * }
     * ```
     *
     * If not set unique slug will be generated adding incrementing suffix to the base slug.
     */
    public $uniqueSlugGenerator;

    /**
     * {@inheritdoc}
     */
    public function init()
    {
        parent::init();

        if (empty($this->attributes)) {
            $this->attributes = [BaseActiveRecord::EVENT_BEFORE_VALIDATE => $this->slugAttribute];
        }

        if ($this->attribute === null && $this->value === null) {
            throw new InvalidConfigException('Either "attribute" or "value" property must be specified.');
        }
    }

    /**
     * {@inheritdoc}
     */
    protected function getValue($event)
    {
        if (!$this->isNewSlugNeeded()) {
            return $this->owner->{$this->slugAttribute};
        }

        if ($this->attribute !== null) {
            $slugParts = [];
            foreach ((array) $this->attribute as $attribute) {
                $part = ArrayHelper::getValue($this->owner, $attribute);
                if ($this->skipOnEmpty && $this->isEmpty($part)) {
                    return $this->owner->{$this->slugAttribute};
                }
                $slugParts[] = $part;
            }
            $slug = $this->generateSlug($slugParts);
        } else {
            $slug = parent::getValue($event);
        }

        return $this->ensureUnique ? $this->makeUnique($slug) : $slug;
    }

    /**
     * Checks whether the new slug generation is needed
     * This method is called by [[getValue]] to check whether the new slug generation is needed.
     * You may override it to customize checking.
     * @return bool
     * @since 2.0.7
     */
    protected function isNewSlugNeeded()
    {
        if (empty($this->owner->{$this->slugAttribute})) {
            return true;
        }

        if ($this->immutable) {
            return false;
        }

        if ($this->attribute === null) {
            return true;
        }

        foreach ((array) $this->attribute as $attribute) {
            if ($this->owner->isAttributeChanged($attribute)) {
                return true;
            }
        }

        return false;
    }

    /**
     * This method is called by [[getValue]] to generate the slug.
     * You may override it to customize slug generation.
     * The default implementation calls [[\yii\helpers\Inflector::slug()]] on the input strings
     * concatenated by dashes (`-`).
     * @param array $slugParts an array of strings that should be concatenated and converted to generate the slug value.
     * @return string the conversion result.
     */
    protected function generateSlug($slugParts)
    {
        return Inflector::slug(implode('-', $slugParts));
    }

    /**
     * This method is called by [[getValue]] when [[ensureUnique]] is true to generate the unique slug.
     * Calls [[generateUniqueSlug]] until generated slug is unique and returns it.
     * @param string $slug basic slug value
     * @return string unique slug
     * @see getValue
     * @see generateUniqueSlug
     * @since 2.0.7
     */
    protected function makeUnique($slug)
    {
        $uniqueSlug = $slug;
        $iteration = 0;
        while (!$this->validateSlug($uniqueSlug)) {
            $iteration++;
            $uniqueSlug = $this->generateUniqueSlug($slug, $iteration);
        }

        return $uniqueSlug;
    }

    /**
     * Checks if given slug value is unique.
     * @param string $slug slug value
     * @return bool whether slug is unique.
     */
    protected function validateSlug($slug)
    {
        /* @var $validator UniqueValidator */
        /* @var $model BaseActiveRecord */
        $validator = Yii::createObject(array_merge(
            [
                'class' => UniqueValidator::className(),
            ],
            $this->uniqueValidator
        ));

        $model = clone $this->owner;
        $model->clearErrors();
        $model->{$this->slugAttribute} = $slug;

        $validator->validateAttribute($model, $this->slugAttribute);
        return !$model->hasErrors();
    }

    /**
     * Generates slug using configured callback or increment of iteration.
     * @param string $baseSlug base slug value
     * @param int $iteration iteration number
     * @return string new slug value
     * @throws \yii\base\InvalidConfigException
     */
    protected function generateUniqueSlug($baseSlug, $iteration)
    {
        if (is_callable($this->uniqueSlugGenerator)) {
            return call_user_func($this->uniqueSlugGenerator, $baseSlug, $iteration, $this->owner);
        }

        return $baseSlug . '-' . ($iteration + 1);
    }

    /**
     * Checks if $slugPart is empty string or null.
     *
     * @param string $slugPart One of attributes that is used for slug generation.
     * @return bool whether $slugPart empty or not.
     * @since 2.0.13
     */
    protected function isEmpty($slugPart)
    {
        return $slugPart === null || $slugPart === '';
    }
}


text:
The following document describes the IAM policy required for creating
resources in AWS.

## Existing VPC

When provisioning nodes in a pre-existing VPC, the following policy is required
for the provisioner:

```
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Stmt1503669830000",
            "Effect": "Allow",
            "Action": [
                "ec2:CreateTags",
                "ec2:DescribeInstances",
                "ec2:ModifyInstanceAttribute",
                "ec2:RunInstances",
                "ec2:TerminateInstances"
            ],
            "Resource": [
                "*"
            ]
        }
    ]
}
```

## New VPC

When desired, the provisioner is also capable of creating a new VPC, and configuring
all the related resources that are required for the cluster. In this scenario,
the following policy is required:

```
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Stmt1503669830000",
            "Effect": "Allow",
            "Action": [
                "ec2:DescribeKeyPairs",
                "ec2:CreateKeyPair",
                "ec2:DescribeVpcs",
                "ec2:CreateVpc",
                "ec2:CreateTags",
                "ec2:DescribeSubnets",
                "ec2:CreateSubnet",
                "ec2:AttachInternetGateway",
                "ec2:CreateInternetGateway",
                "ec2:DescribeInternetGateways",
                "ec2:AssociateRouteTable",
                "ec2:CreateRoute",
                "ec2:DescribeRouteTables",
                "ec2:AuthorizeSecurityGroupIngress",
                "ec2:DescribeSecurityGroups",
                "ec2:DescribeInstances",
                "ec2:ModifyInstanceAttribute",
                "ec2:RunInstances",
                "ec2:TerminateInstances"
            ],
            "Resource": [
                "*"
            ]
        }
    ]
}
```


text:
package org.fugerit.java.core.doc.filter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.fugerit.java.core.cfg.ConfigException;
import org.w3c.dom.Element;

public interface DocTypeHandler {

	public String getType();

	public String getExtension();

	public void handleDocTypeInit( HttpServletRequest request, HttpServletResponse response, DocContext docContext ) throws Exception;

	public void handleDocType( HttpServletRequest request, HttpServletResponse response, DocContext docContext ) throws Exception;

	public void handleDocTypePost( HttpServletRequest request, HttpServletResponse response, DocContext docContext ) throws Exception;

	public void init( Element config ) throws ConfigException;

}


text:
`m2j.js` is used to read a folder of Markdown files, pulling out the YAML front matter from each, and saving it all as a JSON object.

This is especially useful if you have a folder full of Markdown files
that you want scanned and processed into a singl JSON file, which can
then be consumed by Angular on the client, cached in a Node server, or
saved in a nosql database.

In addition to moving the YAML to JSON, a few extra elements are created:

-  `iso8601` [formatted][1] from `date` using [Moment.js][2]
-  `preview` is first 70 or so characters of the actual raw markdown content, with ellipses at the end
-  `basename` is the filename without the path or extension

_Example_

```
% m2.js --help

  Usage: m2j [options] <files>

  Options:

    -h, --help               output usage information
    -V, --version            output the version number
    -w --width <int>         max width of preview text [70]
    -p --pretty              format JSON with newlines
    -o --outfile <filename>  filename to save json to [output.json]

% m2j.js lottery.ms
```

**lottery.md**

```
---
title: The Lottery Ticket
author: Anton C.
date: "2013-03-15 15:00"
template: article.jade
tags:
  - Fiction
  - Russian

---

Ivan Dmitritch, a middle-class man who lived with his family on an income of twelve hundred a year and was very well satisfied with his lot, sat down on the sofa after supper and began reading the newspaper.

```

**output**

```
{
  "files": [
    {
      "title": "The Lottery Ticket",
      "author": "Anton C.",
      "date": "1893-04-01",
      "template": "article.jade",
      "tags": [
        "Fiction",
        "Russian"
      ],
      "preview": "Ivan Dmitritch, a middle-class man who lived with his family on an …",
      "iso8601Date": "1893-04-01T00:00:00-07:00",
      "basename": "lottery.md"
    }
  ]
}
```

[1]: http://en.wikipedia.org/wiki/ISO_8601
[2]: http://momentjs.com/docs/#/parsing/string/


text:
package restlib.server.bio;

import restlib.ContentInfo;
import restlib.Request;
import restlib.Response;
import restlib.bio.OutputStreamSerializer;
import restlib.bio.OutputStreamSerializers;
import restlib.data.Charset;
import restlib.data.MediaRange;
import restlib.data.MediaRanges;
import restlib.data.Preference;

import com.google.common.base.Preconditions;

public final class OutputStreamSerializerSuppliers {
    public static final OutputStreamSerializerSupplier STRING_AS_PLAIN_TEXT_SERIALIZER_SUPPLIER = stringSerializerSupplier(MediaRanges.TEXT_PLAIN);

    public static OutputStreamSerializerSupplier stringSerializerSupplier(
            final MediaRange mediaRange) {
        return new OutputStreamSerializerSupplier() {
            @Override
            public OutputStreamSerializer get(final Request request,
                    final Response response) {
                Preconditions.checkNotNull(request);
                Preconditions.checkNotNull(response);

                final Charset charset =
                        Preference.<Charset> bestMatch(
                                request.preferences().acceptedCharsets(),
                                Charset.available()).or(Charset.UTF_8);
                final ContentInfo contentInfo =
                        ContentInfo.builder()
                            .setMediaRange(mediaRange.withCharset(charset)).build();
                return OutputStreamSerializers.stringSerializer(
                        response.entity().get().toString(), contentInfo);
            }

            @Override
            public MediaRange mediaRange() {
                return mediaRange;
            }
        };
    }

    private OutputStreamSerializerSuppliers() {}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ext.Net;
using Newtonsoft.Json;

using CCC.UTILS.Libs;
using CCC.UTILS.Helpers;
using LyncBillingUI.Helpers;
using LyncBillingUI.Helpers.Account;
using LyncBillingBase.DataModels;

namespace LyncBillingUI.Pages.SiteAdministration
{
    public partial class TelephonyRates : System.Web.UI.Page
    {
        private string sipAccount = string.Empty;
        private static List<Site> usersSites;
        private List<Gateway> gateways = new List<Gateway>();
        private List<Gateway> filteredGateways = new List<Gateway>();

        // This actually takes a copy of the current session for some uses on the frontend.
        public UserSession CurrentSession { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            //
            // If the user is not loggedin, redirect to Login page.
            if (HttpContext.Current.Session == null || HttpContext.Current.Session.Contents["UserData"] == null)
            {
                string RedirectTo = String.Format(@"{0}/Site/Administration/Dashboard", Global.APPLICATION_URL);
                string Url = String.Format(@"{0}/Login?RedirectTo={1}", Global.APPLICATION_URL, RedirectTo);
                Response.Redirect(Url);
            }
            else
            {
                CurrentSession = ((UserSession)HttpContext.Current.Session.Contents["UserData"]);

                if (CurrentSession.ActiveRoleName != Functions.SiteAdminRoleName)
                {
                    string url = String.Format(@"{0}/Authorize?access={1}", Global.APPLICATION_URL, Functions.SiteAdminRoleName);
                    Response.Redirect(url);
                }
            }

            sipAccount = CurrentSession.GetEffectiveSipAccount();

            // Get User Sites
            GetUserSitesDate();
        }

        private void GetUserSitesDate()
        {
            if (!Ext.Net.X.IsAjaxRequest)
            {
                usersSites = Global.DATABASE.SystemRoles.GetSitesByRoles(CurrentSession.SystemRoles, Functions.SiteAdminRoleName);
            }
        }

        public List<Gateway> GetGateways(int siteID)
        {
            gateways = Global.DATABASE.Gateways.GetAll().ToList();

            //Get Related Gateways for that specific site
            List<GatewayInfo> gatewaysDetails = Global.DATABASE.GatewaysInfo.GetAll().Where(item => item.SiteId == siteID).ToList();

            foreach (int id in gatewaysDetails.Select(item => item.GatewayId))
            {
                filteredGateways.Add(gateways.First(item => item.Id == id));
            }

            return filteredGateways;
        }

        protected void FilterGatewaysBySiteStore_Load(object sender, EventArgs e)
        {
            if (!Ext.Net.X.IsAjaxRequest)
            {
                FilterGatewaysBySite.GetStore().DataSource = usersSites;
                FilterGatewaysBySite.GetStore().DataBind();
            }
        }

        protected void GetGatewaysForSite(object sender, DirectEventArgs e)
        {
            FilterRatesByGateway.Clear();
            FilterRatesByGateway.ReadOnly = false;

            if (FilterGatewaysBySite.SelectedItem != null && !string.IsNullOrEmpty(FilterGatewaysBySite.SelectedItem.Value))
            {
                List<Gateway> gateways = GetGateways(Convert.ToInt32(FilterGatewaysBySite.SelectedItem.Value));

                FilterRatesByGateway.Disabled = false;
                FilterRatesByGateway.GetStore().DataSource = gateways;
                FilterRatesByGateway.GetStore().DataBind();

                ManageRatesGrid.GetStore().RemoveAll();

                if (gateways.Count == 1)
                {
                    FilterRatesByGateway.SetValueAndFireSelect(gateways[0].Id);
                    FilterRatesByGateway.ReadOnly = true;
                }
                else
                {
                    FilterRatesByGateway.ReadOnly = false;
                }
            }
        }

        public string GetRatesTableName(int siteID)
        {
            if (gateways.Count < 1)
                gateways = GetGateways(siteID);

            string rateTable = string.Empty;

            if (FilterRatesByGateway.SelectedItem.Index == -1)
            {
                return rateTable;
            }
            else
            {
                int gatewayID = Convert.ToInt32(FilterRatesByGateway.SelectedItem.Value);
                rateTable = Global.DATABASE.GatewaysRates.GetByGatewayId(gatewayID).First(item => item.EndingDate == DateTime.MinValue).RatesTableName;
                return rateTable;
            }

        }

        protected void GetRates(object sender, DirectEventArgs e)
        {
            int gatewayId = 0;
            List<GatewayRate> gatewayRates = new List<GatewayRate>();

            if (FilterGatewaysBySite.SelectedItem.Index > -1 && FilterRatesByGateway.SelectedItem.Index > -1)
            {
                gatewayId = Convert.ToInt32(FilterRatesByGateway.SelectedItem.Value);

                //Clear Store
                ManageRatesGrid.GetStore().RemoveAll();

                ManageRatesGrid.GetStore().DataSource = Global.DATABASE.Rates.GetInternationalRatesByGatewayId(gatewayId) ?? (new List<RatesInternational>());
                ManageRatesGrid.GetStore().DataBind();
            }
        }

        protected void RejectChanges_DirectEvent(object sender, DirectEventArgs e)
        {
            ManageRatesGrid.GetStore().RejectChanges();
        }

        protected void UpdateEdited_DirectEvent(object sender, DirectEventArgs e)
        {
            int gatewayId = 0;
            string json = e.ExtraParams["Values"];

            //ChangeRecords<Rate> toBeUpdated = new StoreDataHandler(e.ExtraParams["Values"]).BatchObjectData<Rate>();
            ChangeRecords<RatesInternational> toBeUpdated = new StoreDataHandler(e.ExtraParams["Values"]).BatchObjectData<RatesInternational>();

            if (toBeUpdated.Updated.Count > 0)
            {
                gatewayId = Convert.ToInt32(FilterRatesByGateway.SelectedItem.Value);

                foreach (RatesInternational countryRate in toBeUpdated.Updated)
                {
                    //List<DialingPrefixRate> dialingPrefixsRates = DialingPrefixsRates.GetRates(ratesTableName, countryRate.Iso3CountryCode);
                    List<RatesNational> dialingPrefixsRates = Global.DATABASE.Rates.GetNationalRatesForCountryByGatewayId(gatewayId, countryRate.Iso3CountryCode).ToList();

                    //The Rates Table doesnt have this country codes
                    if (dialingPrefixsRates.Where(item => item.RateId == 0).Count() == dialingPrefixsRates.Count())
                    {
                        foreach (RatesNational dialingPrefixRate in dialingPrefixsRates)
                        {
                            if (dialingPrefixRate.TypeOfService.ToLower() == "gsm")
                                dialingPrefixRate.Rate = countryRate.MobileLineRate;
                            else
                                dialingPrefixRate.Rate = countryRate.FixedLineRate;

                            int rateID = Global.DATABASE.Rates.Insert(dialingPrefixRate, gatewayId);
                        }

                        ManageRatesStore.Find("Iso3CountryCode", countryRate.Iso3CountryCode).Commit();
                    }
                    else if (dialingPrefixsRates.Where(item => item.RateId > 0).Count() == dialingPrefixsRates.Count())
                    {
                        foreach (RatesNational dialingPrefixRate in dialingPrefixsRates)
                        {
                            if (dialingPrefixRate.TypeOfService.ToLower() == "gsm" && dialingPrefixRate.Rate != countryRate.MobileLineRate)
                            {
                                dialingPrefixRate.Rate = countryRate.MobileLineRate;
                                Global.DATABASE.Rates.Update(dialingPrefixRate, gatewayId);
                            }
                            else if (dialingPrefixRate.TypeOfService.ToLower() != "gsm" && dialingPrefixRate.Rate != countryRate.FixedLineRate)
                            {
                                dialingPrefixRate.Rate = countryRate.FixedLineRate;
                                Global.DATABASE.Rates.Update(dialingPrefixRate, gatewayId);
                            }
                        }

                        ManageRatesStore.Find("Iso3CountryCode", countryRate.Iso3CountryCode).Commit();
                    }
                    else
                    {
                        // Some needs to be updated and some needs to be inserted
                        foreach (RatesNational dialingPrefixRate in dialingPrefixsRates)
                        {
                            if (dialingPrefixRate.RateId == 0)
                            {
                                if (dialingPrefixRate.TypeOfService.ToLower() == "gsm")
                                {
                                    dialingPrefixRate.Rate = countryRate.MobileLineRate;
                                }
                                else
                                {
                                    dialingPrefixRate.Rate = countryRate.FixedLineRate;
                                }

                                int rateID = Global.DATABASE.Rates.Insert(dialingPrefixRate, gatewayId);
                            }
                            else if (dialingPrefixRate.RateId != 0)
                            {
                                if (dialingPrefixRate.TypeOfService.ToLower() == "gsm" && dialingPrefixRate.Rate != countryRate.MobileLineRate)
                                {
                                    dialingPrefixRate.Rate = countryRate.MobileLineRate;
                                    Global.DATABASE.Rates.Update(dialingPrefixRate, gatewayId);
                                }
                                else if (dialingPrefixRate.TypeOfService.ToLower() != "gsm" && dialingPrefixRate.Rate != countryRate.FixedLineRate)
                                {
                                    dialingPrefixRate.Rate = countryRate.FixedLineRate;
                                    Global.DATABASE.Rates.Update(dialingPrefixRate, gatewayId);
                                }
                            }
                            else
                            {
                                // Catcher should be implemented
                            }
                        }

                        ManageRatesStore.Find("Iso3CountryCode", countryRate.Iso3CountryCode).Commit();
                    }
                }
            }

            if (toBeUpdated.Deleted.Count > 0)
            {

            }
        }

    }

}


text:
import epub, os
from genshi.template import TemplateLoader, MarkupTemplate
from epub import modulepath

class Section:

    def __init__(self):
        self.title = ''
        self.subsections = []
        self.css = ''
        self.text = []
        self.templateFileName = os.path.join(modulepath, 'templates/ez-section-mod.html')

class Book:

    def __init__(self):
        self.impl = epub.EpubBook()
        self.title = ''
        self.authors = []
        self.cover = ''
        self.lang = 'en-US'
        self.sections = []
	self.makefunc = {'plain': self.__addSection, 'html': self.__addHtmlSection}
        self.templateLoader = TemplateLoader('templates')
	if not os.path.exists(os.path.join('/tmp' , 'epub-builder')):
            os.makedirs(os.path.join('/tmp' , 'epub-builder'))

    def __addHtmlSection(self, section, id, depth):
        if depth > 0:
	    content = ''
	    for text in section.text:
	 	content = content + text
            urls = self.impl.downloadHtmlImages(content)
            content = self.impl.remoteToLocalImageUrls(urls, content)
            stream = MarkupTemplate("""<html xmlns="http://www.w3.org/1999/xhtml"
    					xmlns:py="http://genshi.edgewall.org/">
					<head>
					  <title>${section.title}</title>
					  <style type="text/css">
						h1 { text-align: center; }
						${section.css}
					  </style>
					</head>
					<body>
					  <h1>${section.title}</h1>
					  """ + content + """
					</body>
					</html>""").generate(section = section)
            html = stream.render('xhtml', doctype = 'xhtml11', drop_xml_decl = False)
            item = self.impl.addHtml('', '%s.html' % id, html)
            self.impl.addSpineItem(item)
            self.impl.addTocMapNode(item.destPath, section.title, depth)
            id += '.'
        if len(section.subsections) > 0:
            for i, subsection in enumerate(section.subsections):
                 self.__addHtmlSection(subsection, id + str(i + 1), depth + 1)

    def __addSection(self, section, id, depth):
        if depth > 0:
            stream = self.templateLoader.load(section.templateFileName).generate(section = section)
            html = stream.render('xhtml', doctype = 'xhtml11', drop_xml_decl = False)
            item = self.impl.addHtml('', '%s.html' % id, html)
            self.impl.addSpineItem(item)
            self.impl.addTocMapNode(item.destPath, section.title, depth)
            id += '.'
        if len(section.subsections) > 0:
            for i, subsection in enumerate(section.subsections):
                self.__addSection(subsection, id + str(i + 1), depth + 1)

    def make(self, outputDir, type):

        outputFile = outputDir + '.epub'

        self.impl.setTitle(self.title)
        self.impl.setLang(self.lang)
        for author in self.authors:
            self.impl.addCreator(author)
        if self.cover:
            self.impl.addCover(self.cover)
        self.impl.addTitlePage()
        self.impl.addTocPage()
        root = Section()
        root.subsections = self.sections
        self.makefunc[type](root, 's', 0)
        self.impl.createBook()
        self.impl.createArchive(outputFile)


text:
module Lasca.Type where

import Data.List
import Data.String
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as Encoding
import qualified Data.ByteString as BS
import qualified Data.ByteString.Short as SBS
import Data.Text.Prettyprint.Doc

data Name = Name Text | NS Name Name deriving (Eq, Ord)

instance IsString Name where
    fromString = Name . T.pack

instance Show Name where
    show n = case n of
        Name s -> T.unpack s
        NS prefix n -> show prefix ++ "_" ++ show n

nameToText n = case n of
    Name n -> n
    NS prefix n -> T.append (nameToText prefix) (T.cons '_' (nameToText n))

qualify mod name = if mod == defaultModuleQName then name else NS mod name

qnameToString n = show n

qname = Name

textToSBS :: Text -> SBS.ShortByteString
textToSBS = SBS.toShort . Encoding.encodeUtf8

nameToSBS :: Name -> SBS.ShortByteString
nameToSBS = textToSBS . nameToText

nameToBS :: Name -> BS.ByteString
nameToBS = Encoding.encodeUtf8 . nameToText

nameToList (Name n) = [n]
nameToList (NS prefix n) = nameToList prefix ++ nameToList n

defaultModuleName = "Main"
defaultModuleQName = Name defaultModuleName

newtype TVar = TV Text
  deriving (Eq, Ord)

instance Show TVar where
  show (TV s) = T.unpack s

data Type
  = TVar TVar
  | TypeIdent Name
  | TypeFunc Type Type
  | TypeApply Type [Type]
  | Forall [TVar] Type
  deriving (Eq, Ord)

instance Show Type where
  show (TVar (TV n)) = T.unpack n
  show (TypeIdent s) = show s
  show (TypeFunc l r) = "(" ++ show l ++ " -> " ++ show r ++ ")"
  show (TypeApply t args) = "(" ++ show t ++ foldl (\acc a -> acc ++ " " ++ show a) "" args ++ ")"
  show (Forall targs t) = "∀(" ++ intercalate "," (map show targs) ++ ") => " ++ show t

instance Pretty Name where
    pretty n = case n of
        Name s -> pretty s
        NS prefix n -> pretty prefix <+> "_" <+> pretty n

instance Pretty TVar where
  pretty (TV s) = pretty s

instance Pretty Type where
    pretty t = case t of
        (TVar (TV n)) -> pretty n
        (TypeIdent s) -> pretty s
        (TypeFunc l r) -> parens $ pretty l <+> "->" <+> pretty r
        (TypeApply t args) -> parens $pretty t <+> foldl (\acc a -> acc <+> pretty a) "" args
        (Forall targs t) -> "∀" <> parens (hsep (punctuate comma (map pretty targs))) <+> "=>" <+> pretty t

typeName tpe = case tpe of
    TypeIdent n -> n
    TypeApply t _ -> typeName t
    Forall _ t -> typeName t
    _ -> error $ "Should not happen. Type name can't be " ++ show tpe

infixr `TypeFunc`

pattern TypeByte     = TypeIdent "Byte"
pattern TypeInt      = TypeIdent "Int"
pattern TypeInt16    = TypeIdent "Int16"
pattern TypeInt32    = TypeIdent "Int32"
pattern TypeFloat    = TypeIdent "Float"
pattern TypeBool     = TypeIdent "Bool"
pattern TypeAny      = TypeIdent "Any"
pattern TypeString   = TypeIdent "String"
pattern TypeUnit     = TypeIdent "Unit"
pattern TypeArray t  = TypeApply (TypeIdent "Array") [t]
pattern TypeByteArray t  = TypeApply (TypeIdent "ByteArray") [t]
pattern TypeArrayInt = TypeArray TypeInt
pattern TypeRef a    = TypeApply (TypeIdent "Var") [a]

isIntegralType (TypeIdent t) | t `elem` ["Byte", "Int", "Int16", "Int32"] = True
isIntegralType _ = False

isAny (TypeIdent "Any") = True
isAny _ = False

typeToList tpe = reverse $ go tpe []
  where go (TypeFunc a b) acc = go b (a : acc)
        go (Forall tvars tpe) acc = go tpe acc
        go a acc              = a : acc

funcTypeArity this@(TypeFunc a b) = (length $ typeToList this) - 1
funcTypeArity _ = 0


text:
using Microsoft.OData.Edm.Values;

namespace Microsoft.OData.Edm.Expressions
{
    /// <summary>
    /// Represents an EDM datetime with offset constant expression.
    /// </summary>
    public interface IEdmDateTimeOffsetConstantExpression : IEdmExpression, IEdmDateTimeOffsetValue
    {
    }
}


text:
use exonum::{
    helpers::{Height, ValidatorId},
    merkledb::BinaryValue,
};

use crate::sandbox::{sandbox_tests_helper::*, supervisor::TxConfig, timestamping_sandbox};

/// - exclude validator from consensus
/// - idea of test is to exclude sandbox validator from consensus
/// - node continues as `full node`
#[test]
fn test_exclude_validator_from_consensus() {
    let sandbox = timestamping_sandbox();
    let sandbox_state = SandboxState::new();

    add_one_height(&sandbox, &sandbox_state);

    let tx_cfg = {
        let mut consensus_cfg = sandbox.cfg();
        consensus_cfg.validator_keys.swap_remove(0);

        TxConfig::create_signed(
            sandbox.public_key(ValidatorId(0)),
            &consensus_cfg.into_bytes(),
            Height(0),
            sandbox.secret_key(ValidatorId(0)),
        )
    };

    add_one_height_with_transactions(&sandbox, &sandbox_state, &[tx_cfg]);
    // node loses validator status
    add_one_height_with_transactions_from_other_validator(&sandbox, &sandbox_state, &[]);
}

// - include validator to consensus
// TODO [ECR-3222]


text:
package org.zstack.header.identity;

import org.zstack.header.vo.ForeignKey;
import org.zstack.header.vo.ForeignKey.ReferenceOption;

import javax.persistence.*;
import java.sql.Timestamp;

@Entity
@Table
public class UserVO {
    @Id
    @Column
    private String uuid;

    @Column
    @ForeignKey(parentEntityClass = AccountVO.class, parentKey = "uuid", onDeleteAction = ReferenceOption.CASCADE)
    private String accountUuid;

    @Column
    private String name;

    @Column
    private String description;

    @Column
    private String password;

    @Column
    private String securityKey;

    @Column
    private String token;

    @Column
    private Timestamp createDate;

    @Column
    private Timestamp lastOpDate;

    @PreUpdate
    private void preUpdate() {
        lastOpDate = null;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getUuid() {
        return uuid;
    }

    public void setUuid(String uuid) {
        this.uuid = uuid;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getAccountUuid() {
        return accountUuid;
    }

    public void setAccountUuid(String accountUuid) {
        this.accountUuid = accountUuid;
    }

    public String getSecurityKey() {
        return securityKey;
    }

    public void setSecurityKey(String securityKey) {
        this.securityKey = securityKey;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public Timestamp getCreateDate() {
        return createDate;
    }

    public void setCreateDate(Timestamp createDate) {
        this.createDate = createDate;
    }

    public Timestamp getLastOpDate() {
        return lastOpDate;
    }

    public void setLastOpDate(Timestamp lastOpDate) {
        this.lastOpDate = lastOpDate;
    }
}


text:
var Promise = require('../Promise');

/**
 * Resolve a promise after a delay
 * @param {number} delay    A delay in milliseconds
 * @returns {Promise} Resolves after given delay
 */
exports.wait = function(delay) {
  return new Promise(function (resolve) {
    setTimeout(resolve, delay);
  });
};

/**
 * Repeat a given asynchronous function a number of times
 * @param {function} fn   A function returning a promise
 * @param {number} times
 * @return {Promise}
 */
exports.repeat = function (fn, times) {
  return new Promise(function (resolve, reject) {
    var count = 0;
    var results = [];

    function recurse() {
      if (count < times) {
        count++;
        fn().then(function (result) {
          results.push(result);
          recurse();
        })
      }
      else {
        resolve(results);
      }
    }

    recurse();
  });
};

/**
 * Repeat an asynchronous callback function whilst
 * @param {function} condition   A function returning true or false
 * @param {function} callback    A callback returning a Promise
 * @returns {Promise}
 */
exports.whilst = function (condition, callback) {
  return new Promise(function (resolve, reject) {
    function recurse() {
      if (condition()) {
        callback().then(function () {
          recurse()
        });
      }
      else {
        resolve();
      }
    }

    recurse();
  });
};


text:
<?php

namespace Oro\Bundle\AsseticBundle\Event;

use Symfony\Component\EventDispatcher\Event;

use Oro\Bundle\AsseticBundle\AssetsConfiguration;

class LoadCssEvent extends Event
{
    /**
     * @var AssetsConfiguration
     */
    protected $assetsConfiguration;

    /**
     * @param AssetsConfiguration $assetsConfiguration
     */
    public function __construct(AssetsConfiguration $assetsConfiguration)
    {
        $this->assetsConfiguration = $assetsConfiguration;
    }

    /**
     * Add CSS files.
     *
     * @param string $group
     * @param array $files
     */
    public function addCss($group, array $files)
    {
        $this->assetsConfiguration->addCss($group, $files);
    }
}


text:
@ECHO OFF

set MCP=%USERPROFILE%\mcp\1.9\dev
set BUILDSRC=%MCP%\src
set CLEANSRC=%MCP%\src-dev

set PROJBASE=%USERPROFILE%\Mod Stuff\MineFactory
set SPRITEFOLDER=MineFactorySprites
set MODNAME=MineFactoryReloaded
set MODVERSION=1.5.0
set ZIPPATH=%USERPROFILE%\Mod Stuff\zip.exe

set SRCBASE=%PROJBASE%\source
set CLIENTSRC=%SRCBASE%\client
set COMMONSRC=%SRCBASE%\common
set SERVERSRC=%SRCBASE%\server

set RELEASEBASE=%PROJBASE%\release
set RELEASECLIENT=%RELEASEBASE%\clienttemp
set RELEASESERVER=%RELEASEBASE%\servertemp

del /s /f /q %BUILDSRC% > NUL
xcopy /y /e /q "%CLEANSRC%" "%BUILDSRC%" > NUL
xcopy /y /e /q "%COMMONSRC%\*" "%BUILDSRC%\minecraft\" > NUL
xcopy /y /e /q "%COMMONSRC%\*" "%BUILDSRC%\minecraft_server\" > NUL
xcopy /y /e /q "%CLIENTSRC%\*" "%BUILDSRC%\minecraft\" > NUL
xcopy /y /e /q "%SERVERSRC%\*" "%BUILDSRC%\minecraft_server\" > NUL

cd %MCP%
runtime\bin\python\python_mcp runtime\recompile.py %*
runtime\bin\python\python_mcp runtime\reobfuscate.py %*

del /s /f /q "%RELEASEBASE%\*.zip" > NUL
del /s /f /q "%RELEASECLIENT%\*" > NUL
del /s /f /q "%RELEASESERVER%\*" > NUL
xcopy /y /e /q "%MCP%\reobf\minecraft\*" "%RELEASECLIENT%\" > NUL
xcopy /y /e /q "%MCP%\reobf\minecraft_server\*" "%RELEASESERVER%\" > NUL

mkdir "%RELEASECLIENT%\%SPRITEFOLDER%\animations"
xcopy /y /e /q "%PROJBASE%\sprites\terrain_0.png" "%RELEASECLIENT%\%SPRITEFOLDER%" > NUL
xcopy /y /e /q "%PROJBASE%\sprites\items_0.png" "%RELEASECLIENT%\%SPRITEFOLDER%" > NUL
xcopy /y /e /q "%PROJBASE%\sprites\animations\*.png" "%RELEASECLIENT%\%SPRITEFOLDER%\animations" > NUL
rmdir "%RELEASECLIENT%\%SPRITEFOLDER%\items"
rmdir "%RELEASECLIENT%\%SPRITEFOLDER%\terrain"
rmdir /S /Q "%RELEASECLIENT%\buildcraft"

mkdir "%RELEASESERVER%\%SPRITEFOLDER%\animations"
xcopy /y /e /q "%PROJBASE%\sprites\terrain_0.png" "%RELEASESERVER%\%SPRITEFOLDER%" > NUL
xcopy /y /e /q "%PROJBASE%\sprites\items_0.png" "%RELEASESERVER%\%SPRITEFOLDER%" > NUL
xcopy /y /e /q "%PROJBASE%\sprites\animations\*.png" "%RELEASESERVER%\%SPRITEFOLDER%\animations" > NUL
rmdir /s /q "%RELEASESERVER%\%SPRITEFOLDER%\items"
rmdir /s /q "%RELEASESERVER%\%SPRITEFOLDER%\terrain"
rmdir /S /Q "%RELEASESERVER%\buildcraft"

cd "%RELEASECLIENT%"
rmdir /s /q net
"%ZIPPATH%" -r -q "%RELEASEBASE%\%MODNAME%_Client_%MODVERSION%.zip" *
cd "%RELEASESERVER%"
rmdir /s /q net
"%ZIPPATH%" -r -q "%RELEASEBASE%\%MODNAME%_Server_%MODVERSION%.zip" *

pause


text:
package sondow.twitter;

import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;

/**
 * Interacts with the twitter API to post tweets or do other twitter actions for a given
 * Twitter account.
 *
 * @author @JoeSondow
 */
public class Tweeter {

    Twitter twitter;

    /**
     * Creates an instance to interact with the Twitter accounts the is set up as the default
     * for this project.
     */
    public Tweeter() {
        this(new ConfigurationBuilder().setTrimUserEnabled(true).build());
    }

    /**
     * Creates an instance to interact with the Twitter account specified by the supplied
     * configuration.
     *
     * @param config the Twitter configuration to use to authenticate
     */
    public Tweeter(Configuration config) {
        twitter = new TwitterFactory(config).getInstance();
    }

    /**
     * Posts a tweet.
     *
     * @param message the content to tweet
     * @return the full tweet object that was created
     */
    public Status tweet(String message) {
        try {
            Status status = twitter.updateStatus(message);
            String msg = "Successfully tweeted message: " + message + " with status " + status;
            System.out.println(msg);
            return status;
        } catch (TwitterException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Retweets a tweet.
     *
     * @param tweetId the id of the tweet, or Status, that we want to retweet
     * @return the full tweet object that was created as a result of retweeting
     */
    public Status retweet(long tweetId) {
        try {
            Status status = twitter.retweetStatus(tweetId);
            System.out.println("Successfully retweeted status " + tweetId + " with status: " + status);
            return status;
        } catch (TwitterException e) {
            e.printStackTrace();
        }
        return null;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <com.cc.custom.uikit.PagerSlidingTabStrip
        android:id="@+id/tx_viewpager_indicator"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:background="@color/TX_CO_WHITE"
        app:pstsShouldExpand="true" />

    <com.cc.custom.uikit.UnScrollViewPager
        android:id="@+id/tx_viewpager_vp"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>


text:
package br.com.delogic.asd.housekeeping;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SpaceHousekeepingJobTest {

    private SpaceHousekeepingJob hk;

    private final Logger logger = LoggerFactory.getLogger(SpaceHousekeepingJobTest.class);

    @Before
    public void clean() {
        File tempDir = new File(getTempDir());
        tempDir.delete();
    }

    @Test
    public void deveExcluirArquivos() throws Exception {
        dadoArquivosEmMB(10, 1);
        dadoHouseKeepingEspacoMB(5);
        quandoExecutarHousekeeping();
        entaoArquivosRemanecentes(5);
        entaoArquivosRemanecente("arquivo.txt5");
        entaoArquivosRemanecente("arquivo.txt6");
        entaoArquivosRemanecente("arquivo.txt7");
        entaoArquivosRemanecente("arquivo.txt8");
        entaoArquivosRemanecente("arquivo.txt9");
    }

    @Test
    public void deveExcluirArquivosSomente1Vez() throws Exception {
        dadoArquivosEmMB(10, 1);
        dadoHouseKeepingEspacoMB(5);
        quandoExecutarHousekeeping();
        quandoExecutarHousekeeping();
        quandoExecutarHousekeeping();
        quandoExecutarHousekeeping();
        quandoExecutarHousekeeping();
        entaoArquivosRemanecentes(5);
        entaoArquivosRemanecente("arquivo.txt5");
        entaoArquivosRemanecente("arquivo.txt6");
        entaoArquivosRemanecente("arquivo.txt7");
        entaoArquivosRemanecente("arquivo.txt8");
        entaoArquivosRemanecente("arquivo.txt9");
    }

    @Test
    public void deveExcluirArquivos1Apenas() throws Exception {
        dadoArquivosEmMB(10, 1);
        dadoHouseKeepingEspacoMB(9);
        quandoExecutarHousekeeping();
        entaoArquivosRemanecentes(9);
        entaoArquivosRemanecente("arquivo.txt1");
        entaoArquivosRemanecente("arquivo.txt2");
        entaoArquivosRemanecente("arquivo.txt3");
        entaoArquivosRemanecente("arquivo.txt4");
        entaoArquivosRemanecente("arquivo.txt5");
        entaoArquivosRemanecente("arquivo.txt6");
        entaoArquivosRemanecente("arquivo.txt7");
        entaoArquivosRemanecente("arquivo.txt8");
        entaoArquivosRemanecente("arquivo.txt9");
    }

    @Test
    public void deveExcluirNenhumArquivo() throws Exception {
        dadoArquivosEmMB(10, 1);
        dadoHouseKeepingEspacoMB(10);
        quandoExecutarHousekeeping();
        entaoArquivosRemanecentes(10);
        entaoArquivosRemanecente("arquivo.txt0");
        entaoArquivosRemanecente("arquivo.txt1");
        entaoArquivosRemanecente("arquivo.txt2");
        entaoArquivosRemanecente("arquivo.txt3");
        entaoArquivosRemanecente("arquivo.txt4");
        entaoArquivosRemanecente("arquivo.txt5");
        entaoArquivosRemanecente("arquivo.txt6");
        entaoArquivosRemanecente("arquivo.txt7");
        entaoArquivosRemanecente("arquivo.txt8");
        entaoArquivosRemanecente("arquivo.txt9");
    }

    @Test
    public void deveExcluirTodosArquivos() throws Exception {
        dadoArquivosEmMB(10, 1);
        dadoHouseKeepingEspacoMB(0.9999);
        quandoExecutarHousekeeping();
        entaoArquivosRemanecentes(0);
    }

    private void entaoArquivosRemanecente(String arquivo) {
        File file = new File(getTempDir() + arquivo);
        logger.debug("verificando se arquivo existe:" + file.getAbsolutePath());
        assertTrue("arquivo não existe:" + file.getAbsolutePath(), file.exists());
        logger.debug("arquivo existe:" + file.getAbsolutePath());
    }

    private void dadoArquivosEmMB(int qtde, int tamanho) throws Exception {

        for (int i = 0; i < qtde; i++) {
            File arquivo = new File(getTempDir() + "arquivo.txt" + i);
            logger.debug("gravando arquivos:" + arquivo.getAbsolutePath());
            FileUtils.writeStringToFile(arquivo, getTextoEmMB(tamanho));
            Thread.sleep(10);
        }

    }

    private String getTempDir() {
        String dir = System.getProperty("java.io.tmpdir");
        dir = dir.endsWith("/") ? dir : dir + File.separator;
        dir += "temphousekeeping" + File.separator;

        File directory = new File(dir);
        if (!directory.exists()) {
            directory.mkdirs();
        }
        return dir;
    }

    private String getTextoEmMB(int tamanho) {
        StringBuilder sb = new StringBuilder();
        while (sb.length() < (1024 * 1024)) {
            sb.append("a");
        }
        return sb.toString();
    }

    private void dadoHouseKeepingEspacoMB(double i) {
        hk = new SpaceHousekeepingJob(getTempDir(), i / 1024);
    }

    private void quandoExecutarHousekeeping() {
        hk.run();
    }

    private void entaoArquivosRemanecentes(int i) {
        File[] arquivos = new File(getTempDir()).listFiles();
        assertEquals(i, arquivos.length);

        for (File file : arquivos) {
            logger.debug("Arquivo remanescente:" + file.getAbsolutePath() + " : existe?" + file.exists() + ", Last Modified:" + file.lastModified());
        }

    }

}


text:
@implementation MXWebviewPlugin

- (UIViewController *)containerVC {
    return _bridge.containerVC;
}

- (UIWebView *)webview {
    return _bridge.webview;
}

- (instancetype)initWithBridge:(MXWebviewBridge *)bridge {
    if (self = [super init]) {
        _bridge = bridge;
    }
    return self;
}

- (void)callBackSuccess:(BOOL)success withDictionary:(NSDictionary *)dict toInvocation:(MXNativeInvocation *)invocation {
    [_bridge callBackSuccess:success withDictionary:dict toInvocation:invocation];
}

- (void)successCallBackWithDictionary:(NSDictionary *)dict toInvocation:(MXNativeInvocation *)invocation {
    [self callBackSuccess:YES withDictionary:dict toInvocation:invocation];
}

- (void)failCallBackWithDictionary:(NSDictionary *)dict toInvocation:(MXNativeInvocation *)invocation {
    [self callBackSuccess:NO withDictionary:dict toInvocation:invocation];
}

- (void)callBackSuccess:(BOOL)success withString:(NSString *)string toInvocation:(MXNativeInvocation *)invocation {
    [_bridge callBackSuccess:success withString:string toInvocation:invocation];
}

- (void)successCallBackWithString:(NSString *)string toInvocation:(MXNativeInvocation *)invocation {
    [self callBackSuccess:YES withString:string toInvocation:invocation];
}

- (void)failCallBackWithString:(NSString *)string toInvocation:(MXNativeInvocation *)invocation {
    [self callBackSuccess:NO withString:string toInvocation:invocation];
}

- (void)callBackSuccess:(BOOL)success withArray:(NSArray *)array toInvocation:(MXNativeInvocation *)invocation {
    [_bridge callBackSuccess:success withArray:array toInvocation:invocation];
}

- (void)successCallBackWithArray:(NSArray *)array toInvocation:(MXNativeInvocation *)invocation {
    [self callBackSuccess:YES withArray:array toInvocation:invocation];
}

- (void)failCallBackWithArray:(NSArray *)array toInvocation:(MXNativeInvocation *)invocation {
    [self callBackSuccess:NO withArray:array toInvocation:invocation];
}

@end


text:
<?php

class Google_Service_YouTube_VideoPlayer extends Google_Model
{
  public $embedHeight;
  public $embedHtml;
  public $embedWidth;

  public function setEmbedHeight($embedHeight)
  {
    $this->embedHeight = $embedHeight;
  }
  public function getEmbedHeight()
  {
    return $this->embedHeight;
  }
  public function setEmbedHtml($embedHtml)
  {
    $this->embedHtml = $embedHtml;
  }
  public function getEmbedHtml()
  {
    return $this->embedHtml;
  }
  public function setEmbedWidth($embedWidth)
  {
    $this->embedWidth = $embedWidth;
  }
  public function getEmbedWidth()
  {
    return $this->embedWidth;
  }
}


text:
package org.qcert.sqlpp;

import java.util.Iterator;
import java.util.List;

import org.apache.asterix.lang.sqlpp.parser.Token;

/**
 * Lexical fixup to get out of the morass caused by whether or not 'value' is a reserved word.  It IS a reserved word in SQL 92 and beyond,
 *   but it is used as a (non-delimited) identifier in TPC-H query 11 and Presto is willing to parse it as an identifier.
 *   In SQL++, the word is always reserved, even though it is only significant when it follows 'select'.
 * In all other contexts, we delimit it using the SQL++ convention.
 */
public class FixupValueKeyword implements LexicalFixup {

	@Override
	public void apply(Iterator<Token> tokens, List<Token> output) {
		boolean sawSelect = false;
		while (tokens.hasNext()) {
			Token tok = tokens.next();
			if (tok.kind == SELECT) {
				sawSelect = true;
			} else if (tok.kind == VALUE) {
				if (!sawSelect) {
					tok.kind = IDENTIFIER;
					tok.image = "`value`";
				} else
					sawSelect = false;
			} else
				sawSelect = false;
			output.add(tok);
		}
	}
}


text:
package org.wso2.emm.integration.ui.pages.policy;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.wso2.emm.integration.ui.pages.UIElementMapper;

import java.io.IOException;

public class RemovePolicyPage {
    private WebDriver driver;
    private UIElementMapper uiElementMapper;

    public RemovePolicyPage(WebDriver driver) throws IOException{
        this.driver = driver;
        this.uiElementMapper = UIElementMapper.getInstance();
        // Check that we're on the right page.
        if (!(driver.getCurrentUrl().contains("policies"))) {
            throw new IllegalStateException("This is not the policy list");
        }
    }

    public void PolicyList() throws IOException {

        driver.findElement(By.xpath(uiElementMapper.getElement("emm.remove.policy.file"))).click();
        driver.findElement(By.xpath(uiElementMapper.getElement("emm.remove.policy.button"))).click();
        driver.findElement(By.xpath(uiElementMapper.getElement("emm.remove.policy.yes"))).click();
        String resultText = driver.findElement(By.xpath(uiElementMapper.getElement("emm.remove.policy.removed.msg")
        )).getText();
        if(!resultText.contains("Done. Selected policy was successfully removed.")){
            throw new IllegalStateException("Policy was not removed");
        }
    }
}


text:
"""Tests for neurodsp.utils.data."""

from numpy.testing import assert_equal, assert_almost_equal

from neurodsp.tests.settings import N_SECONDS, FS, N_SECONDS_ODD, FS_ODD

from neurodsp.utils.data import *

###################################################################################################
###################################################################################################

def test_create_freqs():

    freqs = create_freqs(8, 12)
    assert_equal(freqs, np.array([8, 9, 10, 11, 12]))

    freqs = create_freqs(8, 12, 0.5)
    assert_equal(freqs, np.array([8, 8.5, 9, 9.5, 10, 10.5, 11, 11.5, 12]))

def test_create_times():

    times = create_times(N_SECONDS, FS)
    assert len(times) == compute_nsamples(N_SECONDS, FS)
    assert_equal(times, np.arange(0, N_SECONDS, 1/FS))

    start_val = 0.5
    times = create_times(N_SECONDS, FS, start_val=start_val)
    assert_equal(times[0], start_val)
    assert_almost_equal(times[-1], N_SECONDS + start_val, decimal=2)
    assert len(times) == compute_nsamples(N_SECONDS, FS)

    assert len(create_times(N_SECONDS_ODD, FS)) == compute_nsamples(N_SECONDS_ODD, FS)
    assert len(create_times(N_SECONDS, FS_ODD)) == compute_nsamples(N_SECONDS, FS_ODD)
    assert len(create_times(N_SECONDS_ODD, FS_ODD)) == compute_nsamples(N_SECONDS_ODD, FS_ODD)

def test_create_samples():

    samples = create_samples(10)
    assert_equal(samples, np.arange(0, 10, 1))

def test_compute_nsamples():

    n_samples = compute_nsamples(N_SECONDS, FS)
    assert isinstance(n_samples, int)
    assert n_samples == 1000

    n_samples = compute_nsamples(N_SECONDS_ODD, FS_ODD)
    assert isinstance(n_samples, int)
    assert n_samples == int(np.ceil(N_SECONDS_ODD * FS_ODD))

def test_split_signal(tsig):

    chunks = split_signal(tsig, 100)
    assert chunks.shape == (10, 100)
    assert_equal(chunks[0, 0:10], tsig[0:10])


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Trans. Sapporo nat. Hist. Soc. 11: 71 (1930)

#### Original name
Clavaria meakanensis S. Imai

### Remarks
null


text:
#ifndef ORG_EEROS_HAL_PIXYCAM_HPP_
#define ORG_EEROS_HAL_PIXYCAM_HPP_

#include <eeros/math/Matrix.hpp>
#include <eeros/logger/Logger.hpp>
#include <eeros/core/Thread.hpp>
#include <pixy2/libpixyusb2.h>
#include <unistd.h>
#include <atomic>

#define nrDots 4

using namespace eeros::logger;
using namespace eeros::math;

namespace eeros {
namespace hal {

/**
 * This class is part of the hardware abstraction layer.
 * It is used by \ref eeros::control::PixyCamInput class.
 * Do not use it directly. Fetch and build the pixy2 library.
 * Unfortunately, it misses suitable make and install targets.
 * You have to manually copy the proper header files to your
 * install directory. As the library is not built for relocatable
 * code, eeros cannot be built with pixy code in it and all the
 * code has been placed into this header file.
 *
 * @since v1.3
 */

class PixyCam : public eeros::Thread {
 public:
  explicit PixyCam(std::string dev, int priority) : starting(true), running(false), log(Logger::getLogger()) {
    log.info() << "Connecting to Pixy2";
    auto res = pixy.init();
    if (res < 0) {
      log.warn() << "no connection to Pixy2 possible";
      return;
    } else log.info() << "Pixy2 connected";
    pixy.getVersion();
    log.info() << "Pixy2 version = " << pixy.version;
    // Set Pixy2 to color connected components program
    pixy.changeProg("color_connected_components");
    starting = false;
  }

  /**
   * Destructs the thread.
   */
  virtual ~PixyCam() {
    pixy.setLamp(0, 0);
    running = false;
    join();
  }

  /**
   * Returns the position of the camera, with respect to the middle of the
   * markers pattern, with lowpass filter
   */
  virtual Vector3 getPos() {
    return output;
  }

  /**
   * Returns the position of the camera, with respect to the middle of the markers pattern
   */
  virtual Vector3 getPosRaw() {
    return outputRaw;
  }

  /**
   * Returns the position of the detected dots on the markers pattern in pixels
   */
  virtual Matrix<nrDots,2,double> getDots() {
    return pos;
  }

  /**
   * Returns the height of the camera to the markers pattern
   */
  virtual double getHeight() {
    return height;
  }

  /**
   * Returns true if data are valid, i.e. if all markers are within the field of view of the camera
   */
  virtual double isDataValid() {
    return valid;
  }

  /**
   * Returns the nu,ber of markers detected by the camera
   */
  virtual int getNofBlocks() {
    return nofBlocks;
  }

  /**
   * Sets the lamp of the camera
   * @param white: white light on if true
   * @param rgb: rgb light on if true
   */
  virtual void setLamp(bool white, bool rgb) {
    pixy.setLamp(white, rgb);
  }

 private:

  /**
   * Gets sensor data and outputs position of the camera with respect to the middle of the markers pattern.
   * Returns data raw, as well as filtered by a lowpass filter.
   */
  virtual void run() {
    while (starting);
    running = true;
    while (running) {
      pixy.ccc.getBlocks();
      nofBlocks = pixy.ccc.numBlocks;
      for(int i=0;i<nrDots; i++) {
        auto block = pixy.ccc.blocks[i];
        pos(i,0) = block.m_x;
        pos(i,1) = block.m_y;
      }
      double i_x_min = 0;
      double i_x_max = 0;
      double i_y_min = 0;
      double i_y_max = 0;
      double xO = 0;
      double yO = 0;

      for (int i=0; i<4; i++) {
        xO = xO + pos.get(i,0)/4;
        yO = yO + pos.get(i,1)/4;
        if (pos.get(i,0) < pos.get(i_x_min,0))
          i_x_min = i;
        if (pos.get(i,0) > pos.get(i_x_max,0))
          i_x_max = i;
        if (pos.get(i,1) < pos.get(i_y_min,1))
          i_y_min = i;
        if (pos.get(i,1) > pos.get(i_y_max,1))
          i_y_max = i;
      }

      // Shift centre ref system to middle
      xO = xO - max_pixel_x/2;
      yO = yO - max_pixel_y/2;

      double scaling_height = 3.02 / (3.02 + 1.43);
      double distWorld = 0.335 * scaling_height;
      double distCam = (sqrt((pos.get(i_x_max,0) - pos.get(i_x_min,0)) * (pos.get(i_x_max,0) - pos.get(i_x_min,0))
            + (pos.get(i_x_max,1) - pos.get(i_x_min,1)) * (pos.get(i_x_max,1) - pos.get(i_x_min,1)) )
            + sqrt((pos.get(i_y_max,0) - pos.get(i_y_min,0)) * (pos.get(i_y_max,0) - pos.get(i_y_min,0))
            + (pos.get(i_y_max,1) - pos.get(i_y_min,1)) * (pos.get(i_y_max,1) - pos.get(i_y_min,1))))/2;

      // Define height from markers
      double pixel_fix = 93;     // pixel
      double height_fix = 0.915; // m
      height = pixel_fix * height_fix / distCam;

      // Define if markers in central region on picture
      if(pos.get(i_x_min,0) > delta_pixel_range && pos.get(i_x_min,0) < (max_pixel_x-delta_pixel_range) &&
      pos.get(i_x_max,0) > delta_pixel_range && pos.get(i_x_max,0) < (max_pixel_x-delta_pixel_range) &&
      pos.get(i_y_min,0) > delta_pixel_range && pos.get(i_y_min,0) < (max_pixel_x-delta_pixel_range) &&
      pos.get(i_y_max,0) > delta_pixel_range && pos.get(i_y_max,0) < (max_pixel_x-delta_pixel_range) &&
      pos.get(i_x_min,1) > delta_pixel_range && pos.get(i_x_min,1) < (max_pixel_y-delta_pixel_range) &&
      pos.get(i_x_max,1) > delta_pixel_range && pos.get(i_x_max,1) < (max_pixel_y-delta_pixel_range) &&
      pos.get(i_y_min,1) > delta_pixel_range && pos.get(i_y_min,1) < (max_pixel_y-delta_pixel_range) &&
      pos.get(i_y_max,1) > delta_pixel_range && pos.get(i_y_max,1) < (max_pixel_y-delta_pixel_range) )
        markersInRange = true;
      else
        markersInRange = false;

      if(height < height_limit && markersInRange == true) valid = true;
      else valid = false;

      double xS = xO * distWorld / distCam;
      double yS = yO * distWorld / distCam;

      double phiS = (atan2((pos.get(i_x_max,1) - pos.get(i_x_min,1)), (pos.get(i_x_max,0) - pos.get(i_x_min,0)))
            + atan2((pos.get(i_y_min,0) - pos.get(i_y_max,0)), (pos.get(i_y_max,1) - pos.get(i_y_min,1)))) / 2;

      // Filtering
      double alpha_xy = 0.05;
      double alpha_phi = 0.1;
      double xS_filtered, yS_filtered, phiS_filtered;

      if(first){
        xS_filtered = xS;
        yS_filtered = yS;
        phiS_filtered = phiS;
        first = false;
      } else {
        xS_filtered = xS*alpha_xy + xS_prev*(1-alpha_xy);
        yS_filtered = yS*alpha_xy + yS_prev*(1-alpha_xy);
        phiS_filtered = phiS*alpha_phi + phiS_prev*(1-alpha_phi);
      }
      xS_prev = xS_filtered;
      yS_prev = yS_filtered;
      phiS_prev = phiS_filtered;

      double xS_out_f, yS_out_f;
      xS_out_f = yS_filtered;
      yS_out_f = xS_filtered;

      // Set output
      outputRaw << xS, yS, phiS;
      output << xS_out_f, yS_out_f, phiS_filtered;

      usleep(5000);
    }
  }

  std::atomic<bool> starting;
  std::atomic<bool> running;
  bool first = true;
  bool valid = false;
  bool markersInRange = false;
  int nofBlocks;
  Matrix<nrDots,2,double> pos;
  Vector3 output, outputRaw;
  double height = 0;
  Pixy2 pixy;
  Logger log;
  double xS_prev = 0;
  double yS_prev = 0;
  double phiS_prev = 0;
  double max_pixel_x = 316;
  double max_pixel_y = 208;
  double delta_pixel_range = 10;
  double height_limit = 1.2;
};

}
}

#endif // ORG_EEROS_HAL_PIXYCAM_HPP_


text:
<?php

namespace Sonata\UserBundle\Block\Breadcrumb;

use Sonata\BlockBundle\Block\BlockContextInterface;

/**
 * Class for user breadcrumbs.
 *
 * @author Sylvain Deloux <sylvain.deloux@ekino.com>
 */
class UserIndexBreadcrumbBlockService extends BaseUserProfileBreadcrumbBlockService
{
    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'sonata.user.block.breadcrumb_index';
    }

    /**
     * {@inheritdoc}
     */
    protected function getMenu(BlockContextInterface $blockContext)
    {
        $menu = $this->getRootMenu($blockContext);

        return $menu;
    }
}