text:
import shuffle from './shuffle';
import {dragOver, dropPiece, pickImage} from './drag-and-drop';
import styles from '../styles/app.scss'

//DOM caching
const hexagons = Array.from(document.querySelectorAll('.c-puzzle__hexagon'));
const piecesContainer = document.querySelector('.c-pieces');
const pieces = Array.from(document.querySelectorAll('.c-pieces__piece'));
const start = document.getElementById('start');
const hint = document.getElementById('hint');
const reset = document.getElementById('reset');
const hardMode = document.getElementById('hard-mode');
const timer = document.getElementById('timer');
const solved = document.getElementById('solved');
const unsolved = document.getElementById('unsolved');
const startSound = document.getElementById('start-audio');
const failSound = document.getElementById('fail-audio');
const winSound = document.getElementById('win-audio');
const resetSound = document.getElementById('reset-audio');

let remainingTime = 300;
let timerIntervalID;
let remainingHints = 3;

const updateTimer = time => {
  time > 60 ? timer.classList.remove('alert') : timer.classList.add('alert');
  timer.innerHTML = `${~~(time / 60)}:${time % 60 < 10 ? '0' : ''}${time % 60}`;
};

const updateHints = times => hint.innerHTML = `Hint${times ? ` (${times})` : ''}`;

const resetGame = () => {
  unsolved.classList.remove('show');
  piecesContainer.classList.remove('show');
  hexagons.forEach(hexagon => hexagon.classList.remove('finished'));
  pieces.forEach(piece => piecesContainer.appendChild(piece));
  remainingTime = hardMode.checked ? 180 : 300;
  remainingHints = hardMode.checked ? 0 : 3;
  updateHints(remainingHints);
  start.disabled = false;
  hint.disabled = true;
  reset.disabled = true;
  hardMode.disabled = false;
  solved.classList.add('show');
  clearInterval(timerIntervalID);
  updateTimer(remainingTime);
};

const failed = () => {
  failSound.play();
  resetGame();
};

const resetButton = () => {
  resetSound.play();
  resetGame();
};

const win = () => {
  winSound.play();
  hexagons.forEach(hexagon => hexagon.classList.add('finished'));
  clearInterval(timerIntervalID);
};

const timerInterval = () => remainingTime > 0 ? updateTimer(--remainingTime) : failed();

const checkResolved = () => {
  const resolved = hexagons.every(hexagon => {
    return hexagon.firstElementChild && (hexagon.firstElementChild.getAttribute('data-piece') === hexagon.getAttribute('data-piece'))
  });
  if (resolved) {
    win();
  }
};

const dropAndCheck = (event) => {
  dropPiece(event);
  checkResolved();
};

const showHint = () => {
  solved.classList.add('show');
  updateHints(--remainingHints);
  window.addEventListener('mouseup', hideHint);
};

const hideHint = () => {
  solved.classList.remove('show');
  if(!remainingHints) {
    hint.disabled = true;
  }
  window.removeEventListener('mouseup', hideHint);
};

const startGame = (event) => {
  startSound.play();
  shuffle(piecesContainer);
  start.disabled = true;
  if (!hardMode.checked) {
    hint.disabled = false;
  }
  reset.disabled = false;
  hardMode.disabled = true;
  piecesContainer.classList.add('show');
  solved.classList.remove('show');
  unsolved.classList.add('show');
  timerIntervalID = setInterval(timerInterval, 1000);
};

const toggleHardMode = (event) => {
  remainingTime = event.target.checked ? 180 : 300;
  remainingHints = event.target.checked ? 0 : 3;
  updateTimer(remainingTime);
  updateHints(remainingHints);
};

hexagons.forEach((hexagon) => {
  hexagon.addEventListener('drop', dropAndCheck);
  hexagon.addEventListener('dragover', dragOver);
  hexagon.addEventListener('dragstart', pickImage);
});

piecesContainer.addEventListener('drop', dropPiece);
piecesContainer.addEventListener('dragover', dragOver);

pieces.forEach((piece) => piece.addEventListener('dragstart', pickImage));

start.addEventListener('click', startGame);
reset.addEventListener('click', resetButton);
hint.addEventListener('mousedown', showHint);
hardMode.addEventListener('change', toggleHardMode);

// https://webpack.github.io/docs/hot-module-replacement.html
if (module.hot) {
  module.hot.accept();
}


text:
<?php

/* IbwJobeetBundle:Affiliate:affiliate_new.html.twig */
class __TwigTemplate_f728bd4ece99a0b37edbb89a0e0fbd8038b44d7aae3519fd6176b2f4f5d14139 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = $this->env->loadTemplate("IbwJobeetBundle::layout.html.twig");

        $this->blocks = array(
            'form_errors' => array($this, 'block_form_errors'),
            'stylesheets' => array($this, 'block_stylesheets'),
            'content' => array($this, 'block_content'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "IbwJobeetBundle::layout.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        // line 3
        $context["form_themes"] = $this;
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 5
    public function block_form_errors($context, array $blocks = array())
    {
        // line 6
        ob_start();
        // line 7
        echo "    ";
        if ((twig_length_filter($this->env, (isset($context["errors"]) ? $context["errors"] : $this->getContext($context, "errors"))) > 0)) {
            // line 8
            echo "

            ";
            // line 9
            $context['_parent'] = (array) $context;
            $context['_seq'] = twig_ensure_traversable((isset($context["errors"]) ? $context["errors"] : $this->getContext($context, "errors")));
            foreach ($context['_seq'] as $context["_key"] => $context["error"]) {
                // line 10
                echo "
";
                echo twig_escape_filter($this->env, $this->env->getExtension('translator')->trans($this->getAttribute((isset($context["error"]) ? $context["error"] : $this->getContext($context, "error")), "messageTemplate"), $this->getAttribute((isset($context["error"]) ? $context["error"] : $this->getContext($context, "error")), "messageParameters"), "validators"), "html", null, true);
                echo "

            ";
            }
            $_parent = $context['_parent'];
            unset($context['_seq'], $context['_iterated'], $context['_key'], $context['error'], $context['_parent'], $context['loop']);
            $context = array_intersect_key($context, $_parent) + $_parent;
            // line 12
            echo "

    ";
        }
        echo trim(preg_replace('/>\s+</', '><', ob_get_clean()));
    }

    // line 17
    public function block_stylesheets($context, array $blocks = array())
    {
        // line 18
        echo "    ";
        $this->displayParentBlock("stylesheets", $context, $blocks);
        echo "
    <link rel=\"stylesheet\" href=\"";
        // line 19
        echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("bundles/ibwjobeet/css/job.css"), "html", null, true);
        echo "\" type=\"text/css\" media=\"all\" />
";
    }

    // line 22
    public function block_content($context, array $blocks = array())
    {
        // line 23
        echo "
";
        echo $this->env->getExtension('translator')->getTranslator()->trans("Become an affiliate", array(), "messages");
        echo "

        <form action=\"";
        // line 24
        echo $this->env->getExtension('routing')->getPath("ibw_affiliate_create");
        echo "\" method=\"post\" ";
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), 'enctype');
        echo ">

                            <input type=\"submit\" value=\"Submit\" />

                        ";
        // line 35
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "url"), 'label');
        echo "

                            ";
        // line 37
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "url"), 'errors');
        echo "
                            ";
        // line 38
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "url"), 'widget');
        echo "

                        ";
        // line 42
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "email"), 'label');
        echo "

                            ";
        // line 44
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "email"), 'errors');
        echo "
                            ";
        // line 45
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "email"), 'widget');
        echo "

                        ";
        // line 49
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "categories"), 'label');
        echo "

                            ";
        // line 51
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "categories"), 'errors');
        echo "
                            ";
        // line 52
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "categories"), 'widget');
        echo "

        ";
        // line 57
        echo         $this->env->getExtension('form')->renderer->renderBlock((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), 'form_end');
        echo "
";
    }

    public function getTemplateName()
    {
        return "IbwJobeetBundle:Affiliate:affiliate_new.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  150 => 57,  142 => 52,  138 => 51,  133 => 49,  126 => 45,  122 => 44,  117 => 42,  110 => 38,  106 => 37,  101 => 35,  85 => 24,  80 => 23,  77 => 22,  71 => 19,  66 => 18,  63 => 17,  56 => 12,  47 => 10,  43 => 9,  40 => 8,  37 => 7,  35 => 6,  32 => 5,  27 => 3,);
    }
}

redpajama_set_name: RedPajamaGithub


text:
module OAuth
  module Helper
    def generate_key(size=25)
      Base64.encode64(OpenSSL::Random.random_bytes(size)).gsub(/\W/, '')
    end
  end
end


text:
require 'puppet/ssl/certificate_authority'
require 'puppet/util/log/rate_limited_logger'

# Place for any authentication related bits
module Puppet::Network::Authentication
  # Create a rate-limited logger for the expiration warning that uses the run interval
  # as the minimum amount of time before a warning about the same cert can be logged again.
  # This is a class variable so that all classes that include the module share the same logger.
  @@logger = Puppet::Util::Log::RateLimitedLogger.new(Puppet[:runinterval])

  # Check the expiration of known certificates and optionally any that are specified as part of a request
  def warn_if_near_expiration(*certs)
    # Check CA cert if we're functioning as a CA
    certs << Puppet::SSL::CertificateAuthority.instance.host.certificate if Puppet::SSL::CertificateAuthority.ca?

    # Depending on the run mode, the localhost certificate will be for the
    # master or the agent. Don't load the certificate if the CA cert is not
    # present: infinite recursion will occur as another authenticated request
    # will be spawned to download the CA cert.
    if [Puppet[:hostcert], Puppet[:localcacert]].all? {|path| Puppet::FileSystem.exist?(path) }
      certs << Puppet::SSL::Host.localhost.certificate
    end

    # Remove nil values for caller convenience
    certs.compact.each do |cert|
      # Allow raw OpenSSL certificate instances or Puppet certificate wrappers to be specified
      cert = Puppet::SSL::Certificate.from_instance(cert) if cert.is_a?(OpenSSL::X509::Certificate)
      raise ArgumentError, "Invalid certificate '#{cert.inspect}'" unless cert.is_a?(Puppet::SSL::Certificate)

      if cert.near_expiration?
        @@logger.warning("Certificate '#{cert.unmunged_name}' will expire on #{cert.expiration.strftime('%Y-%m-%dT%H:%M:%S%Z')}")
      end
    end
  end
end


text:
package com.x22.bookcollection.ui;

import android.app.Activity;
import android.app.Fragment;
import android.app.LoaderManager;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.ColorMatrixColorFilter;
import android.os.Bundle;
import android.os.Environment;
import android.provider.BaseColumns;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;

import com.x22.bookcollection.R;
import com.x22.bookcollection.provider.BookContract;
import com.x22.bookcollection.util.LogUtils;

import java.io.File;

public class BooksFragment  extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
    private static final String TAG = LogUtils.makeLogTag(BooksFragment.class);

    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    private GridView booksGridView;

    private ListAdapter adapter;

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static BooksFragment newInstance() {
        BooksFragment fragment = new BooksFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    public BooksFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_books, container, false);
        booksGridView = (GridView) rootView.findViewById(R.id.books_grid_view);

        getLoaderManager().initLoader(BooksQuery.NORMAL_TOKEN, null, this);

        return rootView;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        ((MainActivity) activity).onSectionAttached("All books");
    }

    @Override
    public Loader<Cursor> onCreateLoader(int loaderId, Bundle bundle) {
        /*
     * Takes action based on the ID of the Loader that's being created
     */
        switch (loaderId) {
            case BooksQuery.NORMAL_TOKEN:
                // Returns a new CursorLoader
                return new CursorLoader(
                        getActivity(),   // Parent activity context
                        BookContract.Books.CONTENT_URI,        // Table to query
                        BooksQuery.NORMAL_PROJECTION,     // Projection to return
                        null,            // No selection clause
                        null,            // No selection arguments
                        null             // Default sort order
                );
            default:
                // An invalid id was passed in
                return null;
        }
    }

    @Override
    public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
        adapter = new BooksAdapter(getActivity(), cursor);
        booksGridView.setAdapter(adapter);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> cursorLoader) {

    }

    public class BooksAdapter extends CursorAdapter {
        private Cursor cursor;

        public BooksAdapter(Context context, Cursor cur) {
            super(context, cur, false);
            cursor = cur;
            // TODO Auto-generated constructor stub
        }

        public int scaleColor(int color, float factor, boolean scaleAlpha) {
            return Color.argb(scaleAlpha ? (Math.round(Color.alpha(color) * factor)) : Color.alpha(color),
                    Math.round(Color.red(color) * factor), Math.round(Color.green(color) * factor),
                    Math.round(Color.blue(color) * factor));
        }

        public int scaleSessionColorToDefaultBG(int color) {
            return scaleColor(color, 0.75f, false);
        }

        public ColorFilter makeSessionImageScrimColorFilter(int sessionColor) {
            float a = 0.25f;
            float sat = 0.25f; // saturation (0=gray, 1=color)
            return new ColorMatrixColorFilter(new float[]{
                    ((1 - 0.213f) * sat + 0.213f) * a, ((0 - 0.715f) * sat + 0.715f) * a, ((0 - 0.072f) * sat + 0.072f) * a, 0, Color.red(sessionColor) * (1 - a),
                    ((0 - 0.213f) * sat + 0.213f) * a, ((1 - 0.715f) * sat + 0.715f) * a, ((0 - 0.072f) * sat + 0.072f) * a, 0, Color.green(sessionColor) * (1 - a),
                    ((0 - 0.213f) * sat + 0.213f) * a, ((0 - 0.715f) * sat + 0.715f) * a, ((1 - 0.072f) * sat + 0.072f) * a, 0, Color.blue(sessionColor) * (1 - a),
                    0, 0, 0, 0, 255
            });
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            // TODO Auto-generated method stub

            final String bookId = cursor.getString(BooksQuery.BOOK_ID);
            if(bookId == null) {
                return;
            }

            Log.i(TAG, "cursor.getString(BooksQuery.TITLE): "+ cursor.getString(BooksQuery.TITLE));
            TextView titleView = (TextView) view.findViewById(R.id.book_title);
            titleView.setText(cursor.getString(BooksQuery.TITLE));

            ImageView photoView = (ImageView) view.findViewById(R.id.book_photo_colored);
            //photoView.setColorFilter(makeSessionImageScrimColorFilter(-16611119));
            //new PorterDuffColorFilter(getResources().getColor(R.color.no_track_branding_session_tile_overlay), PorterDuff.Mode.SRC_ATOP));

            File coverFile = new File(String.format("%s/bookcollection/%s.jpg", Environment.getExternalStorageDirectory(), cursor.getString(BooksQuery.UUID)));
            Log.i(TAG, "cursor.getString(BooksQuery.TITLE): " + cursor.getString(BooksQuery.UUID) + " - coverFile: " + coverFile.getAbsolutePath());
            if(coverFile.exists()){
                Bitmap myBitmap = BitmapFactory.decodeFile(coverFile.getAbsolutePath());
                photoView.setImageBitmap(myBitmap);
            } else {
                photoView.setVisibility(View.INVISIBLE);
                photoView.setMinimumHeight(0);
            }

            FrameLayout bookTargetView = (FrameLayout) view.findViewById(R.id.book_target);
            /*bookTargetView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mCallbacks.onSessionSelected(sessionId, finalPhotoView);
                }
            });*/
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            // TODO Auto-generated method stub
            LayoutInflater inflater = LayoutInflater.from(context);
            View view = inflater.inflate(R.layout.list_item_book_summarized, parent, false);
            bindView(view, context, cursor);
            return view;
        }

        public int getCount() {
            // TODO Auto-generated method stub
            //return cursor.getCount();
            return 5;
        }

        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        /* or used this getView()
		public View getView(final int position, View convertView,
				ViewGroup parent) {

			// TODO Auto-generated method stub
			CountryHolder holder = null;

			if (convertView == null) {

				LayoutInflater inflater = (LayoutInflater) context
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				convertView = inflater.inflate(R.layout.activity_column, null);

				holder = new CountryHolder();
				holder.ID = (TextView) convertView.findViewById(R.id.ColID);
				holder.Code = (TextView) convertView.findViewById(R.id.ColCode);
				holder.Country = (TextView) convertView
						.findViewById(R.id.ColCountry);

				convertView.setTag(holder);
			} else {
				holder = (CountryHolder) convertView.getTag();
			}

			cursor.moveToPosition(position);
			holder.ID.setText(cursor.getString(cursor.getColumnIndex("ID")));
			holder.Code.setText(cursor.getString(cursor.getColumnIndex("Code")));
			holder.Country.setText(cursor.getString(cursor.getColumnIndex("Country")));

			return convertView;

		}
		*/

    }

    public class CountryHolder {
        TextView ID;
        TextView Code;
        TextView Country;
    }

    private interface BooksQuery {
        int NORMAL_TOKEN = 0x1;

        String[] NORMAL_PROJECTION = {
                BaseColumns._ID,
                BookContract.Books.BOOK_ID,
                BookContract.Books.ISBN,
                BookContract.Books.TITLE,
                BookContract.Books.PLACES,
                BookContract.Books.CHARACTERS,
                BookContract.Books.PUBLISHER,
                BookContract.Books.PUBLICATION_DATE,
                BookContract.Books.PAGES,
                BookContract.Books.DESCRIPTION,
                BookContract.Books.BINDING,
                BookContract.Books.LANGUAGE,
                BookContract.Books.AVARAGE_RATING,
                BookContract.Books.RATING_COUNT,
                BookContract.Books.UUID,
        };

        int _ID = 0;
        int BOOK_ID = 1;
        int TITLE = 3;
        int UUID = 14;
        int PHOTO_URL = 3;
    }
}


text:
namespace boost::math::ccmath {

namespace detail {

template <typename Real>
inline constexpr Real sqrt_impl_2(Real x, Real s, Real s2)
{
    return !(s < s2) ? s2 : sqrt_impl_2(x, (x / s + s) / 2, s);
}

template <typename Real>
inline constexpr Real sqrt_impl_1(Real x, Real s)
{
    return sqrt_impl_2(x, (x / s + s) / 2, s);
}

template <typename Real>
inline constexpr Real sqrt_impl(Real x)
{
    return sqrt_impl_1(x, x > 1 ? x : Real(1));
}

} // namespace detail

template <typename Real, std::enable_if_t<!std::is_integral_v<Real>, bool> = true>
inline constexpr Real sqrt(Real x)
{
    if(BOOST_MATH_IS_CONSTANT_EVALUATED(x))
    {
        return boost::math::ccmath::isnan(x) ? std::numeric_limits<Real>::quiet_NaN() :
               boost::math::ccmath::isinf(x) ? std::numeric_limits<Real>::infinity() :
               detail::sqrt_impl<Real>(x);
    }
    else
    {
        using std::sqrt;
        return sqrt(x);
    }
}

template <typename Z, std::enable_if_t<std::is_integral_v<Z>, bool> = true>
inline constexpr double sqrt(Z x)
{
    return detail::sqrt_impl<double>(static_cast<double>(x));
}

} // Namespaces

#endif // BOOST_MATH_CCMATH_SQRT


text:
package org.multiverse.stms.gamma.transactionalobjects.txnlong;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.multiverse.api.LockMode;
import org.multiverse.api.TxnFactory;
import org.multiverse.api.exceptions.*;
import org.multiverse.api.exceptions.DeadTxnException;
import org.multiverse.api.exceptions.PreparedTxnException;
import org.multiverse.api.references.TxnLong;
import org.multiverse.stms.gamma.GammaConstants;
import org.multiverse.stms.gamma.GammaStm;
import org.multiverse.stms.gamma.transactionalobjects.GammaTxnLong;
import org.multiverse.stms.gamma.transactions.GammaTxn;
import org.multiverse.stms.gamma.transactions.GammaTxnFactory;
import org.multiverse.stms.gamma.transactions.fat.FatFixedLengthGammaTxnFactory;
import org.multiverse.stms.gamma.transactions.fat.FatMonoGammaTxnFactory;
import org.multiverse.stms.gamma.transactions.fat.FatVariableLengthGammaTxnFactory;

import java.util.Collection;

import static java.util.Arrays.asList;
import static org.junit.Assert.*;
import static org.multiverse.TestUtils.*;
import static org.multiverse.api.TxnThreadLocal.*;
import static org.multiverse.stms.gamma.GammaTestUtils.*;

@RunWith(Parameterized.class)
public class GammaTxnLong_getAndIncrement1Test implements GammaConstants {

    private final GammaTxnFactory transactionFactory;
    private final GammaStm stm;

    public GammaTxnLong_getAndIncrement1Test(GammaTxnFactory transactionFactory) {
        this.transactionFactory = transactionFactory;
        this.stm = transactionFactory.getConfig().getStm();
    }

    @Before
    public void setUp() {
        clearThreadLocalTxn();
    }

    @Parameterized.Parameters
    public static Collection<TxnFactory[]> configs() {
        return asList(
                new TxnFactory[]{new FatVariableLengthGammaTxnFactory(new GammaStm())},
                new TxnFactory[]{new FatFixedLengthGammaTxnFactory(new GammaStm())},
                new TxnFactory[]{new FatMonoGammaTxnFactory(new GammaStm())}
        );
    }

    @Test
    public void whenPreparedTransactionAvailable_thenPreparedTxnException() {
        GammaTxnLong ref = new GammaTxnLong(stm, 10);
        long version = ref.getVersion();

        GammaTxn tx = transactionFactory.newTxn();
        tx.prepare();
        setThreadLocalTxn(tx);

        try {
            ref.getAndIncrement(30);
            fail();
        } catch (PreparedTxnException expected) {

        }

        assertIsAborted(tx);
        assertVersionAndValue(ref, version, 10);
    }

    @Test
    public void whenActiveTransactionAvailable() {
        TxnLong ref = new GammaTxnLong(stm, 10);

        GammaTxn tx = transactionFactory.newTxn();
        setThreadLocalTxn(tx);
        long value = ref.getAndIncrement(20);
        tx.commit();

        assertEquals(10, value);
        assertIsCommitted(tx);
        assertEquals(30, ref.atomicGet());
        assertSame(tx, getThreadLocalTxn());
    }

    @Test
    public void whenNoChange() {
        GammaTxnLong ref = new GammaTxnLong(stm, 10);
        long version = ref.getVersion();

        GammaTxn tx = transactionFactory.newTxn();
        setThreadLocalTxn(tx);
        long value = ref.getAndIncrement(0);
        tx.commit();

        assertEquals(10, value);
        assertIsCommitted(tx);
        assertEquals(10, ref.atomicGet());
        assertSame(tx, getThreadLocalTxn());
        assertVersionAndValue(ref, version, 10);
    }

    @Test
    public void whenListenersAvailable() {
        long initialValue = 10;
        GammaTxnLong ref = new GammaTxnLong(stm, initialValue);
        long initialVersion = ref.getVersion();

        long amount = 2;
        TxnLongAwaitThread thread = new TxnLongAwaitThread(ref, initialValue + amount);
        thread.start();

        sleepMs(500);

        GammaTxn tx = transactionFactory.newTxn();
        setThreadLocalTxn(tx);
        long result = ref.getAndIncrement(amount);
        tx.commit();

        joinAll(thread);

        assertEquals(initialValue, result);
        assertRefHasNoLocks(ref);
        assertVersionAndValue(ref, initialVersion + 1, initialValue + amount);
    }

    @Test
    public void whenLocked_thenReadWriteConflict() {
        long initialValue = 10;
        GammaTxnLong ref = new GammaTxnLong(stm, initialValue);
        long version = ref.getVersion();

        GammaTxn otherTx = transactionFactory.newTxn();
        ref.getLock().acquire(otherTx, LockMode.Exclusive);

        GammaTxn tx = transactionFactory.newTxn();
        setThreadLocalTxn(tx);
        try {
            ref.getAndIncrement(1);
            fail();
        } catch (ReadWriteConflict expected) {
        }

        assertIsAborted(tx);
        assertVersionAndValue(ref, version, initialValue);
        assertSurplus(ref, 1);
        assertRefHasExclusiveLock(ref, otherTx);
    }

    @Test
    public void whenNoTransactionAvailable_thenNoTransactionFoundException() {
        long initialValue = 10;
        GammaTxnLong ref = new GammaTxnLong(stm, initialValue);
        long initialVersion = ref.getVersion();

        try {
            ref.getAndIncrement(1);
            fail();
        } catch (TxnMandatoryException expected) {

        }

        assertSurplus(ref, 0);
        assertRefHasNoLocks(ref);
        assertVersionAndValue(ref, initialVersion, initialValue);
        assertNull(getThreadLocalTxn());
    }

    @Test
    public void whenCommittedTransactionAvailable_thenDeadTxnException() {
        long initialValue = 10;
        GammaTxnLong ref = new GammaTxnLong(stm, initialValue);
        long initialVersion = ref.getVersion();

        GammaTxn tx = transactionFactory.newTxn();
        setThreadLocalTxn(tx);
        tx.commit();

        try {
            ref.getAndIncrement(2);
            fail();
        } catch (DeadTxnException expected) {

        }

        assertSurplus(ref, 0);
        assertRefHasNoLocks(ref);
        assertVersionAndValue(ref, initialVersion, initialValue);
        assertSame(tx, getThreadLocalTxn());
        assertIsCommitted(tx);
    }

    @Test
    public void whenAbortedTransactionAvailable_thenDeadTxnException() {
        long initialValue = 10;
        GammaTxnLong ref = new GammaTxnLong(stm, initialValue);
        long initialVersion = ref.getVersion();

        GammaTxn tx = transactionFactory.newTxn();
        setThreadLocalTxn(tx);
        tx.abort();

        try {
            ref.getAndIncrement(1);
            fail();
        } catch (DeadTxnException expected) {
        }

        assertSurplus(ref, 0);
        assertRefHasNoLocks(ref);
        assertVersionAndValue(ref, initialVersion, initialValue);
        assertSame(tx, getThreadLocalTxn());
        assertIsAborted(tx);
    }

}


text:
package netavark

import (
	"encoding/json"
	"net"
	"os"
	"path/filepath"
	"time"

	internalutil "github.com/containers/common/libnetwork/internal/util"
	"github.com/containers/common/libnetwork/types"
	"github.com/containers/common/pkg/util"
	"github.com/containers/storage/pkg/stringid"
	"github.com/pkg/errors"
)

// NetworkCreate will take a partial filled Network and fill the
// missing fields. It creates the Network and returns the full Network.
// nolint:gocritic
func (n *netavarkNetwork) NetworkCreate(net types.Network) (types.Network, error) {
	n.lock.Lock()
	defer n.lock.Unlock()
	err := n.loadNetworks()
	if err != nil {
		return types.Network{}, err
	}
	network, err := n.networkCreate(&net, false)
	if err != nil {
		return types.Network{}, err
	}
	// add the new network to the map
	n.networks[network.Name] = network
	return *network, nil
}

func (n *netavarkNetwork) networkCreate(newNetwork *types.Network, defaultNet bool) (*types.Network, error) {
	// if no driver is set use the default one
	if newNetwork.Driver == "" {
		newNetwork.Driver = types.DefaultNetworkDriver
	}
	if !defaultNet {
		// FIXME: Should we use a different type for network create without the ID field?
		// the caller is not allowed to set a specific ID
		if newNetwork.ID != "" {
			return nil, errors.Wrap(types.ErrInvalidArg, "ID can not be set for network create")
		}

		// generate random network ID
		var i int
		for i = 0; i < 1000; i++ {
			id := stringid.GenerateNonCryptoID()
			if _, err := n.getNetwork(id); err != nil {
				newNetwork.ID = id
				break
			}
		}
		if i == 1000 {
			return nil, errors.New("failed to create random network ID")
		}
	}

	err := internalutil.CommonNetworkCreate(n, newNetwork)
	if err != nil {
		return nil, err
	}

	// Only get the used networks for validation if we do not create the default network.
	// The default network should not be validated against used subnets, we have to ensure
	// that this network can always be created even when a subnet is already used on the host.
	// This could happen if you run a container on this net, then the cni interface will be
	// created on the host and "block" this subnet from being used again.
	// Therefore the next podman command tries to create the default net again and it would
	// fail because it thinks the network is used on the host.
	var usedNetworks []*net.IPNet
	if !defaultNet && newNetwork.Driver == types.BridgeNetworkDriver {
		usedNetworks, err = internalutil.GetUsedSubnets(n)
		if err != nil {
			return nil, err
		}
	}

	switch newNetwork.Driver {
	case types.BridgeNetworkDriver:
		err = internalutil.CreateBridge(n, newNetwork, usedNetworks)
		if err != nil {
			return nil, err
		}
		// validate the given options, we do not need them but just check to make sure they are valid
		for key, value := range newNetwork.Options {
			switch key {
			case "mtu":
				_, err = internalutil.ParseMTU(value)
				if err != nil {
					return nil, err
				}

			case "vlan":
				_, err = internalutil.ParseVlan(value)
				if err != nil {
					return nil, err
				}

			default:
				return nil, errors.Errorf("unsupported bridge network option %s", key)
			}
		}
	case types.MacVLANNetworkDriver:
		err = createMacvlan(newNetwork)
		if err != nil {
			return nil, err
		}
	default:
		return nil, errors.Wrapf(types.ErrInvalidArg, "unsupported driver %s", newNetwork.Driver)
	}

	// add gatway when not internal or dns enabled
	addGateway := !newNetwork.Internal || newNetwork.DNSEnabled
	err = internalutil.ValidateSubnets(newNetwork, addGateway, usedNetworks)
	if err != nil {
		return nil, err
	}

	newNetwork.Created = time.Now()

	if !defaultNet {
		confPath := filepath.Join(n.networkConfigDir, newNetwork.Name+".json")
		f, err := os.Create(confPath)
		if err != nil {
			return nil, err
		}
		enc := json.NewEncoder(f)
		enc.SetIndent("", "     ")
		err = enc.Encode(newNetwork)
		if err != nil {
			return nil, err
		}
	}

	return newNetwork, nil
}

func createMacvlan(network *types.Network) error {
	if network.Internal {
		return errors.New("internal is not supported with macvlan")
	}
	if network.NetworkInterface != "" {
		interfaceNames, err := internalutil.GetLiveNetworkNames()
		if err != nil {
			return err
		}
		if !util.StringInSlice(network.NetworkInterface, interfaceNames) {
			return errors.Errorf("parent interface %s does not exist", network.NetworkInterface)
		}
	}
	if len(network.Subnets) == 0 {
		return errors.Errorf("macvlan driver needs at least one subnet specified, DHCP is not supported with netavark")
	}
	network.IPAMOptions["driver"] = types.HostLocalIPAMDriver

	// validate the given options, we do not need them but just check to make sure they are valid
	for key, value := range network.Options {
		switch key {
		case "mode":
			if !util.StringInSlice(value, types.ValidMacVLANModes) {
				return errors.Errorf("unknown macvlan mode %q", value)
			}
		case "mtu":
			_, err := internalutil.ParseMTU(value)
			if err != nil {
				return err
			}
		default:
			return errors.Errorf("unsupported macvlan network option %s", key)
		}
	}
	return nil
}

// NetworkRemove will remove the Network with the given name or ID.
// It does not ensure that the network is unused.
func (n *netavarkNetwork) NetworkRemove(nameOrID string) error {
	n.lock.Lock()
	defer n.lock.Unlock()
	err := n.loadNetworks()
	if err != nil {
		return err
	}

	network, err := n.getNetwork(nameOrID)
	if err != nil {
		return err
	}

	// Removing the default network is not allowed.
	if network.Name == n.defaultNetwork {
		return errors.Errorf("default network %s cannot be removed", n.defaultNetwork)
	}

	file := filepath.Join(n.networkConfigDir, network.Name+".json")
	// make sure to not error for ErrNotExist
	if err := os.Remove(file); err != nil && !errors.Is(err, os.ErrNotExist) {
		return err
	}
	delete(n.networks, network.Name)
	return nil
}

// NetworkList will return all known Networks. Optionally you can
// supply a list of filter functions. Only if a network matches all
// functions it is returned.
func (n *netavarkNetwork) NetworkList(filters ...types.FilterFunc) ([]types.Network, error) {
	n.lock.Lock()
	defer n.lock.Unlock()
	err := n.loadNetworks()
	if err != nil {
		return nil, err
	}

	networks := make([]types.Network, 0, len(n.networks))
outer:
	for _, net := range n.networks {
		for _, filter := range filters {
			// All filters have to match, if one does not match we can skip to the next network.
			if !filter(*net) {
				continue outer
			}
		}
		networks = append(networks, *net)
	}
	return networks, nil
}

// NetworkInspect will return the Network with the given name or ID.
func (n *netavarkNetwork) NetworkInspect(nameOrID string) (types.Network, error) {
	n.lock.Lock()
	defer n.lock.Unlock()
	err := n.loadNetworks()
	if err != nil {
		return types.Network{}, err
	}

	network, err := n.getNetwork(nameOrID)
	if err != nil {
		return types.Network{}, err
	}
	return *network, nil
}


text:
import 'bootstrap';
import 'fetch';
//import {AuthConfig} from './services/authConfig';
import {Aurelia} from 'aurelia-framework';

/** Basic authN configuration, from http://aurelia-authentication.spoonx.org/baseConfig.html */
var baseConfig = {
    // If using aurelia-api:
    // =====================

    // This is the name of the endpoint used for any requests made in relation to authentication (login, logout, etc.). An empty string selects the default endpoint of aurelia-api.
    endpoint: 'api',
    // When authenticated, these endpoints will have the token added to the header of any requests (for authorization). Accepts an array of endpoint names. An empty string selects the default endpoint of aurelia-api.
    configureEndpoints: ["api"],

    // SPA related options
    // ===================

    // The SPA url to which the user is redirected after a successful login
    loginRedirect: '/projects',
    // The SPA url to which the user is redirected after a successful logout
    logoutRedirect: '/',
    // The SPA route used when an unauthenticated user tries to access an SPA page that requires authentication
    loginRoute: '/login',
    // Whether or not an authentication token is provided in the response to a successful signup
    loginOnSignup: true,
    // If loginOnSignup == false: The SPA url to which the user is redirected after a successful signup (else loginRedirect is used)
    signupRedirect: '/login',

    // API related options
    // ===================

    // The base url used for all authentication related requests, including provider.url below.
    // This appends to the httpClient/endpoint base url, it does not override it.
    baseUrl: '/auth',
    // The API endpoint to which login requests are sent
    loginUrl: '/login',
    // The API endpoint to which signup requests are sent
    signupUrl: '/signup',
    // The API endpoint used in profile requests (inc. `find/get` and `update`)
    profileUrl: '/me',
    // The API endpoint used with oAuth to unlink authentication
    unlinkUrl: '/unlink/',
    // The HTTP method used for 'unlink' requests (Options: 'get' or 'post')
    unlinkMethod: 'get',

    // Token Options
    // =============

    // The header property used to contain the authToken in the header of API requests that require authentication
    authHeader: 'Authorization',
    // The token name used in the header of API requests that require authentication
    authToken: 'Bearer',
    // The property from which to get the access token after a successful login or signup
    accessTokenProp: 'access_token',

    // If the property defined by `accessTokenProp` is an object:
    // ------------------------------------------------------------

    //This is the property from which to get the token `{ "accessTokenProp": { "accessTokenName" : '...' } }`
    accessTokenName: 'token',
    // This allows the token to be a further object deeper `{ "accessTokenProp": { "accessTokenRoot" : { "accessTokenName" : '...' } } }`
    accessTokenRoot: false,

    // Refresh Token Options
    // =====================

    // Option to turn refresh tokens On/Off
    useRefreshToken: true,
    // The option to enable/disable the automatic refresh of Auth tokens using Refresh Tokens
    autoUpdateToken: true,
    // Oauth Client Id
    clientId: false,
    // The the property from which to get the refresh token after a successful token refresh
    refreshTokenProp: 'refresh_token',

    // If the property defined by `refreshTokenProp` is an object:
    // -----------------------------------------------------------

    // This is the property from which to get the token `{ "refreshTokenProp": { "refreshTokenName" : '...' } }`
    refreshTokenName: 'token',
    // This allows the refresh token to be a further object deeper `{ "refreshTokenProp": { "refreshTokenRoot" : { "refreshTokenName" : '...' } } }`
    refreshTokenRoot: false,

    // Miscellaneous Options
    // =====================

    // Whether to enable the fetch interceptor which automatically adds the authentication headers
    // (or not... e.g. if using a session based API or you want to override the default behaviour)
    httpInterceptor: true,
    // For OAuth only: Tell the API whether or not to include token cookies in the response (for session based APIs)
    withCredentials: true,
    // Controls how the popup is shown for different devices (Options: 'browser' or 'mobile')
    platform: 'browser',
    // Determines the `window` property name upon which aurelia-authentication data is stored (Default: `window.localStorage`)
    storage: 'localStorage',
    // The key used for storing the authentication response locally
    storageKey: 'aurelia_authentication'
};

var configForDevelopment = {
    // OAuth provider specific related configuration
    // ============================================
    providers: {
        google: {
            name: 'google',
            url: '#/',
            authorizationEndpoint: 'https://accounts.google.com/o/oauth2/auth',
            redirectUri: window.location.origin || window.location.protocol + '//' + window.location.host,
            // redirectUri: 'http://62.251.42.70:9000',
            scope: ['profile', 'email'],
            scopePrefix: 'openid',
            scopeDelimiter: ' ',
            requiredUrlParams: ['scope'],
            optionalUrlParams: ['display'],
            display: 'popup',
            type: '2.0',
            clientId: '936472878571-3gqkvd6ontmr6gn24u6q3dka4f17qm5o.apps.googleusercontent.com',
            clientSecret: 'V55QHX7lPS_t0PiVLgPz8eCm',
            popupOptions: { width: 452, height: 633 }
        },
        facebook: {
            name: 'facebook',
            url: '/auth/facebook',
            authorizationEndpoint: 'https://www.facebook.com/v2.3/dialog/oauth',
            redirectUri: window.location.origin + '/' || window.location.protocol + '//' + window.location.host + '/',
            scope: ['email'],
            scopeDelimiter: ',',
            nonce: function () {
                return Math.random();
            },
            requiredUrlParams: ['nonce', 'display', 'scope'],
            display: 'popup',
            type: '2.0',
            popupOptions: { width: 580, height: 400 }
        },
        linkedin: {
            name: 'linkedin',
            url: '/auth/linkedin',
            authorizationEndpoint: 'https://www.linkedin.com/uas/oauth2/authorization',
            redirectUri: window.location.origin || window.location.protocol + '//' + window.location.host,
            requiredUrlParams: ['state'],
            scope: ['r_emailaddress'],
            scopeDelimiter: ' ',
            state: 'STATE',
            type: '2.0',
            popupOptions: { width: 527, height: 582 }
        },
        github: {
            name: 'github',
            url: '/auth/github',
            authorizationEndpoint: 'https://github.com/login/oauth/authorize',
            redirectUri: window.location.origin || window.location.protocol + '//' + window.location.host,
            optionalUrlParams: ['scope'],
            scope: ['user:email'],
            scopeDelimiter: ' ',
            type: '2.0',
            popupOptions: { width: 1020, height: 618 }
        },
        yahoo: {
            name: 'yahoo',
            url: '/auth/yahoo',
            authorizationEndpoint: 'https://api.login.yahoo.com/oauth2/request_auth',
            redirectUri: window.location.origin || window.location.protocol + '//' + window.location.host,
            scope: [],
            scopeDelimiter: ',',
            type: '2.0',
            popupOptions: { width: 559, height: 519 }
        },
        twitter: {
            name: 'twitter',
            url: '/auth/twitter',
            authorizationEndpoint: 'https://api.twitter.com/oauth/authenticate',
            type: '1.0',
            popupOptions: { width: 495, height: 645 }
        },
        live: {
            name: 'live',
            url: '/auth/live',
            authorizationEndpoint: 'https://login.live.com/oauth20_authorize.srf',
            redirectUri: window.location.origin || window.location.protocol + '//' + window.location.host,
            scope: ['wl.emails'],
            scopeDelimiter: ' ',
            requiredUrlParams: ['display', 'scope'],
            display: 'popup',
            type: '2.0',
            popupOptions: { width: 500, height: 560 }
        },
        instagram: {
            name: 'instagram',
            url: '/auth/instagram',
            authorizationEndpoint: 'https://api.instagram.com/oauth/authorize',
            redirectUri: window.location.origin || window.location.protocol + '//' + window.location.host,
            requiredUrlParams: ['scope'],
            scope: ['basic'],
            scopeDelimiter: '+',
            display: 'popup',
            type: '2.0',
            popupOptions: { width: 550, height: 369 }
        }
    }
};

var configForProduction = {
    // OAuth provider specific related configuration
    // ============================================
    providers: {
        google: {
            name: 'google',
            url: '/auth/google',
            authorizationEndpoint: 'https://accounts.google.com/o/oauth2/auth',
            redirectUri: window.location.origin || window.location.protocol + '//' + window.location.host,
            scope: ['profile', 'email'],
            scopePrefix: 'openid',
            scopeDelimiter: ' ',
            requiredUrlParams: ['scope'],
            optionalUrlParams: ['display'],
            display: 'popup',
            type: '2.0',
            clientId: '593653893869-u6frt6h714iipqupecrds34bo11js3n8.apps.googleusercontent.com',
            popupOptions: { width: 452, height: 633 }
        },
        facebook: {
            name: 'facebook',
            url: '/auth/facebook',
            authorizationEndpoint: 'https://www.facebook.com/v2.3/dialog/oauth',
            redirectUri: window.location.origin + '/' || window.location.protocol + '//' + window.location.host + '/',
            scope: ['email'],
            scopeDelimiter: ',',
            nonce: function () {
                return Math.random();
            },
            requiredUrlParams: ['nonce', 'display', 'scope'],
            display: 'popup',
            type: '2.0',
            popupOptions: { width: 580, height: 400 }
        },
        linkedin: {
            name: 'linkedin',
            url: '/auth/linkedin',
            authorizationEndpoint: 'https://www.linkedin.com/uas/oauth2/authorization',
            redirectUri: window.location.origin || window.location.protocol + '//' + window.location.host,
            requiredUrlParams: ['state'],
            scope: ['r_emailaddress'],
            scopeDelimiter: ' ',
            state: 'STATE',
            type: '2.0',
            popupOptions: { width: 527, height: 582 }
        },
        github: {
            name: 'github',
            url: '/auth/github',
            authorizationEndpoint: 'https://github.com/login/oauth/authorize',
            redirectUri: window.location.origin || window.location.protocol + '//' + window.location.host,
            optionalUrlParams: ['scope'],
            scope: ['user:email'],
            scopeDelimiter: ' ',
            type: '2.0',
            popupOptions: { width: 1020, height: 618 }
        },
        yahoo: {
            name: 'yahoo',
            url: '/auth/yahoo',
            authorizationEndpoint: 'https://api.login.yahoo.com/oauth2/request_auth',
            redirectUri: window.location.origin || window.location.protocol + '//' + window.location.host,
            scope: [],
            scopeDelimiter: ',',
            type: '2.0',
            popupOptions: { width: 559, height: 519 }
        },
        twitter: {
            name: 'twitter',
            url: '/auth/twitter',
            authorizationEndpoint: 'https://api.twitter.com/oauth/authenticate',
            type: '1.0',
            popupOptions: { width: 495, height: 645 }
        },
        live: {
            name: 'live',
            url: '/auth/live',
            authorizationEndpoint: 'https://login.live.com/oauth20_authorize.srf',
            redirectUri: window.location.origin || window.location.protocol + '//' + window.location.host,
            scope: ['wl.emails'],
            scopeDelimiter: ' ',
            requiredUrlParams: ['display', 'scope'],
            display: 'popup',
            type: '2.0',
            popupOptions: { width: 500, height: 560 }
        },
        instagram: {
            name: 'instagram',
            url: '/auth/instagram',
            authorizationEndpoint: 'https://api.instagram.com/oauth/authorize',
            redirectUri: window.location.origin || window.location.protocol + '//' + window.location.host,
            requiredUrlParams: ['scope'],
            scope: ['basic'],
            scopeDelimiter: '+',
            display: 'popup',
            type: '2.0',
            popupOptions: { width: 550, height: 369 }
        }
    }
};

var authConfig;
if (window.location.hostname === 'localhost') {
    authConfig = Object.assign({}, baseConfig, configForDevelopment);
}
else {
    authConfig = Object.assign({}, baseConfig, configForProduction);
}

//export default config;

export function configure(aurelia: Aurelia) {
  aurelia.use
    .standardConfiguration()
    .plugin('aurelia-dialog')
    .developmentLogging();

  aurelia.use
    .plugin('aurelia-api', config => {
      config
        .registerEndpoint('api', 'http://cs.tno.nl/db/')
        // .registerEndpoint('api', 'http://localhost:3000')
        .setDefaultEndpoint('api');
    })
    //Uncomment the line below to enable animation.
    //.plugin('aurelia-animator-css')
    .plugin('aurelia-authentication', baseConfig => {
        baseConfig.configure(authConfig);
    });

  //Anyone wanting to use HTMLImports to load views, will need to install the following plugin.
  //aurelia.use.plugin('aurelia-html-import-template-loader')

  aurelia.start().then(() => aurelia.setRoot());
}


text:
(function () {
  'use strict';

  /**
   * @ngdoc overview
   * @name horizon.framework.util.filters
   * @description
   * horizon.framework.util.filters provides common filters to be used within Horizon.
   *
   */
  angular
    .module('horizon.framework.util.filters', ['horizon.framework.util.i18n']);
})();


text:
package com.thebluealliance.androidclient.background;

import android.os.AsyncTask;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import com.thebluealliance.androidclient.Constants;
import com.thebluealliance.androidclient.R;
import com.thebluealliance.androidclient.activities.RefreshableHostActivity;
import com.thebluealliance.androidclient.adapters.ListViewAdapter;
import com.thebluealliance.androidclient.datafeed.APIResponse;
import com.thebluealliance.androidclient.datafeed.DataManager;
import com.thebluealliance.androidclient.datafeed.RequestParams;
import com.thebluealliance.androidclient.helpers.AnalyticsHelper;
import com.thebluealliance.androidclient.helpers.EventHelper;
import com.thebluealliance.androidclient.interfaces.RefreshListener;
import com.thebluealliance.androidclient.interfaces.RefreshableHost;
import com.thebluealliance.androidclient.listitems.ListItem;
import com.thebluealliance.androidclient.models.Event;

import java.util.ArrayList;

/**
 * File created by phil on 4/20/14.
 */
public class PopulateEventList extends AsyncTask<Void, Void, APIResponse.CODE> {

    private Fragment mFragment;
    private int mYear = -1, mWeek = -1;
    private String mTeamKey = null, mHeader, mDistrictKey;
    private ArrayList<ListItem> events;
    private RefreshableHostActivity activity;
    private RefreshableHost host;
    private RequestParams requestParams;
    private long startTime;

    private PopulateEventList(Fragment fragment, RequestParams requestParams) {
        mFragment = fragment;
        this.requestParams = requestParams;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        startTime = System.currentTimeMillis();
    }

    public PopulateEventList(Fragment fragment, String districtKey, RequestParams requestParams) {
        this(fragment, requestParams);
        activity = (RefreshableHostActivity) mFragment.getActivity();
        this.host = activity;

        mTeamKey = mHeader = null;
        mYear = -1;
        mDistrictKey = districtKey;
    }

    public PopulateEventList(Fragment fragment, int year, String weekHeader, String teamKey, RequestParams requestParams) {
        this(fragment, requestParams);
        mYear = year;
        mTeamKey = teamKey;
        mHeader = weekHeader;
        activity = (RefreshableHostActivity) mFragment.getActivity();
        this.host = activity;
        mDistrictKey = null;
    }

    public PopulateEventList(Fragment fragment, RefreshableHost host, int year, String weekHeader, String teamKey, RequestParams requestParams) {
        this(fragment, requestParams);
        mYear = year;
        mTeamKey = teamKey;
        mHeader = weekHeader;
        this.host = host;
        activity = (RefreshableHostActivity) mFragment.getActivity();
        mDistrictKey = null;
    }

    private PopulateEventList(Fragment fragment, RefreshableHost host, int year, String weekHeader, String teamKey, String districtKey, RequestParams requestParams) {
        this(fragment, requestParams);
        mYear = year;
        mTeamKey = teamKey;
        mHeader = weekHeader;
        this.host = host;
        activity = (RefreshableHostActivity) mFragment.getActivity();
        mDistrictKey = districtKey;
    }

    @Override
    protected APIResponse.CODE doInBackground(Void... params) {
        if (mFragment == null) {
            throw new IllegalArgumentException("Fragment must not be null!");
        }

        //first, let's generate the event week based on its header (event weeks aren't constant over the years)
        if (mHeader == null || mHeader.equals("")) {
            mWeek = -1;
        } else {
            mWeek = EventHelper.weekNumFromLabel(mYear, mHeader);
        }

        events = new ArrayList<>();

        APIResponse<ArrayList<Event>> response;

        if (mYear != -1 && mWeek == -1 && mTeamKey == null) {
            // Return a list of all events for a year
        } else if (mYear == -1 && mDistrictKey != null) {
            // return a list of all events in a given district in a year
            try {
                response = DataManager.Events.getEventsInDistrict(mFragment.getActivity(), mDistrictKey, requestParams);

                if (isCancelled()) {
                    return APIResponse.CODE.NODATA;
                }

                ArrayList<Event> eventData = response.getData();
                if (eventData != null && !eventData.isEmpty()) {
                    events = EventHelper.renderEventListForDistrict(mFragment.getActivity(), eventData, false); // To enable a local broadcast for a live district event, make the last arg true
                }
                return response.getCode();

            } catch (DataManager.NoDataException e) {
                Log.w(Constants.LOG_TAG, "Unable to find events in district " + mDistrictKey);
                e.printStackTrace();
            }

        } else if (mYear != -1 && mWeek != -1 && mTeamKey == null) {
            // Return a list of all events for a week in a given year
            try {
                response = DataManager.Events.getSimpleEventsInWeek(activity, mYear, mWeek, requestParams);

                if (isCancelled()) {
                    return APIResponse.CODE.NODATA;
                }

                ArrayList<Event> eventData = response.getData();
                if (eventData != null && !eventData.isEmpty()) {
                    events = EventHelper.renderEventListForWeek(eventData);
                }
                return response.getCode();
            } catch (Exception e) {
                Log.w(Constants.LOG_TAG, "unable to find events for week " + mWeek + " " + mYear);
                e.printStackTrace();
            }
        } else if (mYear != -1 && mWeek == -1 && mTeamKey != null) {
            // Return a list of all events for a team for a given year
            Log.d(Constants.LOG_TAG, "Loading events for team " + mTeamKey + " in " + mYear);
            try {
                response = DataManager.Teams.getEventsForTeam(activity, mTeamKey, mYear, requestParams);
                ArrayList<Event> eventsArray = response.getData();
                if (eventsArray != null && !eventsArray.isEmpty()) {
                    events = EventHelper.renderEventListForTeam(activity, eventsArray, true);
                }
                return response.getCode();
            } catch (Exception e) {
                Log.w(Constants.LOG_TAG, "unable to load event list");
                e.printStackTrace();
            }
        } else if (mYear != -1 && mWeek != -1 && mTeamKey != null) {
            // Return a list of all events for a given team in a given week in a given year
        }

        return APIResponse.CODE.NODATA;
    }

    @Override
    protected void onPostExecute(APIResponse.CODE code) {
        super.onPostExecute(code);

        //android gets angry if you modify Views off the UI thread, so we do the actual View manipulation here
        View view = mFragment.getView();
        if (view != null && activity != null) {
            ListViewAdapter adapter = new ListViewAdapter(activity, events);
            ListView eventList = (ListView) view.findViewById(R.id.list);
            TextView noDataText = (TextView) view.findViewById(R.id.no_data);

            // If there's no data in the adapter or if we can't download info
            // off the web, display a message.
            if (code == APIResponse.CODE.NODATA || (!requestParams.forceFromCache && adapter.values.isEmpty())) {
                noDataText.setText(R.string.no_event_data);
                noDataText.setVisibility(View.VISIBLE);
                eventList.setVisibility(View.GONE);
            } else {
                Parcelable state = eventList.onSaveInstanceState();
                eventList.setAdapter(adapter);
                eventList.setVisibility(View.VISIBLE);
                noDataText.setVisibility(View.GONE);
                eventList.onRestoreInstanceState(state);
            }

            if (code == APIResponse.CODE.OFFLINECACHE) {
                activity.showWarningMessage(mFragment.getString(R.string.warning_using_cached_data));
            }

            if (mHeader != null && !mHeader.equals("") || mTeamKey != null || mDistrictKey != null) {
                view.findViewById(R.id.progress).setVisibility(View.GONE);
            }

            if (code == APIResponse.CODE.LOCAL && !isCancelled()) {
                /**
                 * The data has the possibility of being updated, but we at first loaded
                 * what we have cached locally for performance reasons.
                 * Thus, fire off this task again with a flag saying to actually load from the web
                 */
                requestParams.forceFromCache = false;
                new PopulateEventList(mFragment, host, mYear, mHeader, mTeamKey, mDistrictKey, requestParams).execute();
            } else if (host != null) {
                // Show notification if we've refreshed data.
                Log.d(Constants.REFRESH_LOG, "Event List Refresh complete");
                host.notifyRefreshComplete((RefreshListener) mFragment);
            }

            AnalyticsHelper.sendTimingUpdate(activity, System.currentTimeMillis() - startTime, "event list", requestParams.toString());
        }
    }
}


text:
require 'pacto'
require 'thor'
require 'pacto/cli'
require 'pacto/cli/helpers'

# FIXME: RakeTask is a huge class, refactor this please
# rubocop:disable ClassLength
module Pacto
  class RakeTask
    extend Forwardable
    include Thor::Actions
    include Rake::DSL
    include Pacto::CLI::Helpers

    def initialize
      @exit_with_error = false
      @cli = Pacto::CLI::Main.new
    end

    def run(task, args, opts = {})
      Pacto::CLI::Main.new([], opts).public_send(task, *args)
    end

    def install
      desc 'Tasks for Pacto gem'
      namespace :pacto do
        validate_task
        generate_task
        meta_validate
      end
    end

    def validate_task
      desc 'Validates all contracts in a given directory against a given host'
      task :validate, :host, :dir do |_t, args|
        opts = args.to_hash
        dir = opts.delete :dir
        run(:validate, dir, opts)
      end
    end

    def generate_task
      desc 'Generates contracts from partial contracts'
      task :generate, :input_dir, :output_dir, :host do |_t, args|
        if args.to_a.size < 3
          fail Pacto::UI.colorize('USAGE: rake pacto:generate[<request_contract_dir>, <output_dir>, <record_host>]', :yellow)
        end

        generate_contracts(args[:input_dir], args[:output_dir], args[:host])
      end
    end

    def meta_validate
      desc 'Validates a directory of contract definitions'
      task :meta_validate, :dir do |_t, args|
        run(:meta_validate, *args)
      end
    end

    # rubocop:enable MethodLength

    # FIXME: generate_contracts is a big method =(. Needs refactoring
    # rubocop:disable MethodLength
    def generate_contracts(input_dir, output_dir, host)
      WebMock.allow_net_connect!
      generator = Pacto::Generator.contract_generator
      puts "Generating contracts from partial contracts in #{input_dir} and recording to #{output_dir}\n\n"

      failed_contracts = []
      each_contract(input_dir) do |contract_file|
        begin
          contract = generator.generate_from_partial_contract(contract_file, host)
          output_file = File.expand_path(File.basename(contract_file), output_dir)
          output_file = File.open(output_file, 'wb')
          output_file.write contract
          output_file.flush
          output_file.close
        rescue InvalidContract => e
          failed_contracts << contract_file
          puts Pacto::UI.colorize(e.message, :red)
        end
      end

      if failed_contracts.empty?
        puts Pacto::UI.colorize('Successfully generated all contracts', :green)
      else
        fail Pacto::UI.colorize("The following contracts could not be generated: #{failed_contracts.join ','}", :red)
      end
    end
    # rubocop:enable MethodLength
  end
end
# rubocop:enable ClassLength

Pacto::RakeTask.new.install


text:
package org.precompiler.scala101.ch09

/**
  *
  * @author Richard Li
  */
object MatchingLiteralsAndConstants extends App {
  def translate(weekday: String) = {

    weekday match {
      case "Sunday" => println("周日")
      case "Saturday" => println("周六")
      case "Monday" => println("周一")
      case unknown => println(s"unknown: ${unknown}")
    }
  }

  List("Sunday", "Saturday", "Monday", "Wednesday").foreach(translate)

  def translate(weekday: DayofWeek.Value) = {
    weekday match {
      case DayofWeek.MONDAY => println("周一")
      case DayofWeek.TUESDAY => println("周二")
      case DayofWeek.WEDNESDAY => println("周三")
      case _ => println("Unknown")
    }
  }

  translate(DayofWeek.MONDAY)
  translate(DayofWeek.FRIDAY)

}

object DayofWeek extends Enumeration {
  val MONDAY = Value("Monday")
  val TUESDAY = Value("Tuesday")
  val WEDNESDAY = Value("Wednesday")
  val FRIDAY = Value("Friday")
}


text:
module Related
  module Follower
    def follow!(other)
      Related::Relationship.create(:follow, self, other)
    end

    def unfollow!(other)
      rel = self.following.relationships.find(other)
      rel.destroy if rel
    end

    def followers
      self.incoming(:follow)
    end

    def following
      self.outgoing(:follow)
    end

    def friends
      self.followers.intersect(self.following)
    end

    def followed_by?(other)
      self.followers.include?(other)
    end

    def following?(other)
      self.following.include?(other)
    end

    def followers_count
      self.followers.size
    end

    def following_count
      self.following.size
    end
  end
end


text:
package relay

import (
	"net"

	pb "gx/ipfs/QmZBfqr863PYD7BKbmCFSNmzsqYmtr2DKgzubsQaiTQkMc/go-libp2p-circuit/pb"

	ma "gx/ipfs/QmTZBfrPJmjWsCvHEtX5FE6KimVJhsJg5sBbqEFYf4UZtL/go-multiaddr"
	manet "gx/ipfs/Qmc85NSvmSG4Frn9Vb2cBc1rMyULH6D3TNVEfCzSKoUpip/go-multiaddr-net"
)

var _ manet.Listener = (*RelayListener)(nil)

type RelayListener Relay

func (l *RelayListener) Relay() *Relay {
	return (*Relay)(l)
}

func (r *Relay) Listener() *RelayListener {
	// TODO: Only allow one!
	return (*RelayListener)(r)
}

func (l *RelayListener) Accept() (manet.Conn, error) {
	select {
	case c := <-l.incoming:
		err := l.Relay().writeResponse(c.Stream, pb.CircuitRelay_SUCCESS)
		if err != nil {
			log.Debugf("error writing relay response: %s", err.Error())
			c.Stream.Reset()
			return nil, err
		}

		// TODO: Pretty print.
		log.Infof("accepted relay connection: %q", c)

		return c, nil
	case <-l.ctx.Done():
		return nil, l.ctx.Err()
	}
}

func (l *RelayListener) Addr() net.Addr {
	return &NetAddr{
		Relay:  "any",
		Remote: "any",
	}
}

func (l *RelayListener) Multiaddr() ma.Multiaddr {
	return ma.Cast(ma.CodeToVarint(P_CIRCUIT))
}

func (l *RelayListener) Close() error {
	// TODO: noop?
	return nil
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:context="http://www.springframework.org/schema/context"  xmlns:jpa="http://www.springframework.org/schema/data/jpa"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
		http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"
	default-lazy-init="false" default-autowire="byName">

	<description>MyBatis-ActiveSQL</description>

	<context:component-scan base-package="org.makersoft"/>

	<bean id="sqlSessionFactory" class="org.makersoft.activesql.ActiveSQLSessionFactoryBean">
		<property name="configLocation" value="classpath:mybatis/configuration.xml" />
		<property name="dataSource" ref="dataSource" />
		<property name="mapperLocations" value="classpath*:mybatis/mappers/*.xml" />
	</bean>

	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="org.makersoft.activesql.mapper" />
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
	</bean>

	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>

	<!-- 使用annotation定义事务
	<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
	 -->
	<beans profile="test">
		<!-- 定义受环境影响易变的变量 -->
		<context:property-placeholder ignore-resource-not-found="false" location="classpath*:/application.properties" />

		<!-- Simple连接池 -->
		<bean id="dataSource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
			<property name="driverClass" value="org.h2.Driver" />
			<property name="url" value="jdbc:h2:mem:activesql;DB_CLOSE_DELAY=-1" />
			<property name="username" value="sa" />
			<property name="password" value="" />
		</bean>

		<!-- 初始化数据表结构 与默认数据-->
        <jdbc:initialize-database data-source="dataSource">
                <jdbc:script location="classpath:sql/h2.create.sql" encoding="UTF-8"/>
        </jdbc:initialize-database>
	</beans>
</beans>


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

<TITLE>
Uses of Class org.apache.fop.pdf.PDFFunction (Apache FOP 1.1 API)
</TITLE>

<META NAME="date" CONTENT="2012-10-16">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

fop 1.1

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
org.apache.fop.pdf.PDFFunction

Packages that use PDFFunction

org.apache.fop.pdf
Classes for handling the low-level creation of PDF documents.

Uses of PDFFunction in org.apache.fop.pdf

Fields in org.apache.fop.pdf declared as PDFFunction

protected  PDFFunction
PDFShading.function

          Required for Type 1, 2, and 3:
 The object of the color mapping function (usually type 2 or 3).

Methods in org.apache.fop.pdf that return PDFFunction

protected  PDFFunction
PDFDocument.findFunction(PDFFunction compare)

          Looks through the registered functions to see if one that is equal to
 a reference object exists

 PDFFunction
PDFFactory.makeFunction(int theNumber,
             int theFunctionType,
             java.util.List theDomain,
             java.util.List theRange,
             java.lang.StringBuffer theFunctionDataStream)

          make a postscript calculator function

 PDFFunction
PDFFactory.makeFunction(int theFunctionType,
             java.util.List theDomain,
             java.util.List theRange,
             java.util.List theSize,
             int theBitsPerSample,
             int theOrder,
             java.util.List theEncode,
             java.util.List theDecode,
             java.lang.StringBuffer theFunctionDataStream,
             java.util.List theFilter)

          Make a Type 0 sampled function

 PDFFunction
PDFFactory.makeFunction(int theFunctionType,
             java.util.List theDomain,
             java.util.List theRange,
             java.util.List theCZero,
             java.util.List theCOne,
             double theInterpolationExponentN)

          make a type Exponential interpolation function
 (for shading usually)

 PDFFunction
PDFFactory.makeFunction(int theFunctionType,
             java.util.List theDomain,
             java.util.List theRange,
             java.util.List theFunctions,
             java.util.List theBounds,
             java.util.List theEncode)

          Make a Type 3 Stitching function

Methods in org.apache.fop.pdf with parameters of type PDFFunction

protected  PDFFunction
PDFDocument.findFunction(PDFFunction compare)

          Looks through the registered functions to see if one that is equal to
 a reference object exists

 PDFShading
PDFFactory.makeShading(PDFResourceContext res,
            int theShadingType,
            PDFDeviceColorSpace theColorSpace,
            java.util.List theBackground,
            java.util.List theBBox,
            boolean theAntiAlias,
            int theBitsPerCoordinate,
            int theBitsPerComponent,
            int theBitsPerFlag,
            java.util.List theDecode,
            PDFFunction theFunction)

          Make a free-form gouraud shaded triangle mesh, coons patch mesh, or tensor patch mesh
 shading object

 PDFShading
PDFFactory.makeShading(PDFResourceContext res,
            int theShadingType,
            PDFDeviceColorSpace theColorSpace,
            java.util.List theBackground,
            java.util.List theBBox,
            boolean theAntiAlias,
            int theBitsPerCoordinate,
            int theBitsPerComponent,
            java.util.List theDecode,
            int theVerticesPerRow,
            PDFFunction theFunction)

          make a Lattice-Form Gouraud mesh shading object

 PDFShading
PDFFactory.makeShading(PDFResourceContext res,
            int theShadingType,
            PDFDeviceColorSpace theColorSpace,
            java.util.List theBackground,
            java.util.List theBBox,
            boolean theAntiAlias,
            java.util.List theDomain,
            java.util.List theMatrix,
            PDFFunction theFunction)

          make a function based shading object

 PDFShading
PDFFactory.makeShading(PDFResourceContext res,
            int theShadingType,
            PDFDeviceColorSpace theColorSpace,
            java.util.List theBackground,
            java.util.List theBBox,
            boolean theAntiAlias,
            java.util.List theCoords,
            java.util.List theDomain,
            PDFFunction theFunction,
            java.util.List theExtend)

          Make an axial or radial shading object.

Constructors in org.apache.fop.pdf with parameters of type PDFFunction

PDFSeparationColorSpace(java.lang.String colorName,
                        PDFFunction tintFunction)

          Creates a new "Separation" color space.

PDFShading(int theShadingType,
           PDFDeviceColorSpace theColorSpace,
           java.util.List theBackground,
           java.util.List theBBox,
           boolean theAntiAlias,
           int theBitsPerCoordinate,
           int theBitsPerComponent,
           int theBitsPerFlag,
           java.util.List theDecode,
           PDFFunction theFunction)

          Constructor for Type 4,6, or 7

PDFShading(int theShadingType,
           PDFDeviceColorSpace theColorSpace,
           java.util.List theBackground,
           java.util.List theBBox,
           boolean theAntiAlias,
           int theBitsPerCoordinate,
           int theBitsPerComponent,
           java.util.List theDecode,
           int theVerticesPerRow,
           PDFFunction theFunction)

          Constructor for type 5

PDFShading(int theShadingType,
           PDFDeviceColorSpace theColorSpace,
           java.util.List theBackground,
           java.util.List theBBox,
           boolean theAntiAlias,
           java.util.List theDomain,
           java.util.List theMatrix,
           PDFFunction theFunction)

          Constructor for type function based shading

PDFShading(int theShadingType,
           PDFDeviceColorSpace theColorSpace,
           java.util.List theBackground,
           java.util.List theBBox,
           boolean theAntiAlias,
           java.util.List theCoords,
           java.util.List theDomain,
           PDFFunction theFunction,
           java.util.List theExtend)

          Constructor for Type 2 and 3

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

fop 1.1

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright 1999-2012 The Apache Software Foundation. All Rights Reserved.


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

namespace LogCirDes
{
    public class Component : Renderable
    {
        public Component(string texturePath) : base(texturePath)
        {
        }
    }
}


text:
package org.pentaho.di.core.changed;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

public class ChangedFlag implements ChangedFlagInterface
{
	private List<PDIObserver> obs = Collections.synchronizedList(new ArrayList<PDIObserver>());

	private AtomicBoolean changed = new AtomicBoolean();

	public void addObserver(PDIObserver o)
	{
		if (o == null)
			throw new NullPointerException();
		if (!obs.contains(o))
		{
			obs.add(o);
		}
	}

	public synchronized void deleteObserver(PDIObserver o)
	{
		obs.remove(o);
	}

	public void notifyObservers(Object arg)
	{

		PDIObserver[] lobs;
		synchronized (this)
		{
			if (!changed.get())
				return;
			lobs = obs.toArray(new PDIObserver[obs.size()]);
			clearChanged();
		}
		for (int i = lobs.length - 1; i >= 0; i--)
			lobs[i].update(this, arg);
	}

    /**
     * Sets this as being changed.
     */
	public void setChanged()
	{
		changed.set(true);
	}

    /**
     * Sets whether or not this has changed.
     * @param ch true if you want to mark this as changed, false otherwise
     */
	public void setChanged(boolean b)
	{
		changed.set(b);
	}

    /**
     * Clears the changed flags.
     */
	public void clearChanged()
	{
		changed.set(false);
	}

    /**
     * Checks whether or not this has changed.
     * @return true if the this has changed, false otherwise
     */
	public synchronized boolean hasChanged()
	{
		return changed.get();
	}

}


text:
.class Lcom/htc/service/IGestureService$Stub$Proxy;
.super Ljava/lang/Object;
.source "IGestureService.java"

# interfaces
.implements Lcom/htc/service/IGestureService;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/htc/service/IGestureService$Stub;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0xa
    name = "Proxy"
.end annotation

# instance fields
.field private mRemote:Landroid/os/IBinder;

# direct methods
.method constructor <init>(Landroid/os/IBinder;)V
    .locals 0
    .parameter "remote"

    .prologue
    .line 55
    invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V

    .line 56
    iput-object p1, p0, Lcom/htc/service/IGestureService$Stub$Proxy;->mRemote:Landroid/os/IBinder;

    .line 57
    return-void
.end method

# virtual methods
.method public asBinder()Landroid/os/IBinder;
    .locals 1

    .prologue
    .line 60
    iget-object v0, p0, Lcom/htc/service/IGestureService$Stub$Proxy;->mRemote:Landroid/os/IBinder;

    return-object v0
.end method

.method public getInterfaceDescriptor()Ljava/lang/String;
    .locals 1

    .prologue
    .line 64
    const-string v0, "com.htc.service.IGestureService"

    return-object v0
.end method


text:
#include <warn/push>
#include <warn/ignore/all>
#include <gtest/gtest.h>
#include <warn/pop>

#include <inviwo/core/network/processornetwork.h>
#include <inviwo/core/processors/processorfactory.h>
#include <inviwo/core/util/logerrorcounter.h>
#include <inviwo/core/datastructures/transferfunction.h>
#include <inviwo/core/properties/transferfunctionproperty.h>
#include <inviwo/core/common/inviwoapplication.h>
#include <inviwo/core/common/inviwomodule.h>

namespace inviwo {

class ProcessorCreationTests : public ::testing::TestWithParam<std::string> {
protected:
    ProcessorCreationTests() : p(nullptr) {}

    virtual ~ProcessorCreationTests() { EXPECT_TRUE(p == nullptr); }

    virtual void SetUp() {
        isAdded_ = false;
    }

    virtual void TearDown() {
        if (isAdded_) {
            ProcessorNetwork *pn = InviwoApplication::getPtr()->getProcessorNetwork();
            size_t sizeBefore = pn->getProcessors().size();

            pn->removeAndDeleteProcessor(p);

            size_t sizeAfter = pn->getProcessors().size();
            EXPECT_EQ(sizeBefore, sizeAfter + 1);
        } else if (p) {
            p->deinitialize();
            delete p;
        }
        p = nullptr;
    }

    void create() {
        size_t warnCount = LogErrorCounter::getPtr()->getWarnCount();
        size_t errCount = LogErrorCounter::getPtr()->getErrorCount();

        auto s = InviwoApplication::getPtr()->getProcessorFactory()->create(GetParam());
        ASSERT_TRUE(s.get() != nullptr);

        p = dynamic_cast<Processor *>(s.get());
        ASSERT_TRUE(p != nullptr);
        s.release();
        EXPECT_EQ(warnCount, LogErrorCounter::getPtr()->getWarnCount());
        EXPECT_EQ(errCount, LogErrorCounter::getPtr()->getErrorCount());
    }

    void initialize() {
        size_t warnCount = LogErrorCounter::getPtr()->getWarnCount();
        size_t errCount = LogErrorCounter::getPtr()->getErrorCount();

        p->initialize();
        EXPECT_EQ(warnCount, LogErrorCounter::getPtr()->getWarnCount());
        EXPECT_EQ(errCount, LogErrorCounter::getPtr()->getErrorCount());
    }

    void resetAllPoperties() {
        size_t warnCount = LogErrorCounter::getPtr()->getWarnCount();
        size_t errCount = LogErrorCounter::getPtr()->getErrorCount();

        p->resetAllPoperties();
        EXPECT_EQ(warnCount, LogErrorCounter::getPtr()->getWarnCount());
        EXPECT_EQ(errCount, LogErrorCounter::getPtr()->getErrorCount());
    }

    void addProcessor() {
        size_t warnCount = LogErrorCounter::getPtr()->getWarnCount();
        size_t errCount = LogErrorCounter::getPtr()->getErrorCount();

        InviwoApplication::getPtr()->getProcessorNetwork()->addProcessor(p);
        EXPECT_EQ(warnCount, LogErrorCounter::getPtr()->getWarnCount());
        EXPECT_EQ(errCount, LogErrorCounter::getPtr()->getErrorCount());
        isAdded_ = true;
    }

    Processor *p;
    bool isAdded_;
};

const std::vector<std::string> getListOfProcessors() {
    std::vector<std::string> theVec;
    for (const auto& module : InviwoApplication::getPtr()->getModules()) {
        for (const auto& processor: module->getProcessors()) {
            theVec.push_back(processor->getClassIdentifier());
        }
    }
    return theVec;
}

//
// TEST_P(ProcessorCreationTests,ProcesorCreate){
//    initialize();
//}
//
// TEST_P(ProcessorCreationTests,ProcesorCreateAndReset){
//    initialize();
//    resetAllPoperties();
//}
//
//
// TEST_P(ProcessorCreationTests,ProcesorCreateAndAddToNetwork){
//    initialize();
//    addProcessor();
//}

// disabled the 3 test above since they are only needed when the following test fails

TEST_P(ProcessorCreationTests, ProcesorCreateAndResetAndAddToNetwork) {
    create();
    initialize();
    resetAllPoperties();
    addProcessor();
}

INSTANTIATE_TEST_CASE_P(RegisteredProcessors, ProcessorCreationTests,
                        ::testing::ValuesIn(getListOfProcessors()));
}


text:
import csv
import multiprocessing
import os
import string
import subprocess
import warnings

from django.utils import timezone
from typing import Dict
import numpy as np
import pandas as pd

from data_refinery_common.logging import get_and_configure_logger
from data_refinery_common.job_lookup import ProcessorPipeline
from data_refinery_common.message_queue import send_job
from data_refinery_common.models import (
    ComputationalResult,
    ComputedFile,
    OriginalFile,
    OriginalFileSampleAssociation,
    Pipeline,
    Processor,
    ProcessorJob,
    ProcessorJobOriginalFileAssociation,
    Sample,
    SampleAnnotation,
    SampleComputedFileAssociation,
    SampleResultAssociation,
)
from data_refinery_common.utils import get_env_variable
from data_refinery_workers.processors import utils

S3_BUCKET_NAME = get_env_variable("S3_BUCKET_NAME", "data-refinery")
LOCAL_ROOT_DIR = get_env_variable("LOCAL_ROOT_DIR", "/home/user/data_store")
logger = get_and_configure_logger(__name__)

def _prepare_files(job_context: Dict) -> Dict:
    """Adds the keys "input_file_path" and "output_file_path" to
    job_context so everything is prepared for processing.
    """
    # All files for the job are in the same directory.
    job_context["work_dir"] = LOCAL_ROOT_DIR + "/" + "processor_job_" + str(job_context["job_id"]) + "/"
    os.makedirs(job_context["work_dir"], exist_ok=True)

    original_file = job_context["original_files"][0]
    sanitized_filename = original_file.absolute_file_path.split('/')[-1]  + ".sanitized"
    job_context['input_file_path'] = job_context['work_dir'] + sanitized_filename

    new_filename= original_file.absolute_file_path.split('/')[-1].replace('.txt', '.PCL')
    job_context["output_file_path"] = job_context["work_dir"] +  new_filename

    # Sanitize this file so R doesn't choke.
    # Some have comments, some have non-comment-comments.
    with open(original_file.absolute_file_path, "r") as file_input:
        with open(job_context["input_file_path"], "w") as file_output:
            for line in file_input:
                if '#' not in line and \
                line.strip() != '' and \
                line != '\n' and \
                '\t' in line and \
                line[0:3].upper() != "GSM" and \
                line[0] != "'" and \
                line[0] != '"' and \
                line[0] != '!' and \
                line[0] != '/' and \
                line[0] != '<' and \
                line[0] != '\t':
                    file_output.write(line)

    return job_context

def _detect_columns(job_context: Dict) -> Dict:
    """ Detect which columns match to which inputs.

    Related: https://github.com/AlexsLemonade/refinebio/issues/86#issuecomment-379308817

    We need to find:

        First column should be ID_REF or PROBE_ID and the type should be string.
        Detection Pval column
        Expression column (contains sample title and NOT 'BEAD')

        Header examples:
            ['ID_REF', 'LV-C&si-Control-1', 'Detection Pval',
            'LV-C&si-Control-2', 'Detection Pval', 'LV-C&si-Control-3', 'Detection
            Pval', 'LV-C&si-EZH2-1', 'Detection Pval', 'LV-C&si-EZH2-2', 'Detection
            Pval', 'LV-C&si-EZH2-3', 'Detection Pval', 'LV-EZH2&si-EZH2-1',
            'Detection Pval', 'LV-EZH2&si-EZH2-2', 'Detection Pval', 'LV-EZH2&si-
            EZH2-3', 'Detection Pval', 'LV-T350A&si-EZH2-1', 'Detection Pval', 'LV-
            T350A&si-EZH2-2', 'Detection Pval', 'LV-T350A&si-EZH2-3', 'Detection
            Pval']

    Adds the following keys to job_context:
        columnIds: the identifiers of columns which contain expression data
        probeId: which is the value of the column containing the probe identifiers.
        detectionPval: a string which identifies Pvalue columns
    """
    try:
        input_file = job_context["input_file_path"]
        headers = None
        with open(input_file, 'r') as tsv_in:
            tsv_in = csv.reader(tsv_in, delimiter='\t')
            for row in tsv_in:
                headers = row
                break

        # Ex GSE45331_non-normalized.txt
        predicted_header = 0
        if headers[0].upper() in ["TARGETID", "TARGET_ID"]:
            predicted_header = 1

        # First the probe ID column
        if headers[predicted_header].upper() not in ["ID_REF", "PROBE_ID", "IDREF", "PROBEID", "REF_ID", "REFID", "IDPROBE", "ID_PROBE"]:
            job_context["job"].failure_reason = ("Could not find any ID column in headers "
                                + str(headers) + " for file " + job_context["input_file_path"])
            job_context["success"] = False
            return job_context
        else:
            job_context['probeId'] = headers[predicted_header]

        # Then the detection Pvalue string, which is always(?) some form of 'Detection Pval'
        for header in headers:
            if 'DETECTION_PVAL' in header.upper().replace(' ', '_'):
                # Could be <SAMPLE_ID>.Detection Pval, etc
                if '.' in header:
                    job_context['detectionPval'] = header.split('.')[-1]
                else:
                    job_context['detectionPval'] = header
                break
        else:
            job_context["job"].failure_reason = "Could not detect PValue column!"
            job_context["success"] = False
            job_context["job"].no_retry = True
            return job_context

        # Then, finally, create an absolutely bonkers regular expression
        # which will explicitly hit on any sample which contains a sample
        # ID _and_ ignores the magical word 'BEAD', etc. Great!
        column_ids = ""
        for sample in job_context['samples']:
            for offset, header in enumerate(headers, start=1):

                if sample.title == header:
                    column_ids = column_ids + str(offset) + ","
                    continue

                # Sometimes the title might actually be in the description field.
                # To find this, look in all the related SampleAnnotations.
                # Since there are multiple annotations, we need to break early before continuing.
                # Related: https://github.com/AlexsLemonade/refinebio/issues/499
                continue_me = False
                for annotation in sample.sampleannotation_set.filter(is_ccdl=False):
                    try:
                        if annotation.data.get('description', '')[0] == header:
                            column_ids = column_ids + str(offset) + ","
                            continue_me = True
                            break
                    except Exception:
                        pass
                if continue_me:
                    # Treat the header as the real title, as we will need it later.
                    sample.title = header
                    sample.save()
                    continue

                if header.upper().replace(' ', '_') == "RAW_VALUE":
                    column_ids = column_ids + str(offset) + ","
                    continue

                if sample.title.upper() in header.upper() and \
                'BEAD' not in header.upper() and \
                'NARRAYS' not in header.upper() and \
                'ARRAY_STDEV' not in header.upper() and \
                'PVAL' not in header.upper().replace(' ', '').replace('_', ''):
                    column_ids = column_ids + str(offset) + ","
                    continue

        for offset, header in enumerate(headers, start=1):
            if 'AVG_Signal' in header:
                column_ids = column_ids + str(offset) + ","
                continue

        # Remove the trailing comma
        column_ids = column_ids[:-1]
        job_context['columnIds'] = column_ids
    except Exception as e:
        job_context["job"].failure_reason = str(e)
        job_context["success"] = False
        logger.exception("Failed to extract columns in " + job_context["input_file_path"], exception=str(e))
        job_context["job"].no_retry = True
        return job_context

    return job_context

def _detect_platform(job_context: Dict) -> Dict:
    """
    Determine the platform/database to process this sample with.
    They often provide something like "V2" or "V 2", but we don't trust them so we detect it ourselves.

    Related: https://github.com/AlexsLemonade/refinebio/issues/232
    """

    all_databases = {
        'HOMO_SAPIENS': [
            'illuminaHumanv1',
            'illuminaHumanv2',
            'illuminaHumanv3',
            'illuminaHumanv4',
        ],
        'MUS_MUSCULUS': [
            'illuminaMousev1',
            'illuminaMousev1p1',
            'illuminaMousev2',
        ],
        'RATTUS_NORVEGICUS': [
            'illuminaRatv1'
        ]
    }

    sample0 = job_context['samples'][0]
    databases = all_databases[sample0.organism.name]

    # Loop over all of the possible platforms and find the one with the best match.
    highest = 0.0
    high_mapped_percent = 0.0
    high_db = None
    for platform in databases:
        try:
            result = subprocess.check_output([
                    "/usr/bin/Rscript",
                    "--vanilla",
                    "/home/user/data_refinery_workers/processors/detect_database.R",
                    "--platform", platform,
                    "--inputFile", job_context['input_file_path'],
                    "--column", job_context['probeId'],
                ])

            results = result.decode().split('\n')
            cleaned_result = float(results[0].strip())

            if cleaned_result > highest:
                highest = cleaned_result
                high_db = platform
                high_mapped_percent = float(results[1].strip())

        except Exception as e:
            logger.exception(e, processor_job_id=job_context["job"].id)
            continue

    # Record our sample detection outputs for every sample.
    for sample in job_context['samples']:
        sa = SampleAnnotation()
        sa.sample = sample
        sa.is_ccdl = True
        sa.data = {
            "detected_platform": high_db,
            "detection_percentage": highest,
            "mapped_percentage": high_mapped_percent
        }
        sa.save()

    # If the match is over 75%, record this and process it on that platform.
    if high_mapped_percent > 75.0:
        job_context['platform'] = high_db
    # The match percentage is too low - send this to the no-opper instead.
    else:

        logger.info("Match percentage too low, NO_OP'ing and aborting.",
            job=job_context['job_id'])

        processor_job = ProcessorJob()
        processor_job.pipeline_applied = "NO_OP"
        processor_job.volume_index = job_context["job"].volume_index
        processor_job.ram_amount = job_context["job"].ram_amount
        processor_job.save()

        assoc = ProcessorJobOriginalFileAssociation()
        assoc.original_file = job_context["original_files"][0]
        assoc.processor_job = processor_job
        assoc.save()

        try:
            send_job(ProcessorPipeline.NO_OP, processor_job)
        except Exception as e:
            # Nomad dispatch error, likely during local test.
            logger.error(e, job=processor_job)

        job_context['abort'] = True

    return job_context

def _run_illumina(job_context: Dict) -> Dict:
    """Processes an input TXT file to an output PCL file using a custom R script.

    Expects a job_context which has been pre-populated with inputs, outputs
    and the column identifiers which the R script needs for processing.
    """
    input_file_path = job_context["input_file_path"]

    try:
        job_context['time_start'] = timezone.now()

        formatted_command = [
            "/usr/bin/Rscript",
            "--vanilla",
            "/home/user/data_refinery_workers/processors/illumina.R",
            "--probeId", job_context['probeId'],
            "--expression", job_context['columnIds'],
            "--detection", job_context['detectionPval'],
            "--platform", job_context['platform'],
            "--inputFile", job_context['input_file_path'],
            "--outputFile", job_context['output_file_path'],
            "--cores", str(multiprocessing.cpu_count())
        ]

        subprocess.check_output(formatted_command)

        job_context['formatted_command'] = " ".join(formatted_command)

        job_context['time_end'] = timezone.now()

    except Exception as e:
        error_template = ("Encountered error in R code while running illumina.R"
                          " pipeline during processing of {0}: {1}")
        error_message = error_template.format(job_context['input_file_path'], str(e))
        logger.error(error_message, processor_job=job_context["job_id"])
        job_context["job"].failure_reason = error_message
        job_context["success"] = False

    return job_context

def _create_result_objects(job_context: Dict) -> Dict:
    """ Create the ComputationalResult objects after a Scan run is complete """

    result = ComputationalResult()
    result.commands.append(job_context['formatted_command'])
    result.is_ccdl = True
    result.is_public = True
    result.time_start = job_context['time_start']
    result.time_end = job_context['time_end']
    try:
        processor_key = "ILLUMINA_SCAN"
        result.processor = utils.find_processor(processor_key)
    except Exception as e:
        return utils.handle_processor_exception(job_context, processor_key, e)

    result.save()
    job_context['pipeline'].steps.append(result.id)

    # Split the result into smashable subfiles
    big_tsv = job_context["output_file_path"]
    data = pd.read_csv(big_tsv, sep='\t', header=0, index_col=0)
    individual_files = []
    frames = np.split(data, len(data.columns), axis=1)
    for frame in frames:
        filename = frame.columns.values[0].replace('&', '').replace("*", '').replace(";", '') + '.tsv'
        frame_path = job_context["work_dir"] + filename
        frame.to_csv(frame_path, sep='\t', encoding='utf-8')

        # This needs to be the same as the ones in the job context!
        try:
            sample = job_context['samples'].get(title=frame.columns.values[0])
        except Sample.DoesNotExist:
            logger.error("Could not find sample for column while splitting Illumina file.",
                        title=frame.columns.values[0],
                        processor_job=job_context["job_id"],
                        file_path=big_tsv,
            )
            continue

        computed_file = ComputedFile()
        computed_file.absolute_file_path = frame_path
        computed_file.filename = frame_path.split('/')[-1]
        computed_file.result = result
        computed_file.is_smashable = True
        computed_file.is_qc = False
        computed_file.is_public = True
        computed_file.calculate_sha1()
        computed_file.calculate_size()
        computed_file.save()
        job_context['computed_files'].append(computed_file)

        SampleResultAssociation.objects.get_or_create(
            sample=sample,
            result=result)

        SampleComputedFileAssociation.objects.get_or_create(
            sample=sample,
            computed_file=computed_file)

        individual_files.append(computed_file)

    logger.debug("Created %s", result)
    job_context["success"] = True
    job_context["individual_files"] = individual_files
    job_context["result"] = result

    return job_context

def illumina_to_pcl(job_id: int) -> None:
    pipeline = Pipeline(name=utils.PipelineEnum.ILLUMINA.value)
    return utils.run_pipeline({"job_id": job_id, "pipeline": pipeline},
                              [utils.start_job,
                               _prepare_files,
                               _detect_columns,
                               _detect_platform,
                               _run_illumina,
                               _create_result_objects,
                               utils.end_job])