text:
#ifndef ELG_ENTITYMANAGER_DESCRIPTIONMACROS_H_
#define ELG_ENTITYMANAGER_DESCRIPTIONMACROS_H_

#include "Elg/Utilities/Preprocessor/cat.hpp"
#include "Elg/Utilities/Preprocessor/repetition/repeat.hpp"

#include "Elg/EntityManager/EntityPool/EntityPool.h"
#include "Elg/EntityManager/ComponentPool/ComponentPool.h"

#define ELG_ENTITY_MANAGER_DESCRIPTION_HEADER(ENTITY_COUNT)                                                           \
  static const elg_uint32 MaxEntityCount = (ENTITY_COUNT);                                                            \
                                                                                \
  typedef Elg::EntityManager::EntityPool<MaxEntityCount> EntityPoolType;                                              \
                                                                                \
  EntityPoolType EntityPool;                                                                                \
                                                                                \
  template<typename ComponentType> struct ComponentPoolIndex {                                                        \
    enum { value = -1 };                                                                                \
  };                                                                                \
                                                                                \
  template<typename ComponentType> struct ComponentMaxCount;                                                          \
                                                                                \
  template<elg_uint16 Index> struct ComponentPoolType;                                                                \
                                                                                \
  template<elg_uint16 Index> typename ComponentPoolType<Index>::type& GetComponentPool();                             \
  template<elg_uint16 Index> const typename ComponentPoolType<Index>::type& GetComponentPool() const;

#define ELG_ENTITY_MANAGER_DESCRIPTION_COMPONENT(COMPONENT_INDEX, COMPONENT_COUNT, ...)                               \
  static const elg_uint16 BOOST_PP_CAT(MaxComponentInstances, COMPONENT_INDEX) = (COMPONENT_COUNT);                   \
                                                                                \
  typedef Elg::EntityManager::ComponentPool< __VA_ARGS__,                                                             \
                                             BOOST_PP_CAT(MaxComponentInstances, COMPONENT_INDEX),                    \
                                             MaxEntityCount > BOOST_PP_CAT(ComponentPoolType, COMPONENT_INDEX);       \
                                                                                \
  BOOST_PP_CAT(ComponentPoolType, COMPONENT_INDEX) BOOST_PP_CAT(ComponentPool, COMPONENT_INDEX);                      \
                                                                                \
  template<>                                                                                \
  struct ComponentPoolIndex<__VA_ARGS__> {                                                                            \
    enum { value = (COMPONENT_INDEX) };                                                                               \
  };                                                                                \
                                                                                \
  template<>                                                                                \
  struct ComponentMaxCount<__VA_ARGS__> {                                                                             \
    enum { value = (COMPONENT_COUNT) };                                                                               \
  };                                                                                \
                                                                                \
  template<>                                                                                \
  struct ComponentPoolType<(COMPONENT_INDEX)> {                                                                       \
    typedef BOOST_PP_CAT(ComponentPoolType, COMPONENT_INDEX) type;                                                    \
  };                                                                                \
                                                                                \
  template<>                                                                                \
  ComponentPoolType<(COMPONENT_INDEX)>::type& GetComponentPool<(COMPONENT_INDEX)>() {                                 \
    return BOOST_PP_CAT(ComponentPool, COMPONENT_INDEX);                                                              \
  }                                                                                \
                                                                                \
  template<>                                                                                \
  const ComponentPoolType<(COMPONENT_INDEX)>::type& GetComponentPool<(COMPONENT_INDEX)>() const {                     \
    return BOOST_PP_CAT(ComponentPool, COMPONENT_INDEX);                                                              \
  }

#define ELG_ENTITY_MANAGER_DESCRIPTION_FOOTER_DESTROY_ALL_COMPONENTS(Z, N, DATA)                                      \
  if (BOOST_PP_CAT(ComponentPool, N).GetComponent(entity_id_index) != ELG_ENTITY_MANAGER_INVALID_ID) {                \
    BOOST_PP_CAT(ComponentPool, N).DestroyComponent(entity_id_index);                                                 \
  }

#define ELG_ENTITY_MANAGER_DESCRIPTION_FOOTER_SERIALIZE(Z, N, DATA)                                                   \
  BOOST_PP_CAT(ComponentPool, N).Serialize(out);

#define ELG_ENTITY_MANAGER_DESCRIPTION_FOOTER_DESERIALIZE(Z, N, DATA)                                                 \
  BOOST_PP_CAT(ComponentPool, N).Deserialize(in);

#define ELG_ENTITY_MANAGER_DESCRIPTION_FOOTER(COMPONENT_COUNT)                                                        \
  static const elg_uint16 ComponentCount = (COMPONENT_COUNT);                                                         \
                                                                                \
  void DestroyAllComponents(elg_uint32 entity_id_index) {                                                             \
    BOOST_PP_REPEAT(COMPONENT_COUNT, ELG_ENTITY_MANAGER_DESCRIPTION_FOOTER_DESTROY_ALL_COMPONENTS, DONT_CARE)         \
  }                                                                                \
                                                                                \
  void Serialize(FILE* out) const {                                                                                \
    BOOST_PP_REPEAT(COMPONENT_COUNT, ELG_ENTITY_MANAGER_DESCRIPTION_FOOTER_SERIALIZE, DONT_CARE)                      \
  }                                                                                \
                                                                                \
  void Deserialize(FILE* in) {                                                                                \
    BOOST_PP_REPEAT(COMPONENT_COUNT, ELG_ENTITY_MANAGER_DESCRIPTION_FOOTER_DESERIALIZE, DONT_CARE)                    \
  }

#endif  // ELG_ENTITYMANAGER_DESCRIPTIONMACROS_H_


text: log.info('Application ' + app.name + ' started');

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace Inpsyde\SearchReplace\Page;

/**
 * Class Credits
 *
 * @package Inpsyde\SearchReplace\Page
 */
class Credits extends AbstractPage implements PageInterface {

	/**
	 * Callback function for credits content.
	 */
	public function render() {

		require_once( __DIR__ . '/../templates/credits.php' );
	}

	/**
	 * @return string
	 */
	public function get_page_title() {

		return esc_html__( 'Credits', 'search-and-replace' );
	}

	/**
	 * Return the static slug string.
	 *
	 * @return string
	 */
	public function get_slug() {

		return 'credits';
	}

	/**
	 * @return boolean
	 */
	public function save() {

		return TRUE;
	}
}


text:
<?php

namespace Mhamed\CeciliaBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class MhamedCeciliaBundle extends Bundle
{
}


text:
namespace chromeos {

namespace secure_channel {

// Concrete SingleClientProxy implementation, which forwards client requests to
// its delegate, and utilizes a mojo::Remote<MessageReceiver> to receive
// incoming messages.
class SingleClientProxyImpl : public SingleClientProxy,
                              public ChannelImpl::Delegate {
 public:
  class Factory {
   public:
    static std::unique_ptr<SingleClientProxy> Create(
        SingleClientProxy::Delegate* delegate,
        std::unique_ptr<ClientConnectionParameters>
            client_connection_parameters);
    static void SetFactoryForTesting(Factory* factory);

   protected:
    virtual ~Factory();
    virtual std::unique_ptr<SingleClientProxy> CreateInstance(
        SingleClientProxy::Delegate* delegate,
        std::unique_ptr<ClientConnectionParameters>
            client_connection_parameters) = 0;

   private:
    static Factory* test_factory_;
  };

  SingleClientProxyImpl(const SingleClientProxyImpl&) = delete;
  SingleClientProxyImpl& operator=(const SingleClientProxyImpl&) = delete;
  ~SingleClientProxyImpl() override;

  // SingleClientProxy:
  const base::UnguessableToken& GetProxyId() override;

 private:
  friend class SecureChannelSingleClientProxyImplTest;

  SingleClientProxyImpl(
      SingleClientProxy::Delegate* delegate,
      std::unique_ptr<ClientConnectionParameters> client_connection_parameters);

  // SingleClientProxy:
  void HandleReceivedMessage(const std::string& feature,
                             const std::string& payload) override;
  void HandleRemoteDeviceDisconnection() override;

  // ChannelImpl::Delegate:
  void OnSendMessageRequested(const std::string& message,
                              base::OnceClosure on_sent_callback) override;
  void RegisterPayloadFile(
      int64_t payload_id,
      mojom::PayloadFilesPtr payload_files,
      FileTransferUpdateCallback file_transfer_update_callback,
      base::OnceCallback<void(bool)> registration_result_callback) override;

  void GetConnectionMetadata(
      base::OnceCallback<void(mojom::ConnectionMetadataPtr)> callback) override;
  void OnClientDisconnected() override;

  void FlushForTesting();

  std::unique_ptr<ClientConnectionParameters> client_connection_parameters_;
  std::unique_ptr<ChannelImpl> channel_;
  mojo::Remote<mojom::MessageReceiver> message_receiver_remote_;
};

}  // namespace secure_channel

}  // namespace chromeos

#endif  // CHROMEOS_SERVICES_SECURE_CHANNEL_SINGLE_CLIENT_PROXY_IMPL_H_


text:
package authenticator

import (
	"k8s.io/apiserver/pkg/authentication/authenticator"
	"k8s.io/apiserver/pkg/authentication/request/bearertoken"
	"k8s.io/apiserver/pkg/authentication/token/tokenfile"
	"k8s.io/apiserver/pkg/authentication/user"
)

// newAuthenticatorFromToken returns an authenticator.Request or an error
func NewAuthenticatorFromTokens(tokens map[string]*user.DefaultInfo) authenticator.Request {
	return bearertoken.New(tokenfile.New(tokens))
}


text:
require 'spec/runner/formatter/base_formatter'
require 'fileutils'

module Spec
  module Runner
    module Formatter
      # Baseclass for text-based formatters. Can in fact be used for
      # non-text based ones too - just ignore the +output+ constructor
      # argument.
      class BaseTextFormatter < BaseFormatter
        attr_reader :output, :pending_examples
        # Creates a new instance that will write to +where+. If +where+ is a
        # String, output will be written to the File with that name, otherwise
        # +where+ is exected to be an IO (or an object that responds to #puts and #write).
        def initialize(options, where)
          super
          if where.is_a?(String)
            FileUtils.mkdir_p(File.dirname(where))
            @output = File.open(where, 'w')
          else
            @output = where
          end
          @pending_examples = []
        end

        def example_pending(example, message, pending_caller)
          @pending_examples << ["#{@example_group.description} #{example.description}", message, pending_caller]
        end

        def dump_failure(counter, failure)
          @output.puts
          @output.puts "#{counter.to_s})"
          @output.puts colorize_failure("#{failure.header}\n#{failure.exception.message}", failure)
          @output.puts format_backtrace(failure.exception.backtrace)
          @output.flush
        end

        def colorize_failure(message, failure)
          failure.pending_fixed? ? blue(message) : red(message)
        end

        def colourise(message, failure)
          Kernel.warn <<-NOTICE
DEPRECATED: BaseTextFormatter#colourise is deprecated and will be
removed from a future version of RSpec.

Please use colorize_failure instead.
NOTICE
          colorize_failure(message, failure)
        end

        def dump_summary(duration, example_count, failure_count, pending_count)
          return if dry_run?
          @output.puts
          @output.puts "Finished in #{duration} seconds"
          @output.puts

          summary = "#{example_count} example#{'s' unless example_count == 1}, #{failure_count} failure#{'s' unless failure_count == 1}"
          summary << ", #{pending_count} pending" if pending_count > 0

          if failure_count == 0
            if pending_count > 0
              @output.puts yellow(summary)
            else
              @output.puts green(summary)
            end
          else
            @output.puts red(summary)
          end
          @output.flush
        end

        def dump_pending
          unless @pending_examples.empty?
            @output.puts
            @output.puts "Pending:"
            @pending_examples.each do |pending_example|
              @output.puts "\n#{pending_example[0]} (#{pending_example[1]})"
              @output.puts "#{pending_example[2]}\n"
            end
          end
          @output.flush
        end

        def close
          @output.close  if (IO === @output) & (@output != $stdout)
        end

        def format_backtrace(backtrace)
          return "" if backtrace.nil?
          backtrace.map { |line| backtrace_line(line) }.join("\n")
        end

      protected

        def colour?
          !!@options.colour
        end

        def dry_run?
          !!@options.dry_run
        end

        def autospec?
          !!@options.autospec
        end

        def backtrace_line(line)
          line.sub(/\A([^:]+:\d+)$/, '\\1:')
        end

        def colour(text, colour_code)
          return text unless ENV['RSPEC_COLOR'] || (colour? & (autospec? || output_to_tty?))
          "#{colour_code}#{text}\e[0m"
        end

        def output_to_tty?
          begin
            @output.tty? || ENV.has_key?("AUTOTEST")
          rescue NoMethodError
            false
          end
        end

        def green(text); colour(text, "\e[32m"); end
        def red(text); colour(text, "\e[31m"); end
        def yellow(text); colour(text, "\e[33m"); end
        def blue(text); colour(text, "\e[34m"); end

        def magenta(text)
          Kernel.warn <<-NOTICE
DEPRECATED: BaseTextFormatter#magenta is deprecated and will be
removed from a future version of RSpec.

Please use red instead (it is red/green/refactor after all).
NOTICE
          red(text)
        end
      end
    end
  end
end


text:
class CreateStaffs < ActiveRecord::Migration
  def change
    create_table :staffs do |t|
      t.string :name
      t.string :division
      t.string :role
      t.integer :order
      t.string :picture

      t.string :facebook
      t.string :mail
      t.string :phone
      t.string :linkedin

      t.timestamps null: false
    end
  end
end


text:
"""
sparql_test.py

Created by Philip Cooper on 2008-02-27.
Copyright (c) 2008 Openvest. All rights reserved.
"""

from rdfalchemy.sparql import SPARQLGraph
from rdfalchemy.sparql.sesame2 import SesameGraph
from rdfalchemy import URIRef
from decimal import Decimal
import unittest

class sparql_test:
    def __init__(self):
        pass

class sparql_testTests(unittest.TestCase):
    def setUp(self):
        pass

    def initBindings_test1(self):
        query = 'select * where {?s ?P ?oo.?ss ?p \n?oo}'
        initBindings = dict(oo=URIRef("OHO"), P=Decimal("4.40"))
        processed = SPARQLGraph._processInitBindings(query, initBindings)
        assert processed == \
            'select * where {?s "4.40"^^' + \
            '<http://www.w3.org/2001/XMLSchema#decimal> <OHO>.?ss ?p \n<OHO>}'

    def initBindings_test2(self):
        query = 'select * where {?s ?P ?oo.?ss ?p \n?oo}'
        initBindings = dict(oo=URIRef("OHO"), P=Decimal("4.40"))
        processed = SesameGraph._processInitBindings(query, initBindings)
        assert processed == \
            'select * where {?s "4.40"^^' + \
            '<http://www.w3.org/2001/XMLSchema#decimal> <OHO>.?ss ?p \n<OHO>}'

    def sesame_is_sparql_test(self):
        url = 'http://dbpedia.org/sparql'
        g1 = SesameGraph(url)
        g2 = SPARQLGraph(url)
        q1 = "select distinct ?Concept where {[] a ?Concept} LIMIT 10"
        r1 = set(list(g1.query(q1, resultMethod='xml')))
        r2 = set(list(g2.query(q1, resultMethod='xml')))
        assert r1 == r2
        assert len(r1) == 10, "Ooops, %s, %s" % (len(r1), len(r2))

if __name__ == '__main__':
    unittest.main()


text:
"""
``editquality join_observations -h``
::

    Joins data from Y into X for two sets of obersvations.  The output dataset
    only include observations from X, but with additional fields present in Y
    based on an provided identifier field.

    Usage:
        join_observations <X> <Y> <identifier>
                          [--output=<path>]
                          [--debug] [--verbose]

    Options:
        <X>                   Path to a file containing observations
        <Y>                   Path to a file containing observations with new
                              data
        <identifier>          The field to use as an identifier for matching
        --output=<path>       Path to a file to write output to
                              [default: <stdout>]
        --debug               Print debug logging
        --verbose             Print dots and stuff representing progress
"""
import json
import logging
import sys

import docopt

from . import util

logger = logging.getLogger(__name__)

def main(argv=None):
    args = docopt.docopt(__doc__, argv=argv)

    logging.basicConfig(
        level=logging.DEBUG if args['--debug'] else logging.WARNING,
        format='%(asctime)s %(levelname)s:%(name)s -- %(message)s'
    )

    x_observations = (util.normalize_revision(json.loads(line))
                      for line in open(args['<X>']))
    y_observations = (util.normalize_revision(json.loads(line))
                      for line in open(args['<Y>']))
    identifier = args['<identifier>']

    if args['--output'] == "<stdout>":
        observations_f = sys.stdout
    else:
        observations_f = open(args['--output'], "w")

    verbose = args['--verbose']

    run(x_observations, y_observations, identifier, observations_f, verbose)

def run(x_observations, y_observations, identifier, observations_f, verbose):
    x_obs_map = {observation[identifier]: observation
                 for observation in x_observations}

    for y_ob in y_observations:
        if y_ob[identifier] in x_obs_map:
            x_ob = x_obs_map.pop(y_ob[identifier])
            x_ob.update(y_ob)
            observations_f.write(json.dumps(x_ob))
            observations_f.write("\n")
            if verbose:
                sys.stderr.write(".")
        else:
            if verbose:
                sys.stderr.write("-")

    if verbose:
        sys.stderr.write("\n")


text:
//////////////////////////////////////////////////////////////////////////////
// Name:        src/generic/filedlgg.cpp
// Purpose:     wxGenericFileDialog
// Author:      Robert Roebling
// Modified by:
// Created:     12/12/98
// RCS-ID:      $Id$
// Copyright:   (c) Robert Roebling
// Licence:     wxWindows licence
/////////////////////////////////////////////////////////////////////////////

// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"

#ifdef __BORLANDC__
    #pragma hdrstop
#endif

#if wxUSE_FILEDLG

// NOTE : it probably also supports MAC, untested
#if !defined(__UNIX__) && !defined(__DOS__) && !defined(__WIN32__) && !defined(__OS2__) && !defined(__PALMOS__)
#error wxGenericFileDialog currently only supports Unix, win32 and DOS
#endif

#ifndef WX_PRECOMP
    #ifdef __WXMSW__
        #include "wx/msw/wrapwin.h"
    #endif
    #include "wx/hash.h"
    #include "wx/intl.h"
    #include "wx/settings.h"
    #include "wx/log.h"
    #include "wx/msgdlg.h"
    #include "wx/bmpbuttn.h"
    #include "wx/checkbox.h"
    #include "wx/choice.h"
    #include "wx/stattext.h"
    #include "wx/textctrl.h"
    #include "wx/sizer.h"
    #include "wx/filedlg.h"     // wxFD_OPEN, wxFD_SAVE...
#endif

#include "wx/longlong.h"
#include "wx/config.h"
#include "wx/imaglist.h"
#include "wx/artprov.h"
#include "wx/filefn.h"
#include "wx/filectrl.h"
#include "wx/generic/filedlgg.h"
#include "wx/debug.h"

#if wxUSE_TOOLTIPS
    #include "wx/tooltip.h"
#endif
#if wxUSE_CONFIG
    #include "wx/config.h"
#endif

#ifndef __WXPALMOS5__
#ifndef __WXWINCE__
    #include <sys/types.h>
    #include <sys/stat.h>
#endif

#ifdef __UNIX__
    #include <dirent.h>
    #include <pwd.h>
    #ifndef __VMS
    # include <grp.h>
    #endif
#endif

#ifdef __WINDOWS__
    #include "wx/msw/mslu.h"
#endif

#ifdef __WATCOMC__
    #include <direct.h>
#endif

#ifndef __WXWINCE__
#include <time.h>
#endif

#if defined(__UNIX__) || defined(__DOS__)
#include <unistd.h>
#endif
#endif // ! __WXPALMOS5__

#if defined(__WXWINCE__)
#define IsTopMostDir(dir) (dir == wxT("\\") || dir == wxT("/"))
#elif (defined(__DOS__) || defined(__WINDOWS__) || defined (__OS2__))
#define IsTopMostDir(dir)   (dir.empty())
#else
#define IsTopMostDir(dir)   (dir == wxT("/"))
#endif

//-----------------------------------------------------------------------------
// wxGenericFileDialog
//-----------------------------------------------------------------------------

#define  ID_LIST_MODE     (wxID_FILEDLGG    )
#define  ID_REPORT_MODE   (wxID_FILEDLGG + 1)
#define  ID_UP_DIR        (wxID_FILEDLGG + 2)
#define  ID_HOME_DIR      (wxID_FILEDLGG + 3)
#define  ID_NEW_DIR       (wxID_FILEDLGG + 4)
#define  ID_FILE_CTRL     (wxID_FILEDLGG + 5)

IMPLEMENT_DYNAMIC_CLASS(wxGenericFileDialog, wxFileDialogBase)

BEGIN_EVENT_TABLE(wxGenericFileDialog,wxDialog)
    EVT_BUTTON(ID_LIST_MODE, wxGenericFileDialog::OnList)
    EVT_BUTTON(ID_REPORT_MODE, wxGenericFileDialog::OnReport)
    EVT_BUTTON(ID_UP_DIR, wxGenericFileDialog::OnUp)
    EVT_BUTTON(ID_HOME_DIR, wxGenericFileDialog::OnHome)
    EVT_BUTTON(ID_NEW_DIR, wxGenericFileDialog::OnNew)
    EVT_BUTTON(wxID_OK, wxGenericFileDialog::OnOk)
    EVT_FILECTRL_FILEACTIVATED(ID_FILE_CTRL, wxGenericFileDialog::OnFileActivated)

    EVT_UPDATE_UI(ID_UP_DIR, wxGenericFileDialog::OnUpdateButtonsUI)
#if defined(__DOS__) || defined(__WINDOWS__) || defined(__OS2__)
    EVT_UPDATE_UI(ID_NEW_DIR, wxGenericFileDialog::OnUpdateButtonsUI)
#endif // defined(__DOS__) || defined(__WINDOWS__) || defined(__OS2__)
END_EVENT_TABLE()

long wxGenericFileDialog::ms_lastViewStyle = wxLC_LIST;
bool wxGenericFileDialog::ms_lastShowHidden = false;

void wxGenericFileDialog::Init()
{
    m_bypassGenericImpl = false;

    m_filectrl   = NULL;
    m_upDirButton  = NULL;
    m_newDirButton = NULL;
}

wxGenericFileDialog::wxGenericFileDialog(wxWindow *parent,
                           const wxString& message,
                           const wxString& defaultDir,
                           const wxString& defaultFile,
                           const wxString& wildCard,
                           long  style,
                           const wxPoint& pos,
                           const wxSize& sz,
                           const wxString& name,
                           bool  bypassGenericImpl ) : wxFileDialogBase()
{
    Init();
    Create( parent, message, defaultDir, defaultFile, wildCard, style, pos, sz, name, bypassGenericImpl );
}

bool wxGenericFileDialog::Create( wxWindow *parent,
                                  const wxString& message,
                                  const wxString& defaultDir,
                                  const wxString& defaultFile,
                                  const wxString& wildCard,
                                  long  style,
                                  const wxPoint& pos,
                                  const wxSize& sz,
                                  const wxString& name,
                                  bool  bypassGenericImpl )
{
    m_bypassGenericImpl = bypassGenericImpl;

    parent = GetParentForModalDialog(parent, style);

    if (!wxFileDialogBase::Create(parent, message, defaultDir, defaultFile,
                                  wildCard, style, pos, sz, name))
    {
        return false;
    }

    if (m_bypassGenericImpl)
        return true;

    if (!wxDialog::Create( parent, wxID_ANY, message, pos, sz,
                           wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER | style, name
                           ))
    {
        return false;
    }

#if wxUSE_CONFIG
    if (wxConfig::Get(false))
    {
        wxConfig::Get()->Read(wxT("/wxWindows/wxFileDialog/ViewStyle"),
                              &ms_lastViewStyle);
        wxConfig::Get()->Read(wxT("/wxWindows/wxFileDialog/ShowHidden"),
                              &ms_lastShowHidden);
    }
#endif

    if ((m_dir.empty()) || (m_dir == wxT(".")))
    {
        m_dir = wxGetCwd();
        if (m_dir.empty())
            m_dir = wxFILE_SEP_PATH;
    }

    const size_t len = m_dir.length();
    if ((len > 1) && (wxEndsWithPathSeparator(m_dir)))
        m_dir.Remove( len-1, 1 );

    m_filterExtension = wxEmptyString;

    // layout

    const bool is_pda = (wxSystemSettings::GetScreenType() <= wxSYS_SCREEN_PDA);

    wxBoxSizer *mainsizer = new wxBoxSizer( wxVERTICAL );

    wxBoxSizer *buttonsizer = new wxBoxSizer( wxHORIZONTAL );
    AddBitmapButton( ID_LIST_MODE, wxART_LIST_VIEW,
                     _("View files as a list view"), buttonsizer );
    AddBitmapButton( ID_REPORT_MODE, wxART_REPORT_VIEW,
                     _("View files as a detailed view"), buttonsizer );
    buttonsizer->Add( 30, 5, 1 );
    m_upDirButton = AddBitmapButton( ID_UP_DIR, wxART_GO_DIR_UP,
                                     _("Go to parent directory"), buttonsizer );

#ifndef __DOS__ // VS: Home directory is meaningless in MS-DOS...
    AddBitmapButton( ID_HOME_DIR, wxART_GO_HOME,
                     _("Go to home directory"), buttonsizer );
    buttonsizer->Add( 20, 20 );
#endif //!__DOS__

    m_newDirButton = AddBitmapButton( ID_NEW_DIR, wxART_NEW_DIR,
                                      _("Create new directory"), buttonsizer );

    if (is_pda)
        mainsizer->Add( buttonsizer, wxSizerFlags().Expand() );
    else
        mainsizer->Add( buttonsizer, wxSizerFlags().Expand()
                                                   .Border( wxLEFT | wxRIGHT | wxTOP ) );

    long style2 = 0;
    if ( HasFdFlag(wxFD_MULTIPLE) )
        style2 |= wxFC_MULTIPLE;

    m_filectrl = new wxGenericFileCtrl( this, ID_FILE_CTRL,
                                        m_dir, defaultFile,
                                        wildCard,
                                        style2,
                                        wxDefaultPosition, wxSize(540,200)
                                        );

    m_filectrl->ShowHidden( ms_lastShowHidden );

    if (ms_lastViewStyle == wxLC_LIST)
    {
        m_filectrl->ChangeToListMode();
    }
    else if (ms_lastViewStyle == wxLC_REPORT)
    {
        m_filectrl->ChangeToReportMode();
    }

    mainsizer->Add(m_filectrl, wxSizerFlags(1).Expand().HorzBorder());

    wxSizer *bsizer = CreateButtonSizer(wxOK | wxCANCEL);
    if ( bsizer )
    {
        if (is_pda)
            mainsizer->Add(bsizer, wxSizerFlags().Expand().Border());
        else
            mainsizer->Add(bsizer, wxSizerFlags().Expand().DoubleBorder());
    }

    SetSizer( mainsizer );

    if (!is_pda)
    {
        mainsizer->SetSizeHints( this );

        Centre( wxBOTH );
    }

    return true;
}

wxGenericFileDialog::~wxGenericFileDialog()
{
    if (!m_bypassGenericImpl)
    {
#if wxUSE_CONFIG
        if (wxConfig::Get(false))
        {
            wxConfig::Get()->Write(wxT("/wxWindows/wxFileDialog/ViewStyle"),
                                   ms_lastViewStyle);
            wxConfig::Get()->Write(wxT("/wxWindows/wxFileDialog/ShowHidden"),
                                   ms_lastShowHidden);
        }
#endif
    }
}

wxBitmapButton* wxGenericFileDialog::AddBitmapButton( wxWindowID winId,
                                                      const wxArtID& artId,
                                                      const wxString& tip,
                                                      wxSizer *sizer)
{
    wxBitmapButton *but = new wxBitmapButton(this, winId,
                                         wxArtProvider::GetBitmap(artId, wxART_BUTTON));
    but->SetToolTip(tip);
    sizer->Add(but, wxSizerFlags().Border());
    return but;
}

int wxGenericFileDialog::ShowModal()
{
    if (CreateExtraControl())
    {
        wxSizer *sizer = GetSizer();
        sizer->Insert(2 /* after m_filectrl */, m_extraControl,
                      wxSizerFlags().Expand().HorzBorder());
        sizer->Fit(this);
    }

    m_filectrl->SetDirectory(m_dir);

    return wxDialog::ShowModal();
}

bool wxGenericFileDialog::Show( bool show )
{
    // Called by ShowModal, so don't repeate the update
#ifndef __WIN32__
    if (show)
    {
        m_filectrl->SetDirectory(m_dir);
    }
#endif

    return wxDialog::Show( show );
}

void wxGenericFileDialog::OnOk( wxCommandEvent &WXUNUSED(event) )
{
    wxArrayString selectedFiles;
    m_filectrl->GetFilenames(selectedFiles);

    if (selectedFiles.Count() == 0)
        return;

    if (selectedFiles.Count() == 1)
    {
        SetPath( selectedFiles[0] );
    }

    EndModal(wxID_OK);
}

void wxGenericFileDialog::OnList( wxCommandEvent &WXUNUSED(event) )
{
    m_filectrl->ChangeToListMode();
    ms_lastViewStyle = wxLC_LIST;
    m_filectrl->GetFileList()->SetFocus();
}

void wxGenericFileDialog::OnReport( wxCommandEvent &WXUNUSED(event) )
{
    m_filectrl->ChangeToReportMode();
    ms_lastViewStyle = wxLC_REPORT;
    m_filectrl->GetFileList()->SetFocus();
}

void wxGenericFileDialog::OnUp( wxCommandEvent &WXUNUSED(event) )
{
    m_filectrl->GoToParentDir();
    m_filectrl->GetFileList()->SetFocus();
}

void wxGenericFileDialog::OnHome( wxCommandEvent &WXUNUSED(event) )
{
    m_filectrl->GoToHomeDir();
    m_filectrl->SetFocus();
}

void wxGenericFileDialog::OnNew( wxCommandEvent &WXUNUSED(event) )
{
    m_filectrl->GetFileList()->MakeDir();
}

void wxGenericFileDialog::OnFileActivated( wxFileCtrlEvent &WXUNUSED(event) )
{
    wxCommandEvent dummy;
    OnOk( dummy );
}

void wxGenericFileDialog::OnUpdateButtonsUI(wxUpdateUIEvent& event)
{
    // surprisingly, we can be called before m_filectrl is set in Create() as
    // wxFileCtrl ctor itself can generate idle events, so we need this test
    if ( m_filectrl )
        event.Enable( !IsTopMostDir(m_filectrl->GetShownDirectory()) );
}

#ifdef wxHAS_GENERIC_FILEDIALOG

IMPLEMENT_DYNAMIC_CLASS(wxFileDialog, wxGenericFileDialog)

#endif // wxHAS_GENERIC_FILEDIALOG

#endif // wxUSE_FILEDLG


text:
// ==========================================================================
//  Squidex Headless CMS
// ==========================================================================
//  Copyright (c) Squidex UG (haftungsbeschraenkt)
//  All rights reserved. Licensed under the MIT license.
// ==========================================================================

using Squidex.Domain.Apps.Entities.TestHelpers;
using Squidex.Infrastructure;
using Squidex.Infrastructure.UsageTracking;

namespace Squidex.Domain.Apps.Entities.Apps;

public class AppUsageDeleterTests
{
    private readonly CancellationTokenSource cts = new CancellationTokenSource();
    private readonly CancellationToken ct;
    private readonly IApiUsageTracker usageTracker = A.Fake<IApiUsageTracker>();
    private readonly AppUsageDeleter sut;

    public AppUsageDeleterTests()
    {
        ct = cts.Token;

        sut = new AppUsageDeleter(usageTracker);
    }

    [Fact]
    public void Should_run_with_default_order()
    {
        var order = ((IDeleter)sut).Order;

        Assert.Equal(0, order);
    }

    [Fact]
    public async Task Should_remove_events_from_streams()
    {
        var app = Mocks.App(NamedId.Of(DomainId.NewGuid(), "my-app"));

        await sut.DeleteAppAsync(app, ct);

        A.CallTo(() => usageTracker.DeleteAsync(app.Id.ToString(), ct))
            .MustHaveHappened();
    }
}


text:
namespace KeyPay.DomainModels.V2.PayRun
{
    public class SuperAdjustmentModel
    {
        public string ExternalId { get; set; }
        public string LocationId { get; set; }
        public string LocationName { get; set; }
        public string EmployeeId { get; set; }
        public string EmployeeName { get; set; }
        public string Notes { get; set; }
        public decimal Amount { get; set; }
        public string ContributionType { get; set; }
    }
}


text:
namespace platforms {
namespace darwinn {
namespace driver {

// A buddy memory allocator for DarwiNN virtual address space segment.
// https://en.wikipedia.org/wiki/Buddy_memory_allocation
class BuddyAddressSpace final : public MmioAddressSpace {
 public:
  using AddressSpace::MapMemory;  // Allows for proper overload resolution.

  BuddyAddressSpace(uint64 device_virtual_address_start,
                    uint64 device_virtual_address_size_bytes,
                    MmuMapper* mmu_mapper);

  // This class is neither copyable nor movable.
  BuddyAddressSpace(const BuddyAddressSpace&) = delete;
  BuddyAddressSpace& operator=(const BuddyAddressSpace&) = delete;

  ~BuddyAddressSpace() override = default;

  // Maps the given host buffer to the device buffer. Returns the mapped device
  // buffer on success.
  StatusOr<DeviceBuffer> MapMemory(const Buffer& buffer, DmaDirection direction,
                                   MappingTypeHint mapping_type) override
      LOCKS_EXCLUDED(mutex_);

  // Unmaps the given device buffer.
  Status UnmapMemory(DeviceBuffer buffer) override LOCKS_EXCLUDED(mutex_);

 private:
  mutable std::mutex mutex_;

  // Allocator that manages address space resources.
  BuddyAllocator allocator_ GUARDED_BY(mutex_);
};

}  // namespace driver
}  // namespace darwinn
}  // namespace platforms

#endif  // DARWINN_DRIVER_MEMORY_BUDDY_ADDRESS_SPACE_H_


text:
#include <limits.h>
#include <sys/ioctl.h>
#include <sys/types.h>

#include <drm.h>

#include "igt_core.h"
#include "drmtest.h"

/**
 * Checks DRM_IOCTL_GET_STATS.
 *
 * I don't care too much about the actual contents, just that the kernel
 * doesn't crash.
 */

IGT_TEST_DESCRIPTION("Tests the DRM_IOCTL_GET_STATS ioctl.");

igt_simple_main
{
	int fd, ret;
	drm_stats_t stats;

	fd = drm_open_any();

	ret = ioctl(fd, DRM_IOCTL_GET_STATS, &stats);
	igt_assert(ret == 0);

	close(fd);
}


text:
package com.amrdevelopment.parser.partners.grupo;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;

@XmlRootElement
public class Merchant {

    private Integer id;
    private String name;
    private List<Contacts> contacts;

    public Integer getId() {
        return id;
    }

    @XmlAttribute(name = "id")
    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public List<Contacts> getContacts() {
        return contacts;
    }

    @XmlElement(name = "contacts")
    public void setContacts(List<Contacts> contacts) {
        this.contacts = contacts;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="play_store_app_deep_link" translatable="false">market://details?id=%1$s</string>
    <string name="play_store_app_url" translatable="false">https://play.google.com/store/apps/details?id=%1$s</string>
</resources>


text:
<?php

namespace Rebrec\Bundle\VPNSSHBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

use Symfony\Component\HttpFoundation\Request;

use Rebrec\Bundle\VPNSSHBundle\Utils\Shell\UserProfile;
use Rebrec\Bundle\VPNSSHBundle\Utils\Shell\SSHKeyPair;
use Rebrec\Bundle\VPNSSHBundle\Utils\Shell\SSHAuthKey;

class ClientController extends Controller
{
    /**
     * @Route("/register/{key}")
     * @Template()
     */
    public function registerAction(Request $request, $key)
    {
        $error = true;
        $ipaddress = $request->getClientIp();
        $repository = $this->getDoctrine()->getRepository('RebrecVPNSSHBundle:Ticket');

        $ticket = $repository->findOneBy(array('auth_key' => $key, 'clientIp' => 'empty'));
        if (null === $ticket) {
            $error = true;
        } else {
            $u = new UserProfile($ticket->getUsername());
            $k = new SSHKeyPair($ticket->getAuthKey());
            $a = new SSHAuthKey($k->GetPubKey(), $ticket->getProfile()->getTunnels());
            $u->AddAuthKey($a);

            $ticket->setFirstLogon(new \DateTime());
            $ticket->setPublicKey($k->GetPubKey());
            $ticket->setPrivateKey($k->GetPrivKey());
            $ticket->setPpkKey($k->GetPPKKey());

            $ticket->setClientIp($ipaddress);
            $em = $this->getDoctrine()->getManager();
            $em->persist($ticket);
            $em->flush();
            $error = false;
        }
        return $this->render('RebrecVPNSSHBundle:Client:register.html.twig', array(
            'error' => $error,
            'ipaddress' => $ipaddress,
            'auth_key' => $key
        ));
    }

    /**
     * @Route("/settings")
     * @Template()
     */
    public function settingsAction(Request $request)
    {
        $error = true;
        $ipaddress = $request->getClientIp();
        $repository = $this->getDoctrine()->getRepository('RebrecVPNSSHBundle:Ticket');

        $ticket = $repository->findOneBy(array('clientIp' => $ipaddress));
        if (null === $ticket) {
            $jsonData['msg'] = 'Invalid Session!';
        } else {

            $jsonData['msg'] = 'ok';
            $jsonData['host'] = $ticket->getSshHostIp();
            $jsonData['port'] = $ticket->getSshHostPort();
            $jsonData['session'] = $ticket->getAuthKey();
            $jsonData['user'] = $ticket->getUsername();
            $jsonData['private_key'] = $ticket->getPpkKey();
            $jsonData['tunnels'] = $ticket->getProfile()->getTunnelsToArray(); ////// <========== FAUT CHANGER CA METTRE DANS TUNNEL UN TRUC QUI GENERE LA LISTE COMME IL AFUT

            $response = new \Symfony\Component\HttpFoundation\Response(json_encode($jsonData));
            return $response;

        }
    }
        //return false;

}


text:
var fs = require('fs'),
    fetch = require('node-fetch');

/**
 * Writes generated JSON into file.
 * @param dbName {String} Name of the file to create.
 * @param schema {Object} Populated object of collections.
 * @return {Promise}
 */
function writeJSON(dbName, schema) {

    var baseUrl = 'http://www.filltext.com/?',
        promises = [],
        collection;

    for (collection in schema) {

        var meta = schema[collection].meta,
            fields = meta.fields,
            url;

        url = Object.keys(fields).map(function(key) {
            return key + '={' + fields[key] + '}';
        }).join('&') + '&rows=' + meta.rows;

        console.log('Url for', collection, url);

        (function(c) {
            promises.push(fetch(baseUrl + url).then(function(response) {
                return response.json();
            })
            .then(function(rows) {
                schema[c] = rows;
            }));
        })(collection);
    }

    return Promise.all(promises).then(function() {
        fs.writeFile(dbName, JSON.stringify(schema, null, 4), function(err) {
            if (err) {
                Promise.reject('Failed to save JSON file: ' + err);
            }
        });
    });
}

module.exports = writeJSON;


text:
package sh.isaac.api.coordinate;

/**
 *
 * @author kec
 */
public interface LogicCoordinateProxy extends LogicCoordinate {
   /**
    * Gets the logic coordinate.
    *
    * @return a LogicCoordinate that specifies how to manage the retrieval and display of logic information.
    */
   LogicCoordinate getLogicCoordinate();

   @Override
   default int getClassifierNid() {
      return getLogicCoordinate().getClassifierNid();
   }

   @Override
   default int getDescriptionLogicProfileNid() {
      return getLogicCoordinate().getDescriptionLogicProfileNid();
   }

   @Override
   default int getInferredAssemblageNid() {
      return getLogicCoordinate().getInferredAssemblageNid();
   }

   @Override
   default int getStatedAssemblageNid() {
      return getLogicCoordinate().getStatedAssemblageNid();
   }

   @Override
   default int getConceptAssemblageNid() {
      return getLogicCoordinate().getConceptAssemblageNid();
   }

   @Override
   default int getDigraphIdentityNid() {
      return getLogicCoordinate().getDigraphIdentityNid();
   }

   @Override
   default LogicCoordinateImmutable toLogicCoordinateImmutable() {
      return getLogicCoordinate().toLogicCoordinateImmutable();
   }

}


text:
namespace Stripe.Radar
{
    using System.Collections.Generic;
    using System.Threading;
    using System.Threading.Tasks;

    public class EarlyFraudWarningService : Service<EarlyFraudWarning>,
        IListable<EarlyFraudWarning, EarlyFraudWarningListOptions>,
        IRetrievable<EarlyFraudWarning, EarlyFraudWarningGetOptions>
    {
        public EarlyFraudWarningService()
            : base(null)
        {
        }

        public EarlyFraudWarningService(IStripeClient client)
            : base(client)
        {
        }

        public override string BasePath => "/v1/radar/early_fraud_warnings";

        public virtual EarlyFraudWarning Get(string earlyFraudWarningId, EarlyFraudWarningGetOptions options = null, RequestOptions requestOptions = null)
        {
            return this.GetEntity(earlyFraudWarningId, options, requestOptions);
        }

        public virtual Task<EarlyFraudWarning> GetAsync(string earlyFraudWarningId, EarlyFraudWarningGetOptions options = null, RequestOptions requestOptions = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            return this.GetEntityAsync(earlyFraudWarningId, options, requestOptions, cancellationToken);
        }

        public virtual StripeList<EarlyFraudWarning> List(EarlyFraudWarningListOptions options = null, RequestOptions requestOptions = null)
        {
            return this.ListEntities(options, requestOptions);
        }

        public virtual Task<StripeList<EarlyFraudWarning>> ListAsync(EarlyFraudWarningListOptions options = null, RequestOptions requestOptions = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            return this.ListEntitiesAsync(options, requestOptions, cancellationToken);
        }

        public virtual IEnumerable<EarlyFraudWarning> ListAutoPaging(EarlyFraudWarningListOptions options = null, RequestOptions requestOptions = null)
        {
            return this.ListEntitiesAutoPaging(options, requestOptions);
        }
    }
}


text:
function Knex() {
  return Knex.initialize.apply(null, arguments);
}

// Run a "raw" query, though we can't do anything with it other than put
// it in a query statement.
Knex.raw = function(sql, bindings) {
  return new Raw(sql, bindings);
};

// Require the main constructors necessary for a `Knex` instance,
// each of which are injected with the current instance, so they maintain
// the correct client reference & grammar.
var Raw = require('./lib/raw');

// Doing it this way makes it easier to build for browserify.
var mysql = function() { return require('./lib/dialects/mysql'); };
var mysql2 = function() { return require('./lib/dialects/mysql2'); };
var maria = function() { return require('./lib/dialects/maria'); };
var pg = function() { return require('./lib/dialects/postgres'); };
var sqlite3 = function() { return require('./lib/dialects/sqlite3'); };
var websql = function() { return require('./lib/dialects/websql'); };

// The client names we'll allow in the `{name: lib}` pairing.
var Clients = Knex.Clients = {
  'mysql'      : mysql,
  'mysql2'     : mysql2,
  'maria'      : maria,
  'mariadb'    : maria,
  'mariasql'   : maria,
  'pg'         : pg,
  'postgres'   : pg,
  'postgresql' : pg,
  'sqlite'     : sqlite3,
  'sqlite3'    : sqlite3,
  'websql'     : websql
};

// Require lodash.
var _ = require('lodash');
var Promise = require('./lib/promise');

// Each of the methods which may be statically chained from knex.
var QueryInterface   = require('./lib/query/methods');
var SchemaInterface  = require('./lib/schema/methods');
var MigrateInterface = require('./lib/migrate/methods');

// Create a new "knex" instance with the appropriate configured client.
Knex.initialize = function(config) {
  var Dialect, client;
  var EventEmitter = require('events').EventEmitter;

  // The object we're potentially using to kick off an
  // initial chain. It is assumed that `knex` isn't a
  // constructor, so we have no reference to 'this' just
  // in case it's called with `new`.
  function knex(tableName) {
    var qb = new client.QueryBuilder;
    if (config.__transactor__) qb.transacting(config.__transactor__);
    return tableName ? qb.table(tableName) : qb;
  }

  // Hook up the "knex" object as an EventEmitter.
  var ee = new EventEmitter();
  for (var key in ee) {
    knex[key] = ee[key];
  }

  // The `__knex__` is used if you need to duck-type check whether this
  // is a knex builder, without a full on `instanceof` check.
  knex.VERSION = knex.__knex__  = '0.6.21';
  knex.raw = function(sql, bindings) {
    var raw = new client.Raw(sql, bindings);
    if (config.__transactor__) raw.transacting(config.__transactor__);
    return raw;
  };

  // Runs a new transaction, taking a container and returning a promise
  // for when the transaction is resolved.
  knex.transaction = function(container) {
    return new client.Transaction(container);
  };

  // Convenience method for tearing down the pool.
  knex.destroy = function (callback) {
    var pool = this.client.pool;
    var promise = new Promise(function(resolver, rejecter) {
      if (!pool) resolver();
      pool.destroy(function(err) {
        if (err) return rejecter(err);
        resolver();
      });
    });
    // Allow either a callback or promise interface for destruction.
    if (_.isFunction(callback)) {
      promise.exec(callback);
    } else {
      return promise;
    }
  };

  if (config.__client__) {
    client = config.__client__;
  } else {

    // Build the "client"
    var clientName = config.client || config.dialect;
    if (!Clients[clientName]) {
      throw new Error(clientName + ' is not a valid Knex client, did you misspell it?');
    }
    knex.toString = function() {
      return '[object Knex:' + clientName + ']';
    };
    Dialect = Clients[clientName]();
    client  = new Dialect(config);

    // Passthrough all "start" and "query" events to the knex object.
    client.on('start', function(obj) {
      knex.emit('start', obj);
    });
    client.on('query', function(obj) {
      knex.emit('query', obj);
    });
  }

  // Allow chaining methods from the root object, before
  // any other information is specified.
  _.each(QueryInterface, function(method) {
    knex[method] = function() {
      var builder = knex();
      return builder[method].apply(builder, arguments);
    };
  });
  knex.client = client;

  // Namespaces for additional library components.
  var schema  = knex.schema  = {};
  var migrate = knex.migrate = {};

  // Attach each of the `Schema` "interface" methods directly onto to `knex.schema` namespace, e.g.:
  // `knex.schema.table('tableName', function() {...`
  // `knex.schema.createTable('tableName', function() {...`
  // `knex.schema.dropTableIfExists('tableName');`
  _.each(SchemaInterface, function(key) {
    schema[key] = function() {
      if (!client.SchemaBuilder) client.initSchema();
      var builder = new client.SchemaBuilder();
      if (config.__transactor__) builder.transacting(config.__transactor__);
      return builder[key].apply(builder, arguments);
    };
  });

  // Attach each of the `Migrator` "interface" methods directly onto to `knex.migrate` namespace, e.g.:
  // knex.migrate.latest().then(...
  // knex.migrate.currentVersion(...
  _.each(MigrateInterface, function(method) {
    migrate[method] = function() {
      if (!client.Migrator) client.initMigrator();
      var migrator = new client.Migrator(knex);
      return migrator[method].apply(migrator, arguments);
    };
  });

  // Add a few additional misc utils.
  knex.utils = _.extend({}, require('./lib/utils'));

  return knex;
};

module.exports = Knex;


text:
unsigned int debug(const char *format, ...) {
    va_list argp;
    va_start(argp, format);
    return vprintf(format, argp);
}
#endif

//Parse G-code command
int gcode_parse(const char *s) {
    //Create a copy of the input that we can modify
    char command[strlen(s)+1];
    strncpy(command, s, strlen(s)+1);
    //debug("Command length after copy: %u (%s)\n", (unsigned int)strlen(command), command);

    //Filter out comments, newlines and trailing spaces
    unsigned int i = 0;
    while (command[i] != ';' && command[i] != '\n' && command[i] != '\0') i++;
    while (command[i-1] == ' ') i--;
    command[i] = '\0';
    debug("Command length after comment filter: %u (%s)\n", (unsigned int)strlen(command), command);

    //Extract Xnnn
    char type = 'X';
    int id = -1;
    if (sscanf(command, "%c%d", &type, &id) == 0) {
        debug("Something is wrong with sscanf command");
        return 1;
    }

    //Lookup G-code function in lookup tree
    gcode_type_t *gt;
    gcode_function_t *gf;
    for (gt = gcode_types; gt->type != 0; gt++) if (gt->type == type) break;
    //If a valid subtree was found (e.g 'G' or 'M')
    if (gt-> type != 0) {
        //Run until nnn part is found
        //The last element in array contains function without nnn
        for (gf = gt->subtree; gf->type != 0; gf++) if (gf->id == id) break;
        //Run function
        return (*(gf->fp))(command);
    } else {
        debug("Not a valid G-code command\n");
        return 2;
    }

    return 0;
}

// Extract G-code parameter (similar to strtok)
int gcode_get_parameter(char **s, gcode_parameter_t *gp) {
    //Get first Xnnn
    int n = sscanf(*s, "%c%f", &(gp->type), &(gp->value));
    //Move pointer forward;
    while (*((*s)++) != ' ') if (**s == '\0') break;
    if (n == 1) gp->value = 0.0;
    return n;
}


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

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

  <title>Qt 4.8: Q3AsciiCache Class Reference</title>
  <link rel="stylesheet" type="text/css" href="style/style.css" />

  <link rel="stylesheet" type="text/css" href="style/superfish.css" />
  <link rel="stylesheet" type="text/css" href="style/narrow.css" />

      Home

    Qt Reference Documentation

Qt HOME

DEV

          DOC

BLOG

Qt 4.8

ALL VERSIONS

API Lookup

Class index

Function index

Modules

Namespaces

Global Declarations

QML elements

Qt Topics

Programming with Qt

Device UIs & Qt Quick

UI Design with Qt

Supported Platforms

Qt and Key Technologies

How-To's and Best Practices

Examples

Examples

Tutorials

Demos

QML Examples

          Search index:

          <form id="qtdocsearch" action="" onsubmit="return false;">
            <fieldset>
              <input type="text" name="searchstring" id="pageType" value="" />

 Close

All | API | Articles | Examples

 results:

            </fieldset>
          </form>

            API Lookup

Class index

Function index

Modules

Namespaces

Global Declarations

QML elements

            Qt Topics

Programming with Qt

Device UIs & Qt Quick

UI Design with Qt

Supported Platforms

Qt and Key Technologies

How-To's and Best Practices

            Examples

Examples

Tutorials

Demos

QML Examples

Home

Modules

Qt3SupportLight

Q3AsciiCache

A

A

A

                Print

Contents

Public Functions

Detailed Description

Q3AsciiCache Class Reference

The Q3AsciiCache class is a template class that provides a cache based on char* keys. More...

 #include <Q3AsciiCache>

This class is part of the Qt 3 support library. It is provided to keep old source code working. We strongly advise against using it in new code. See Porting to Qt 4 for more information.

Inherits: Q3PtrCollection.

List of all members, including inherited members

Public Functions

 	Q3AsciiCache ( int maxCost = 100, int size = 17, bool caseSensitive = true, bool copyKeys = true )

 	~Q3AsciiCache ()

 type * 	find ( const char * k, bool ref = true ) const

 bool 	insert ( const char * k, const type * d, int c = 1, int p = 0 )

 bool 	isEmpty () const

 int 	maxCost () const

 bool 	remove ( const char * k )

 void 	setMaxCost ( int m )

 uint 	size () const

 void 	statistics () const

 type * 	take ( const char * k )

 int 	totalCost () const

 type * 	operator[] ( const char * k ) const

Reimplemented Public Functions

 virtual void 	clear ()

 virtual uint 	count () const

4 public functions inherited from Q3PtrCollection

Additional Inherited Members

2 protected functions inherited from Q3PtrCollection

Detailed Description

The Q3AsciiCache class is a template class that provides a cache based on char* keys.

Q3AsciiCache is implemented as a template class. Define a template instance Q3AsciiCache<X> to create a cache that operates on pointers to X (X*).

A cache is a least recently used (LRU) list of cache items. The cache items are accessed via <tt>char*</tt> keys. For Unicode keys use the Q3Cache template instead, which uses QString keys. A Q3Cache has the same performace as a Q3AsciiCache.

Each cache item has a cost. The sum of item costs, totalCost(), will not exceed the maximum cache cost, maxCost(). If inserting a new item would cause the total cost to exceed the maximum cost, the least recently used items in the cache are removed.

Apart from insert(), by far the most important function is find() (which also exists as operator[]()). This function looks up an item, returns it, and by default marks it as being the most recently used item.

There are also methods to remove() or take() an object from the cache. Calling setAutoDelete(TRUE) tells the cache to delete items that are removed. The default is to not delete items when then are removed (i.e., remove() and take() are equivalent).

When inserting an item into the cache, only the pointer is copied, not the item itself. This is called a shallow copy. It is possible to make the cache copy all of the item's data (known as a deep copy) when an item is inserted. insert() calls the virtual function Q3PtrCollection::newItem() for the item to be inserted. Inherit a cache and reimplement newItem() if you want deep copies.

When removing a cache item the virtual function Q3PtrCollection::deleteItem() is called. Its default implementation in Q3AsciiCache is to delete the item if auto-deletion is enabled.

There is a Q3AsciiCacheIterator which may be used to traverse the items in the cache in arbitrary order.

See also Q3AsciiCacheIterator, Q3Cache, and Q3IntCache.

Member Function Documentation

Q3AsciiCache::Q3AsciiCache ( int maxCost = 100, int size = 17, bool caseSensitive = true, bool copyKeys = true )

Constructs a cache whose contents will never have a total cost greater than maxCost and which is expected to contain less than size items.

size is actually the size of an internal hash array; it's usually best to make it prime and at least 50% bigger than the largest expected number of items in the cache.

Each inserted item has an associated cost. When inserting a new item, if the total cost of all items in the cache will exceed maxCost, the cache will start throwing out the older (least recently used) items until there is enough room for the new item to be inserted.

If caseSensitive is TRUE (the default), the cache keys are case sensitive; if it is FALSE, they are case-insensitive. Case-insensitive comparison only affects the 26 letters in US-ASCII. If copyKeys is TRUE (the default), Q3AsciiCache makes a copy of the cache keys, otherwise it copies just the const char * pointer - slightly faster if you can guarantee that the keys will never change, but very risky.

Q3AsciiCache::~Q3AsciiCache ()

Removes all items from the cache and destroys it. All iterators that access this cache will be reset.

void Q3AsciiCache::clear ()<tt> [virtual]</tt>

Reimplemented from Q3PtrCollection::clear().

Removes all items from the cache, and deletes them if auto-deletion has been enabled.

All cache iterators that operate on this cache are reset.

See also remove() and take().

uint Q3AsciiCache::count () const<tt> [virtual]</tt>

Reimplemented from Q3PtrCollection::count().

Returns the number of items in the cache.

See also totalCost() and size().

type * Q3AsciiCache::find ( const char * k, bool ref = true ) const

Returns the item with key k, or 0 if the key does not exist in the cache. If ref is TRUE (the default), the item is moved to the front of the least recently used list.

If there are two or more items with equal keys, the one that was inserted last is returned.

bool Q3AsciiCache::insert ( const char * k, const type * d, int c = 1, int p = 0 )

Inserts the item d into the cache using key k, and with an associated cost of c. Returns TRUE if the item is successfully inserted. Returns FALSE if the item is not inserted, for example, if the cost of the item exceeds maxCost().

The cache's size is limited, and if the total cost is too high, Q3AsciiCache will remove old, least recently used items until there is room for this new item.

Items with duplicate keys can be inserted.

The parameter p is internal and should be left at the default value (0).

Warning: If this function returns FALSE, you must delete d yourself. Additionally, be very careful about using d after calling this function, because any other insertions into the cache, from anywhere in the application or within Qt itself, could cause the object to be discarded from the cache and the pointer to become invalid.

bool Q3AsciiCache::isEmpty () const

Returns TRUE if the cache is empty; otherwise returns FALSE.

int Q3AsciiCache::maxCost () const

Returns the maximum allowed total cost of the cache.

See also setMaxCost() and totalCost().

bool Q3AsciiCache::remove ( const char * k )

Removes the item with key k and returns TRUE if the item was present in the cache; otherwise returns FALSE.

The item is deleted if auto-deletion has been enabled, i.e., if you have called setAutoDelete(TRUE).

If there are two or more items with equal keys, the one that was inserted last is removed.

All iterators that refer to the removed item are set to point to the next item in the cache's traversal order.

See also take() and clear().

void Q3AsciiCache::setMaxCost ( int m )

Sets the maximum allowed total cost of the cache to m. If the current total cost is greater than m, some items are removed immediately.

See also maxCost() and totalCost().

uint Q3AsciiCache::size () const

Returns the size of the hash array used to implement the cache. This should be a bit bigger than count() is likely to be.

void Q3AsciiCache::statistics () const

A debug-only utility function. Prints out cache usage, hit/miss, and distribution information using qDebug(). This function does nothing in the release library.

type * Q3AsciiCache::take ( const char * k )

Takes the item associated with k out of the cache without deleting it and returns a pointer to the item taken out, or 0 if the key does not exist in the cache.

If there are two or more items with equal keys, the one that was inserted last is taken.

All iterators that refer to the taken item are set to point to the next item in the cache's traversal order.

See also remove() and clear().

int Q3AsciiCache::totalCost () const

Returns the total cost of the items in the cache. This is an integer in the range 0 to maxCost().

See also setMaxCost().

type * Q3AsciiCache::operator[] ( const char * k ) const

Returns the item with key k, or 0 if k does not exist in the cache, and moves the item to the front of the least recently used list.

If there are two or more items with equal keys, the one that was inserted last is returned.

This is the same as find( k, TRUE ).

See also find().

      <acronym title="Copyright">©</acronym> 2013 Digia Plc and/or its
      subsidiaries. Documentation contributions included herein are the copyrights of
      their respective owners.

      The documentation provided herein is licensed under the terms of the
      GNU Free Documentation
      License version 1.3 as published by the Free Software Foundation.

      Documentation sources may be obtained from
      www.qt-project.org.

      Digia, Qt and their respective logos are trademarks of Digia Plc
      in Finland and/or other countries worldwide. All other trademarks are property
      of their respective owners. Privacy Policy


text:
<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="apple-touch-icon" href="apple-touch-icon.png">

        <link rel="stylesheet" href="css/normalize.css">
        <link rel="stylesheet" href="css/main.css">
        <link rel="stylesheet" href="css/annotorious.css">
        <link href="css/bootstrap.min.css" rel="stylesheet">

        <link rel="stylesheet" href="css/site.css">
        <link rel="stylesheet" href="css/gloss.css">

                    Tap on a annotation to find out more, or drag to define a new annotation.

Hide annotations

The mantis shrimp can break aquarium glass.

Photograph by prilfish on Flickr. Used under CC 2.0/By


text:
#import "SDDeviceHelper.h"
#import <mach/mach.h>

@implementation SDDeviceHelper

+ (NSUInteger)totalMemory {
    return (NSUInteger)[[NSProcessInfo processInfo] physicalMemory];
}

+ (NSUInteger)freeMemory {
    mach_port_t host_port = mach_host_self();
    mach_msg_type_number_t host_size = sizeof(vm_statistics_data_t) / sizeof(integer_t);
    vm_size_t page_size;
    vm_statistics_data_t vm_stat;
    kern_return_t kern;

    kern = host_page_size(host_port, &page_size);
    if (kern != KERN_SUCCESS) return 0;
    kern = host_statistics(host_port, HOST_VM_INFO, (host_info_t)&vm_stat, &host_size);
    if (kern != KERN_SUCCESS) return 0;
    return vm_stat.free_count * page_size;
}

@end


text:
/**
 * @file Distance Representation
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author Fred Ludlow <fred.ludlow@gmail.com>
 * @private
 */

import { Color } from 'three'

import { RepresentationRegistry } from '../globals'
import { defaults } from '../utils'
import { DistancePicker } from '../utils/picker'
import { uniformArray, uniformArray3 } from '../math/array-utils'
import BitArray from '../utils/bitarray'
import MeasurementRepresentation, { MeasurementRepresentationParameters } from './measurement-representation'
import Selection from '../selection/selection'
import BondStore from '../store/bond-store'
import TextBuffer, { TextBufferData, TextBufferParameters } from '../buffer/text-buffer'
import WideLineBuffer from '../buffer/wideline-buffer'
import CylinderBuffer, { CylinderBufferData } from '../buffer/cylinder-buffer'
import { getFixedLengthDashData } from '../geometry/dash'
import Viewer from '../viewer/viewer';
import { Structure } from '../ngl';
import StructureView from '../structure/structure-view';
import { BondDataFields, BondDataParams, BondData } from '../structure/structure-data';
import { StructureRepresentationData } from './structure-representation';
import CylinderGeometryBuffer from '../buffer/cylindergeometry-buffer';

/**
 * Distance representation parameter object.
 * @typedef {Object} DistanceRepresentationParameters - distance representation parameters
 * @mixes RepresentationParameters
 * @mixes StructureRepresentationParameters
 * @mixes MeasurementRepresentationParameters
 *
 * @property {String} labelUnit - distance unit (e.g. "angstrom" or "nm"). If set, a distance
 *                                symbol is appended to the label (i.e. 'nm' or '\u00C5'). In case of 'nm', the
 *                                distance value is computed in nanometers instead of Angstroms.
 * @property {Array[]} atomPair - list of pairs of selection strings (see {@link Selection})
 *                                or pairs of atom indices. Using atom indices is much more
 *                                efficient when the representation is updated often, e.g. by
 *                                changing the selection or the atom positions, as there
 *                                are no selection strings to be evaluated.
 */
export interface DistanceRepresentationParameters extends MeasurementRepresentationParameters {
  labelUnit: string
  atomPair: AtomPair
  useCylinder: boolean
}
export type AtomPair = (number|string)[][]
/**
 * Distance representation
 */
class DistanceRepresentation extends MeasurementRepresentation {
  protected labelUnit: string
  protected atomPair: AtomPair
  protected useCylinder: boolean
  protected distanceBuffer: WideLineBuffer|CylinderGeometryBuffer
  /**
   * Create Distance representation object
   * @example
   * stage.loadFile( "rcsb://1crn" ).then( function( o ){
   *     o.addRepresentation( "cartoon" );
   *     // either give selections (uses first selected atom) ...
   *     var atomPair = [ [ "1.CA", "4.CA" ], [ "7.CA", "13.CA" ] ];
   *     // or atom indices
   *     var atomPair = [ [ 8, 28 ], [ 173, 121 ] ];
   *     o.addRepresentation( "distance", { atomPair: atomPair } );
   *     stage.autoView();
   * } );
   * @param {Structure} structure - the structure to be represented
   * @param {Viewer} viewer - a viewer object
   * @param {DistanceRepresentationParameters} params - distance representation parameters
   */
  constructor (structure: Structure, viewer: Viewer, params: Partial<DistanceRepresentationParameters>) {
    super(structure, viewer, params)

    this.type = 'distance'

    this.parameters = Object.assign({
      radialSegments: true,
      openEnded: true,
      disableImpostor: true,
      labelUnit: {
        type: 'select',
        rebuild: true,
        options: { '': '', angstrom: 'angstrom', nm: 'nm' }
      },
      useCylinder: {
        type: 'boolean', rebuild: true
      },
      atomPair: {
        type: 'hidden', rebuild: true
      }
    }, this.parameters)

    this.init(params)
  }

  init (params: Partial<DistanceRepresentationParameters>) {
    const p = params || {}
    p.linewidth = defaults(p.linewidth, 5.0)
    p.radiusType = defaults(p.radiusType, 'size')
    p.radiusSize = defaults(p.radiusSize, 0.2)

    this.labelUnit = defaults(p.labelUnit, '')
    this.useCylinder = defaults(p.useCylinder, false)
    this.atomPair = defaults(p.atomPair, [])

    super.init(p)
  }

  getDistanceData (sview: StructureView, atomPair: AtomPair) {
    let n = atomPair.length
    const text = new Array(n)
    let position = new Float32Array(n * 3)
    const sele1 = new Selection()
    const sele2 = new Selection()

    const bondStore = new BondStore()

    const ap1 = sview.getAtomProxy()
    const ap2 = sview.getAtomProxy()

    let j = 0 // Skipped pairs
    const selected = sview.getAtomSet()

    atomPair.forEach((pair, i) => {
      let v1 = pair[ 0 ]
      let v2 = pair[ 1 ]

      if (typeof(v1) === 'number' && Number.isInteger(v1) && typeof(v2) === 'number' && Number.isInteger(v2)) {
        if (selected.get(v1) && selected.get(v2)) {
          ap1.index = v1
          ap2.index = v2
        } else {
          j += 1
          return
        }
      } else {
        sele1.setString(v1 as string)
        sele2.setString(v2 as string)

        var atomIndices1 = sview.getAtomIndices(sele1)
        var atomIndices2 = sview.getAtomIndices(sele2)

        if (atomIndices1!.length && atomIndices2!.length) {
          ap1.index = atomIndices1![ 0 ]
          ap2.index = atomIndices2![ 0 ]
        } else {
          j += 1
          return
        }
      }

      bondStore.addBond(ap1, ap2, 1)

      i -= j
      var d = ap1.distanceTo(ap2)
      switch (this.labelUnit) {
        case 'angstrom':
          text[ i ] = d.toFixed(2) + ' ' + String.fromCharCode(0x212B)
          break
        case 'nm':
          text[ i ] = (d / 10).toFixed(2) + ' nm'
          break
        default:
          text[ i ] = d.toFixed(2)
          break
      }

      var i3 = i * 3
      position[ i3 + 0 ] = (ap1.x + ap2.x) / 2
      position[ i3 + 1 ] = (ap1.y + ap2.y) / 2
      position[ i3 + 2 ] = (ap1.z + ap2.z) / 2
    })

    if (j > 0) {
      n -= j
      position = position.subarray(0, n * 3)
    }

    var bondSet = new BitArray(bondStore.count, true)

    return {
      text: text,
      position: position,
      bondSet: bondSet,
      bondStore: bondStore
    }
  }

  getBondData (sview: StructureView, what: BondDataFields, params: BondDataParams): BondData {
    const bondData = sview.getBondData(this.getBondParams(what, params))
    if (bondData.picking) {
      bondData.picking = new DistancePicker(
        bondData.picking.array,
        bondData.picking.structure,
        params.bondStore!
      ) as any
    }
    return bondData
  }

  createData (sview: StructureView) {
    if (!sview.atomCount || !this.atomPair.length) return

    const n = this.atomPair.length
    const c = new Color(this.labelColor)
    const distanceData = this.getDistanceData(sview, this.atomPair)

    this.textBuffer = new TextBuffer({
      position: distanceData.position,
      size: uniformArray(n, this.labelSize),
      color: uniformArray3(n, c.r, c.g, c.b),
      text: distanceData.text
    } as TextBufferData, this.getLabelBufferParams() as TextBufferParameters)

    const bondParams = {
      bondSet: distanceData.bondSet,
      bondStore: distanceData.bondStore
    }

    const bondData = this.getBondData(
      sview,
      { position: true, color: true, picking: true, radius: this.useCylinder },
      bondParams
    )

    if (this.useCylinder) {
      this.distanceBuffer = new CylinderBuffer(
        bondData as CylinderBufferData,
        this.getBufferParams({
          openEnded: this.openEnded,
          radialSegments: this.radialSegments,
          disableImpostor: this.disableImpostor,
          dullInterior: true
        })
      ) as CylinderGeometryBuffer
    } else {
      this.distanceBuffer = new WideLineBuffer(
        getFixedLengthDashData(bondData as CylinderBufferData),
        this.getBufferParams({
          linewidth: this.linewidth,
          visible: this.lineVisible,
          opacity: this.lineOpacity
        })
      )
    }

    return {
      bondSet: distanceData.bondSet,
      bondStore: distanceData.bondStore,
      position: distanceData.position,
      bufferList: [ this.textBuffer, this.distanceBuffer ]
    }
  }

  updateData (what: BondDataFields, data: StructureRepresentationData) {
    super.updateData(what, data)

    const bondParams = {
      bondSet: data.bondSet,
      bondStore: data.bondStore
    }

    const bondData = this.getBondData(data.sview as StructureView, what, bondParams)
    const distanceData = {}

    if (!what || what.color) {
      Object.assign( distanceData, {
        color: bondData.color,
        color2: bondData.color2
      })
    }

    if (!what || what.radius) {
      Object.assign( distanceData, {radius: bondData.radius})
    }

    (this.distanceBuffer as CylinderGeometryBuffer).setAttributes(distanceData)
  }

  setParameters (params: Partial<DistanceRepresentationParameters>) {
    let rebuild = false
    const what = {}

    super.setParameters(params, what, rebuild)

    if (!this.useCylinder) {
      if (params && params.lineOpacity) {
        (this.distanceBuffer as WideLineBuffer).setParameters({ opacity: params.lineOpacity })
      }
      if (params && params.opacity !== undefined) {
        (this.distanceBuffer as WideLineBuffer).setParameters({ opacity: this.lineOpacity })
      }
      if (params && params.linewidth) {
        (this.distanceBuffer as WideLineBuffer).setParameters({ linewidth: params.linewidth })
      }
    }

    return this
  }
}

RepresentationRegistry.add('distance', DistanceRepresentation)

export default DistanceRepresentation


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>pt.up.pteid4j</groupId>
  <artifactId>pteid4j</artifactId>
  <version>0.2.0-SNAPSHOT</version>
  <packaging>pom</packaging>
  <name>PTeID4J</name>
  <description>Portuguese e-ID for Java</description>
  <inceptionYear>2011</inceptionYear>
  <url>https://github.com/andremanuelbarbosa/pteid4j</url>

  <developers>
    <developer>
      <name>Andre Barbosa</name>
      <email>andremanuelbarbosa@gmail.com</email>
      <url>http://www.andremanuelbarbosa.com/</url>
    </developer>
  </developers>

  <organization>
    <name>Universidade do Porto</name>
    <url>http://www.up.pt/</url>
  </organization>

  <issueManagement>
    <url>https://github.com/andremanuelbarbosa/pteid4j/issues</url>
    <system>GitHub Issues</system>
  </issueManagement>

  <scm>
    <url>https://github.com/andremanuelbarbosa/pteid4j</url>
    <connection>scm:git:git://github.com/andremanuelbarbosa/pteid4j.git</connection>
    <developerConnection>scm:git:git://github.com/andremanuelbarbosa/pteid4j.git</developerConnection>
  </scm>

  <repositories>
    <repository>
      <id>andremanuelbarbosa-cloudbees-releases</id>
      <url>http://repository-andremanuelbarbosa.forge.cloudbees.com/release/</url>
      <releases>
        <enabled>true</enabled>
      </releases>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
    </repository>

    <repository>
      <id>andremanuelbarbosa-cloudbees-snapshots</id>
      <url>http://repository-andremanuelbarbosa.forge.cloudbees.com/snapshot/</url>
      <releases>
        <enabled>false</enabled>
      </releases>
      <snapshots>
        <enabled>true</enabled>
      </snapshots>
    </repository>
  </repositories>

  <distributionManagement>
    <downloadUrl>https://github.com/andremanuelbarbosa/pteid4j</downloadUrl>
    <repository>
      <id>andremanuelbarbosa-cloudbees-release-repo</id>
      <url>dav:https://repository-andremanuelbarbosa.forge.cloudbees.com/release/</url>
    </repository>
    <snapshotRepository>
      <id>andremanuelbarbosa-cloudbees-snapshot-repo</id>
      <url>dav:https://repository-andremanuelbarbosa.forge.cloudbees.com/snapshot/</url>
    </snapshotRepository>
  </distributionManagement>

  <properties>
    <!-- Logging -->
    <slf4j.version>1.7.5</slf4j.version>
    <logback.version>1.0.13</logback.version>

    <!-- Testing -->
    <junit.version>4.11</junit.version>
    <mockito.version>1.9.5</mockito.version>
    <cucumber.version>1.1.6</cucumber.version>

    <!-- Encoding -->
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.sourceEncoding>UTF-8</project.reporting.sourceEncoding>
  </properties>

  <dependencies>
    <!-- Logging -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j.version}</version>
    </dependency>

    <!-- Testing -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-core</artifactId>
      <version>${mockito.version}</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <dependencyManagement>
    <dependencies>
      <!-- Logging -->
      <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>${logback.version}</version>
      </dependency>

      <!-- Testing -->
      <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-java</artifactId>
        <version>${cucumber.version}</version>
        <scope>test</scope>
      </dependency>

      <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-junit</artifactId>
        <version>${cucumber.version}</version>
        <scope>test</scope>
      </dependency>

      <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-spring</artifactId>
        <version>${cucumber.version}</version>
        <scope>test</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <build>
    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-clean-plugin</artifactId>
          <version>2.5</version>
        </plugin>

        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-resources-plugin</artifactId>
          <version>2.6</version>
        </plugin>

        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.1</version>
          <configuration>
            <source>1.7</source>
            <target>1.7</target>
          </configuration>
        </plugin>

        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.17</version>
          <configuration>
            <excludes>
              <exclude>**/*IntegrationTest.java</exclude>
            </excludes>
          </configuration>
        </plugin>

        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-jar-plugin</artifactId>
          <version>2.4</version>
        </plugin>

        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.4</version>
        </plugin>

        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.1</version>
        </plugin>
      </plugins>
    </pluginManagement>

    <extensions>
      <extension>
        <groupId>org.apache.maven.wagon</groupId>
        <artifactId>wagon-webdav-jackrabbit</artifactId>
        <version>2.2</version>
      </extension>
    </extensions>
  </build>
</project>


text:
<?php

require_once 'phing/tasks/ext/phpunit/formatter/PHPUnitResultFormatter.php';

/**
 * Prints plain text output of the test to a specified Writer.
 *
 * @author Michiel Rook <mrook@php.net>
 * @version $Id$
 * @package phing.tasks.ext.phpunit.formatter
 * @since 2.1.0
 */
class PlainPHPUnitResultFormatter extends PHPUnitResultFormatter
{
    private $inner = "";

    public function getExtension()
    {
        return ".txt";
    }

    public function getPreferredOutfile()
    {
        return "testresults";
    }

    public function startTestSuite(PHPUnit_Framework_TestSuite $suite)
    {
        parent::startTestSuite($suite);

        $this->inner = "";
    }

    public function endTestSuite(PHPUnit_Framework_TestSuite $suite)
    {
        if ($suite->getName() == 'AllTests')
        {
            return false;
        }

        $sb = "Testsuite: " . $suite->getName() . "\n";
        $sb.= "Tests run: " . $this->getRunCount();
        $sb.= ", Failures: " . $this->getFailureCount();
        $sb.= ", Errors: " . $this->getErrorCount();
        $sb.= ", Incomplete: " . $this->getIncompleteCount();
        $sb.= ", Skipped: " . $this->getSkippedCount();
        $sb.= ", Time elapsed: " . sprintf('%0.5f', $this->getElapsedTime()) . " s\n";

        if ($this->out != NULL)
        {
            $this->out->write($sb);
            $this->out->write($this->inner);
        }

        parent::endTestSuite($suite);
    }

    public function addError(PHPUnit_Framework_Test $test, Exception $e, $time)
    {
        parent::addError($test, $e, $time);

        $this->formatError("ERROR", $test, $e);
    }

    public function addFailure(PHPUnit_Framework_Test $test, PHPUnit_Framework_AssertionFailedError $e, $time)
    {
        parent::addFailure($test, $e, $time);
        $this->formatError("FAILED", $test, $e);
    }

    public function addIncompleteTest(PHPUnit_Framework_Test $test, Exception $e, $time)
    {
        parent::addIncompleteTest($test, $e, $time);

        $this->formatError("INCOMPLETE", $test);
    }

    public function addSkippedTest(PHPUnit_Framework_Test $test, Exception $e, $time)
    {
        parent::addSkippedTest($test, $e, $time);
        $this->formatError("SKIPPED", $test);
    }

    private function formatError($type, PHPUnit_Framework_Test $test, Exception $e = null)
    {
        if ($test != null)
        {
            $this->endTest($test, time());
        }

        $this->inner.= $test->getName() . " " . $type . "\n";

        if ($e !== null) {
            $this->inner.= $e->getMessage() . "\n";
            // $this->inner.= PHPUnit_Util_Filter::getFilteredStackTrace($e, true) . "\n";
        }
    }

    public function endTestRun()
    {
        parent::endTestRun();

        if ($this->out != NULL)
        {
            $this->out->close();
        }
    }
}


text:
package org.apache.ranger.authorization.kylin.authorizer;

import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.kylin.common.KylinConfig;
import org.apache.kylin.metadata.project.ProjectInstance;
import org.apache.kylin.metadata.project.ProjectManager;
import org.apache.kylin.metadata.project.RealizationEntry;
import org.apache.kylin.rest.util.AclEvaluate;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.util.ReflectionTestUtils;

/**
*
* Here we plug the Ranger RangerKylinAuthorizer into Kylin.
*
* A custom RangerAdminClient is plugged into Ranger in turn, which loads security policies from a local file.
* These policies were generated in the Ranger Admin UI for a kylin service called "kylinTest":
*
* a) A user "kylin" can do all permissions(contains "ADMIN", "MANAGEMENT", "OPERATION", "QUERY")
* on all kylin projects;
* b) A user "zhangqiang" can do a "ADMIN" on the project "test_project",
* and do a "OPERATION" on the project "kylin_project";
* c) A user "yuwen" can do a "ADMIN" on the project "test_project",
* and do a "OPERATION" on the project "kylin_project";
* d) A user "admin" has role "ROLE_ADMIN",
* and the others have role "ROLE_USER" by mock for test.
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath*:applicationContext.xml", "classpath*:kylinSecurity.xml" })
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class RangerKylinAuthorizerTest {
	private static final Map<String, ProjectInstance> uuid2Projects = new HashMap<>();

	private static final Map<String, ProjectInstance> name2Projects = new HashMap<>();

	private static final String ADMIN = "admin";

	private static final String KYLIN = "kylin";

	private static final String ZHANGQIANG = "zhangqiang";

	private static final String YUWEN = "yuwen";

	private static final String LEARN_PROJECT = "learn_project";

	private static final String TEST_PROJECT = "test_project";

	private static final String KYLIN_PROJECT = "kylin_project";

	private static final String[] PROJECTNAMES = new String[] { LEARN_PROJECT, TEST_PROJECT, KYLIN_PROJECT };

	private static final String ROLE_ADMIN = "ADMIN";

	private static final String ROLE_USER = "USER";

	@Autowired
	private AclEvaluate aclEvaluate;

	@BeforeClass
	public static void setup() throws Exception {
		// set kylin conf path
		System.setProperty(KylinConfig.KYLIN_CONF, "src/test/resources");

		// init kylin projects
		initKylinProjects();

		// mock kylin projects, to match projectUuid and projectName for kylin
		mockKylinProjects();
	}

	@AfterClass
	public static void cleanup() throws Exception {
		// do nothing
	}

	/**
	 * Help function: init kylin projects
	 */
	private static void initKylinProjects() {
		for (String projectName : PROJECTNAMES) {
			ProjectInstance projectInstance = getProjectInstance(projectName);
			name2Projects.put(projectName, projectInstance);

			uuid2Projects.put(projectInstance.getUuid(), projectInstance);
		}
	}

	/**
	 * Help function: mock kylin projects, to match projectUuid and projectName
	 */
	private static void mockKylinProjects() {
		KylinConfig kylinConfig = KylinConfig.getInstanceFromEnv();
		ProjectManager projectManager = mock(ProjectManager.class);

		@SuppressWarnings({ "rawtypes", "unchecked" })
		Map<Class, Object> managersCache = (Map<Class, Object>) ReflectionTestUtils.getField(kylinConfig,
				"managersCache");
		managersCache.put(ProjectManager.class, projectManager);

		Answer<ProjectInstance> answer = new Answer<ProjectInstance>() {
			@Override
			public ProjectInstance answer(InvocationOnMock invocation) throws Throwable {
				Object[] args = invocation.getArguments();
				if (args == null || args.length == 0) {
					return null;
				}
				String uuid = (String) args[0];
				return uuid2Projects.get(uuid);
			}
		};
		when(projectManager.getPrjByUuid(anyString())).thenAnswer(answer);
	}

	/**
	 * Help function: get random project instance for test
	 */
	private static ProjectInstance getRandomProjectInstance() {
		String name = RandomStringUtils.randomAlphanumeric(10) + "-project";
		return getProjectInstance(name);
	}

	/**
	 * Help function: get specific project instance for test
	 */
	private static ProjectInstance getProjectInstance(String name) {
		String owner = null;
		String description = null;
		LinkedHashMap<String, String> overrideProps = null;
		List<RealizationEntry> realizationEntries = null;
		List<String> models = null;

		return ProjectInstance.create(name, owner, description, overrideProps, realizationEntries, models);
	}

	// No.1 hasProjectReadPermission test start
	/**
	 * no credentials read any project failed
	 */
	@Test(expected = AuthenticationCredentialsNotFoundException.class)
	public void readProjectAnyWithoutCredentials() {
		ProjectInstance project = getRandomProjectInstance();
		aclEvaluate.hasProjectReadPermission(project);
	}

	/**
	 * admin read all projects sueecss
	 */
	@Test
	@WithMockUser(username = ADMIN, roles = { ROLE_ADMIN })
	public void readProjectAllAsRoleAdmin() {
		for (ProjectInstance project : uuid2Projects.values()) {
			boolean result = aclEvaluate.hasProjectReadPermission(project);
			Assert.assertTrue(result);
		}
	}

	/**
	 * kylin read all projects success
	 */
	@Test
	@WithMockUser(username = KYLIN, roles = { ROLE_USER })
	public void readProjectAllWithAdminPermission() {
		for (ProjectInstance project : uuid2Projects.values()) {
			boolean result = aclEvaluate.hasProjectReadPermission(project);
			Assert.assertTrue(result);
		}
	}

	/**
	 * zhangqiang read test_project success
	 */
	@Test
	@WithMockUser(username = ZHANGQIANG, roles = { ROLE_USER })
	public void readProjectTestWithAdminPermission() {
		ProjectInstance project = name2Projects.get(TEST_PROJECT);
		boolean result = aclEvaluate.hasProjectReadPermission(project);
		Assert.assertTrue(result);
	}

	/**
	 * zhangqiang read kylin_project success
	 */
	@Test
	@WithMockUser(username = ZHANGQIANG, roles = { ROLE_USER })
	public void readProjectKylinWithOperationPermission() {
		ProjectInstance project = name2Projects.get(KYLIN_PROJECT);
		boolean result = aclEvaluate.hasProjectReadPermission(project);
		Assert.assertTrue(result);
	}

	/**
	 * yuwen read test_project success
	 */
	@Test
	@WithMockUser(username = YUWEN, roles = { ROLE_USER })
	public void readProjectTestWithManagementPermission() {
		ProjectInstance project = name2Projects.get(TEST_PROJECT);
		boolean result = aclEvaluate.hasProjectReadPermission(project);
		Assert.assertTrue(result);
	}

	/**
	 * yuwen read kylin_project success
	 */
	@Test
	@WithMockUser(username = YUWEN, roles = { ROLE_USER })
	public void readProjectKylinWithQueryPermission() {
		ProjectInstance project = name2Projects.get(KYLIN_PROJECT);
		boolean result = aclEvaluate.hasProjectReadPermission(project);
		Assert.assertTrue(result);
	}

	/**
	 * yuwen read learn_project failed
	 */
	@Test
	@WithMockUser(username = YUWEN, roles = { ROLE_USER })
	public void readProjectLearnWithoutPermission() {
		ProjectInstance project = name2Projects.get(LEARN_PROJECT);
		boolean result = aclEvaluate.hasProjectReadPermission(project);
		Assert.assertFalse(result);
	}

	// No.1 hasProjectReadPermission test end

	// No.2 hasProjectOperationPermission test start
	/**
	 * no credentials operation any project failed
	 */
	@Test(expected = AuthenticationCredentialsNotFoundException.class)
	public void operationProjectAnyWithoutCredentials() {
		ProjectInstance project = getRandomProjectInstance();
		aclEvaluate.hasProjectOperationPermission(project);
	}

	/**
	 * admin operation all projects sueecss
	 */
	@Test
	@WithMockUser(username = ADMIN, roles = { ROLE_ADMIN })
	public void operationProjectAllAsRoleAdmin() {
		for (ProjectInstance project : uuid2Projects.values()) {
			boolean result = aclEvaluate.hasProjectOperationPermission(project);
			Assert.assertTrue(result);
		}
	}

	/**
	 * kylin operation all projects success
	 */
	@Test
	@WithMockUser(username = KYLIN, roles = { ROLE_USER })
	public void operationProjectAllWithAdminPermission() {
		for (ProjectInstance project : uuid2Projects.values()) {
			boolean result = aclEvaluate.hasProjectOperationPermission(project);
			Assert.assertTrue(result);
		}
	}

	/**
	 * zhangqiang operation test_project success
	 */
	@Test
	@WithMockUser(username = ZHANGQIANG, roles = { ROLE_USER })
	public void operationProjectTestWithAdminPermission() {
		ProjectInstance project = name2Projects.get(TEST_PROJECT);
		boolean result = aclEvaluate.hasProjectOperationPermission(project);
		Assert.assertTrue(result);
	}

	/**
	 * zhangqiang operation kylin_project success
	 */
	@Test
	@WithMockUser(username = ZHANGQIANG, roles = { ROLE_USER })
	public void operationProjectKylinWithOperationPermission() {
		ProjectInstance project = name2Projects.get(KYLIN_PROJECT);
		boolean result = aclEvaluate.hasProjectOperationPermission(project);
		Assert.assertTrue(result);
	}

	/**
	 * yuwen operation test_project success
	 */
	@Test
	@WithMockUser(username = YUWEN, roles = { ROLE_USER })
	public void operationProjectTestWithManagementPermission() {
		ProjectInstance project = name2Projects.get(TEST_PROJECT);
		boolean result = aclEvaluate.hasProjectOperationPermission(project);
		Assert.assertTrue(result);
	}

	/**
	 * yuwen operation kylin_project failed
	 */
	@Test
	@WithMockUser(username = YUWEN, roles = { ROLE_USER })
	public void operationProjectKylinWithoutPermission() {
		ProjectInstance project = name2Projects.get(KYLIN_PROJECT);
		boolean result = aclEvaluate.hasProjectOperationPermission(project);
		Assert.assertFalse(result);
	}

	/**
	 * yuwen operation learn_project failed
	 */
	@Test
	@WithMockUser(username = YUWEN, roles = { ROLE_USER })
	public void operationProjectLearnWithoutPermission() {
		ProjectInstance project = name2Projects.get(LEARN_PROJECT);
		boolean result = aclEvaluate.hasProjectOperationPermission(project);
		Assert.assertFalse(result);
	}

	// No.2 hasProjectOperationPermission test end

	// No.3 hasProjectWritePermission test start
	/**
	 * no credentials write any project failed
	 */
	@Test(expected = AuthenticationCredentialsNotFoundException.class)
	public void writeProjectAnyWithoutCredentials() {
		ProjectInstance project = getRandomProjectInstance();
		aclEvaluate.hasProjectWritePermission(project);
	}

	/**
	 * admin write all projects sueecss
	 */
	@Test
	@WithMockUser(username = ADMIN, roles = { ROLE_ADMIN })
	public void writeProjectAllAsRoleAdmin() {
		for (ProjectInstance project : uuid2Projects.values()) {
			boolean result = aclEvaluate.hasProjectWritePermission(project);
			Assert.assertTrue(result);
		}
	}

	/**
	 * kylin write all projects success
	 */
	@Test
	@WithMockUser(username = KYLIN, roles = { ROLE_USER })
	public void writeProjectAllWithAdminPermission() {
		for (ProjectInstance project : uuid2Projects.values()) {
			boolean result = aclEvaluate.hasProjectWritePermission(project);
			Assert.assertTrue(result);
		}
	}

	/**
	 * zhangqiang write test_project success
	 */
	@Test
	@WithMockUser(username = ZHANGQIANG, roles = { ROLE_USER })
	public void writeProjectTestWithAdminPermission() {
		ProjectInstance project = name2Projects.get(TEST_PROJECT);
		boolean result = aclEvaluate.hasProjectWritePermission(project);
		Assert.assertTrue(result);
	}

	/**
	 * zhangqiang write kylin_project failed
	 */
	@Test
	@WithMockUser(username = ZHANGQIANG, roles = { ROLE_USER })
	public void writeProjectKylinWithoutPermission() {
		ProjectInstance project = name2Projects.get(KYLIN_PROJECT);
		boolean result = aclEvaluate.hasProjectWritePermission(project);
		Assert.assertFalse(result);
	}

	/**
	 * yuwen write test_project success
	 */
	@Test
	@WithMockUser(username = YUWEN, roles = { ROLE_USER })
	public void writeProjectTestWithManagementPermission() {
		ProjectInstance project = name2Projects.get(TEST_PROJECT);
		boolean result = aclEvaluate.hasProjectWritePermission(project);
		Assert.assertTrue(result);
	}

	/**
	 * yuwen write kylin_project failed
	 */
	@Test
	@WithMockUser(username = YUWEN, roles = { ROLE_USER })
	public void writeProjectKylinWithoutPermission2() {
		ProjectInstance project = name2Projects.get(KYLIN_PROJECT);
		boolean result = aclEvaluate.hasProjectWritePermission(project);
		Assert.assertFalse(result);
	}

	/**
	 * yuwen write learn_project failed
	 */
	@Test
	@WithMockUser(username = YUWEN, roles = { ROLE_USER })
	public void writeProjectLearnWithoutPermission() {
		ProjectInstance project = name2Projects.get(LEARN_PROJECT);
		boolean result = aclEvaluate.hasProjectWritePermission(project);
		Assert.assertFalse(result);
	}

	// No.3 hasProjectWritePermission test end

	// No.4 hasProjectAdminPermission test start
	/**
	 * no credentials admin any project failed
	 */
	@Test(expected = AuthenticationCredentialsNotFoundException.class)
	public void adminProjectAnyWithoutCredentials() {
		ProjectInstance project = getRandomProjectInstance();
		aclEvaluate.hasProjectAdminPermission(project);
	}

	/**
	 * admin admin all projects sueecss
	 */
	@Test
	@WithMockUser(username = ADMIN, roles = { ROLE_ADMIN })
	public void adminProjectAllAsRoleAdmin() {
		for (ProjectInstance project : uuid2Projects.values()) {
			boolean result = aclEvaluate.hasProjectAdminPermission(project);
			Assert.assertTrue(result);
		}
	}

	/**
	 * kylin admin all projects success
	 */
	@Test
	@WithMockUser(username = KYLIN, roles = { ROLE_USER })
	public void adminProjectAllWithAdminPermission() {
		for (ProjectInstance project : uuid2Projects.values()) {
			boolean result = aclEvaluate.hasProjectAdminPermission(project);
			Assert.assertTrue(result);
		}
	}

	/**
	 * zhangqiang admin test_project success
	 */
	@Test
	@WithMockUser(username = ZHANGQIANG, roles = { ROLE_USER })
	public void adminProjectTestWithAdminPermission() {
		ProjectInstance project = name2Projects.get(TEST_PROJECT);
		boolean result = aclEvaluate.hasProjectAdminPermission(project);
		Assert.assertTrue(result);
	}

	/**
	 * zhangqiang admin kylin_project failed
	 */
	@Test
	@WithMockUser(username = ZHANGQIANG, roles = { ROLE_USER })
	public void adminProjectKylinWithoutPermission() {
		ProjectInstance project = name2Projects.get(KYLIN_PROJECT);
		boolean result = aclEvaluate.hasProjectAdminPermission(project);
		Assert.assertFalse(result);
	}

	/**
	 * yuwen admin test_project failed
	 */
	@Test
	@WithMockUser(username = YUWEN, roles = { ROLE_USER })
	public void adminProjectTestWithoutPermission() {
		ProjectInstance project = name2Projects.get(TEST_PROJECT);
		boolean result = aclEvaluate.hasProjectAdminPermission(project);
		Assert.assertFalse(result);
	}

	/**
	 * yuwen admin kylin_project failed
	 */
	@Test
	@WithMockUser(username = YUWEN, roles = { ROLE_USER })
	public void adminProjectKylinWithoutPermission2() {
		ProjectInstance project = name2Projects.get(KYLIN_PROJECT);
		boolean result = aclEvaluate.hasProjectAdminPermission(project);
		Assert.assertFalse(result);
	}

	/**
	 * yuwen admin learn_project failed
	 */
	@Test
	@WithMockUser(username = YUWEN, roles = { ROLE_USER })
	public void adminProjectLearnWithoutPermission() {
		ProjectInstance project = name2Projects.get(LEARN_PROJECT);
		boolean result = aclEvaluate.hasProjectAdminPermission(project);
		Assert.assertFalse(result);
	}
	// No.4 hasProjectAdminPermission test end
}