text:
<?php

namespace Locazik\UserBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Locazik\UserBundle\Entity\User;

use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\FormEvent;
use FOS\UserBundle\Event\FilterUserResponseEvent;
use FOS\UserBundle\Event\GetResponseUserEvent;
use FOS\UserBundle\Model\UserInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

class AccountController extends Controller
{
    public function showAction()
    {
        $user = $this->getUser();
        $data['nbAnnoncesOnline'] = $this->get('annonce_manager')->countAnnoncesFromUser($user);
        return $this->render('LocazikUserBundle:Account:show.html.twig', array('user' => $user, 'data' => $data));
    }

    public function listerAnnonceAction()
    {
        $user = $this->getUser();
        $listeAnnonces = $this->get('annonce_manager')->findAllBy(array('user' => $user));
        return $this->render('LocazikUserBundle:Account:listeAnnonces.html.twig', array('listeAnnonces' => $listeAnnonces));
    }

    public function getUser()
    {
        $user = $this->get('security.context')->getToken()->getUser();
        if (!is_object($user)) {
            throw new AccessDeniedException('This user does not have access to this section.');
        }
        return $user;
    }

    /*
    public function editAction(Request $request)
    {
        $user = $this->getUser();
        $dispatcher = $this->get('event_dispatcher');

        $event = new GetResponseUserEvent($user, $request);
        $dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_INITIALIZE, $event);

        if (null !== $event->getResponse()) {
            return $event->getResponse();
        }

        $formFactory = $this->get('fos_user.profile.form.factory');

        $form = $formFactory->createForm();
        $form->setData($user);

        if ('POST' === $request->getMethod()) {
            $form->bind($request);

            if ($form->isValid()) {
                $userManager = $this->get('fos_user.user_manager');

                $event = new FormEvent($form, $request);
                $dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_SUCCESS, $event);

                $userManager->updateUser($user);

                if (null === $response = $event->getResponse()) {
                    $url = $this->generateUrl('fos_user_profile_show');
                    $response = new RedirectResponse($url);
                }

                $dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_COMPLETED, new FilterUserResponseEvent($user, $request, $response));

                return $response;
            }
        }

        return $this->render('LocazikUserBundle:Account:edit.html.twig', array('form' => $form->createView()));
    }
     */

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Ceské Houby 4-5: 824 (1922)

#### Original name
Lycoperdon moravicum Velen.

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
/**
 * The examples provided by Facebook are for non-commercial testing and
 * evaluation purposes only.
 *
 * Facebook reserves all rights not expressly granted.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
 * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * @providesModule createExamplePage
 * @flow
 */
'use strict';

var React = require('react-native');
var {
  Platform,
} = React;
var ReactNative = require('ReactNative');
var UIExplorerBlock = require('./UIExplorerBlock');
var UIExplorerPage = require('./UIExplorerPage');

var invariant = require('invariant');

import type { Example, ExampleModule } from 'ExampleTypes';

var createExamplePage = function(title: ?string, exampleModule: ExampleModule)
  : ReactClass<any, any, any> {
  invariant(!!exampleModule.examples, 'The module must have examples');

  var ExamplePage = React.createClass({
    statics: {
      title: exampleModule.title,
      description: exampleModule.description,
    },

    getBlock: function(example: Example, i) {
      // Filter platform-specific examples
      var {title, description, platform} = example;
      if (platform) {
        if (Platform.OS !== platform) {
          return null;
        }
        title += ' (' + platform + ' only)';
      }
      // Hack warning: This is a hack because the www UI explorer requires
      // renderComponent to be called.
      var originalRender = React.render;
      var originalRenderComponent = React.renderComponent;
      var originalIOSRender = ReactNative.render;
      var originalIOSRenderComponent = ReactNative.renderComponent;
      var renderedComponent;
      // TODO remove typecasts when Flow bug #6560135 is fixed
      // and workaround is removed from react-native.js
      (React: Object).render =
      (React: Object).renderComponent =
      (ReactNative: Object).render =
      (ReactNative: Object).renderComponent =
        function(element, container) {
          renderedComponent = element;
        };
      var result = example.render(null);
      if (result) {
        renderedComponent = React.cloneElement(result, {
          navigator: this.props.navigator,
        });
      }
      (React: Object).render = originalRender;
      (React: Object).renderComponent = originalRenderComponent;
      (ReactNative: Object).render = originalIOSRender;
      (ReactNative: Object).renderComponent = originalIOSRenderComponent;
      return (
        <UIExplorerBlock
          key={i}
          title={title}
          description={description}>
          {renderedComponent}
        </UIExplorerBlock>
      );
    },

    render: function() {
      return (
        <UIExplorerPage title={title}>
          {exampleModule.examples.map(this.getBlock)}
        </UIExplorerPage>
      );
    }
  });

  return ExamplePage;
};

module.exports = createExamplePage;


text:
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'garlic'))

include Garlic

# configure the garlic runner
garlic ENV['CONFIG'] do
  verbose ['true', 'yes', '1'].include?(ENV['VERBOSE'])
  run_targets ENV['TARGETS'] || ENV['TARGET']
end

desc "Run garlic:default (CONFIG=path, TARGETS=list, VERBOSE=true)"
task :garlic do
  garlic.default
end

namespace :garlic do
  Garlic::Session.commands_with_description.each do |command, description|
    desc description
    task command do
      garlic.send command
    end
  end
end


text:
#import "NSObject.h"

// Not exported
@interface EXDifferentialStyle : NSObject
{
}

+ (id)edDifferentialStyleFromXmlDifferentialStyleElement:(struct _xmlNode *)arg1 state:(id)arg2;

@end


text:
KMP_AFFINITY=granularity=fine,noduplicates,compact,1,0 OMP_NUM_THREADS=1 numactl --physcpubind=0 --membind=0 python3 finetune_squad.py --only_calibration --model_parameters ./output_dir/net.params
# fp32 inference
python3 finetune_squad.py --only_predict --model_parameters ./output_dir/net.params --round_to 128 --dev_batch_size 1
# int8 inference
python3 finetune_squad.py --only_predict --model_prefix ./output_dir/model_bert_squad_quantized_customize --deploy --round_to 128 --test_batch_size 1


text:
require 'features_helper'

describe 'GET /api/books' do
  before do
    BookRepository.clear
    book
  end

  let(:book) { Book::Create.new('Clean Code', 'Robert Martin').call.book }

  it 'lists all books' do
    stdout, _stderr = cli_command('list')

    stdout.must_match book.title
    stdout.must_match book.author
  end
end


text:
package poussecafe.messaging;

import org.junit.Test;
import org.mockito.ArgumentCaptor;
import poussecafe.processing.MessageBroker;
import poussecafe.processing.ReceivedMessage;
import poussecafe.runtime.OriginalAndMarshaledMessage;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

public abstract class MessageReceiverTest {

    private Message message;

    private MessageBroker messageBroker;

    @Test
    public void receivedMessageIsConsumed() {
        givenMessageConsumer();
        whenConsumingMessage();
        thenListenerConsumes();
    }

    private void givenMessageConsumer() {
        message = message();
        messageBroker = mock(MessageBroker.class);
        connection = messaging().connect(new MessageReceiverConfiguration.Builder()
                .messageBroker(messageBroker)
                .build());
    }

    protected abstract Message message();

    protected abstract Messaging messaging();

    private MessagingConnection connection;

    @SuppressWarnings("unchecked")
    private void whenConsumingMessage() {
        envelope = envelope(message);
        serializedMessage = serializedMessage(envelope);
        payload = new OriginalAndMarshaledMessage.Builder()
                .original(message)
                .marshaled(serializedMessage)
                .build();
        connection.messageReceiver().onMessage(envelope);
    }

    private Object envelope;

    protected abstract Object envelope(Message message);

    private Object serializedMessage;

    protected abstract Object serializedMessage(Object envelope);

    private OriginalAndMarshaledMessage payload;

    private void thenListenerConsumes() {
        ArgumentCaptor<ReceivedMessage> captor = ArgumentCaptor.forClass(ReceivedMessage.class);
        verify(messageBroker).dispatch(captor.capture());
        assertThat(captor.getValue().message(), is(payload));
    }
}


text:
package org.apache.geode;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import org.apache.geode.internal.cache.GemFireCacheImpl;
import org.apache.geode.internal.cache.TestObjectWithIdentifier;

/**
 * Sample test class which implements Delta.
 *
 * @since GemFire 6.1
 */
public class DeltaTestImpl implements DataSerializable, Delta {

  private static final byte INT_MASK = 0x1;
  private static final byte STR_MASK = 0x2;
  private static final byte DOUBLE_MASK = 0x4;
  private static final byte BYTE_ARR_MASK = 0x8;
  private static final byte TEST_OBJ_MASK = 0x10;
  private static final byte COMPLETE_MASK = 0x1F;

  /*****************************************************************************
   * Below fields are not part of standard Delta implementation but are used for testing purpose.
   */
  public static final String ERRONEOUS_STRING_FOR_FROM_DELTA = "ERRONEOUS_STRING";
  public static final int ERRONEOUS_INT_FOR_TO_DELTA = -101;
  private static long fromDeltaInvokations;
  private static long toDeltaInvokations;
  private static long toDeltaFailure;
  private static long fromDeltaFailure;
  private static long timesConstructed = 0;
  public static boolean NEED_TO_RESET_T0_DELTA = true;
  /** *********************************************************************** */

  // Actual data fields of this instance.
  private int intVar = 0; // 0000 0001
  private String str = ""; // 0000 0010
  private Double doubleVar = new Double(0); // 0000 0100
  private byte[] byteArr = new byte[1]; // 0000 1000
  private TestObjectWithIdentifier testObj = new TestObjectWithIdentifier(); // 0001 0000

  /**
   * Indicates the fields containing delta.
   */
  private byte deltaBits = 0x0;

  private boolean hasDelta = false;

  private static List<Exception> instantiations = new ArrayList<>();

  public static List<Exception> getInstantiations() {
    return instantiations;
  }

  public DeltaTestImpl() {
    timesConstructed++;
    instantiations.add(new Exception("DeltaTestImpl"));
  }

  public DeltaTestImpl(int intVal, String str) {
    this.intVar = intVal;
    this.str = str;
  }

  public DeltaTestImpl(int intVal, String string, Double doubleVal, byte[] bytes,
      TestObjectWithIdentifier testObj) {
    this.intVar = intVal;
    this.str = string;
    this.doubleVar = doubleVal;
    this.byteArr = bytes;
    this.testObj = testObj;
  }

  public static long getTimesConstructed() {
    return timesConstructed;
  }

  public static void setTimesConstructed(long cnt) {
    timesConstructed = cnt;
  }

  public void resetDeltaStatus() {
    this.deltaBits = 0x0;
    this.hasDelta = false;
  }

  public byte[] getByteArr() {
    return byteArr;
  }

  public void setByteArr(byte[] bytes) {
    this.byteArr = bytes;
    this.deltaBits |= BYTE_ARR_MASK;
    this.hasDelta = true;
  }

  public Double getDoubleVar() {
    return doubleVar;
  }

  public void setDoubleVar(Double doubleVar) {
    this.doubleVar = doubleVar;
    this.deltaBits |= DOUBLE_MASK;
    this.hasDelta = true;
  }

  public int getIntVar() {
    return intVar;
  }

  public void setIntVar(int intVar) {
    this.intVar = intVar;
    this.deltaBits |= INT_MASK;
    this.hasDelta = true;
  }

  public String getStr() {
    return str;
  }

  public void setStr(String str) {
    this.str = str;
    this.deltaBits |= STR_MASK;
    this.hasDelta = true;
  }

  public TestObjectWithIdentifier getTestObj() {
    return testObj;
  }

  public void setTestObj(TestObjectWithIdentifier testObj) {
    this.testObj = testObj;
    this.deltaBits |= TEST_OBJ_MASK;
    this.hasDelta = true;
  }

  /*****************************************************************************
   * Below methods are not part of standard Delta implementation but are used for testing purpose.
   */
  public static void resetDeltaInvokationCounters() {
    resetToDeltaCounter();
    resetFromDeltaCounter();
    resetFailureCounter();
  }

  public static void resetToDeltaCounter() {
    toDeltaInvokations = 0;
  }

  public static void resetFromDeltaCounter() {
    fromDeltaInvokations = 0;
  }

  public static void resetFailureCounter() {
    toDeltaFailure = 0;
    fromDeltaFailure = 0;
  }

  public static Boolean deltaFeatureUsed() {
    return (toDeltaInvokations > 0) || (fromDeltaInvokations > 0);
  }

  public static Boolean toDeltaFeatureUsed() {
    return (toDeltaInvokations > 0);
  }

  public static Long getFromDeltaInvokations() {
    return fromDeltaInvokations;
  }

  public static Long getToDeltaInvokations() {
    return toDeltaInvokations;
  }

  public static Boolean fromDeltaFeatureUsed() {
    return (fromDeltaInvokations > 0);
  }

  public static Boolean isFromDeltaFailure() {
    return (fromDeltaFailure > 0);
  }

  public static Boolean isToDeltaFailure() {
    return (toDeltaFailure > 0);
  }

  public static Long getFromDeltaFailures() {
    return fromDeltaFailure;
  }

  public static Long getToDeltaFailures() {
    return toDeltaFailure;
  }

  protected void checkInvalidString(String str) {
    if (ERRONEOUS_STRING_FOR_FROM_DELTA.equals(str)) {
      fromDeltaFailure++;
      throw new InvalidDeltaException("Delta could not be applied. " + this);
    }
  }

  protected void checkInvalidInt(int intVal) {
    if (ERRONEOUS_INT_FOR_TO_DELTA == intVal) {
      toDeltaFailure++;
      throw new InvalidDeltaException("Delta could not be extracted. " + this);
    }
  }

  protected void checkInvalidInt2(int intVal) {}

  /** ********************************************************************** */

  @Override
  public String toString() {
    StringBuffer bytes = new StringBuffer("");
    if (byteArr != null) {
      for (int i = 0; i < byteArr.length; i++) {
        bytes.append(byteArr[i]);
      }
    }
    return "DeltaTestImpl[hasDelta=" + this.hasDelta + ",int=" + this.intVar + ",double="
        + this.doubleVar + ",str=" + this.str + ",bytes={" + bytes.toString() + "},testObj="
        + ((this.testObj != null) ? this.testObj.hashCode() : "") + "]";
  }

  @Override
  public boolean equals(Object other) {
    if (!(other instanceof DeltaTestImpl)) {
      return false;
    }
    DeltaTestImpl delta = (DeltaTestImpl) other;
    if (this.intVar == delta.intVar && this.doubleVar.equals(delta.doubleVar)
        && Arrays.equals(this.byteArr, delta.byteArr) && this.str.equals(delta.str)) {
      return true;
    }
    return false;
  }

  @Override
  public int hashCode() {
    int result = Objects.hash(intVar, str, doubleVar);
    result = 31 * result + Arrays.hashCode(byteArr);
    return result;
  }

  @Override
  public void fromDelta(DataInput in) throws IOException {
    try {
      fromDeltaInvokations++;
      boolean tempHasDelta = false;
      byte tempDeltaBits = this.deltaBits;
      byte[] tempByteArr = this.byteArr;
      int tempIntVar = this.intVar;
      double tempDoubleVar = this.doubleVar;
      String tempStr = this.str;
      TestObjectWithIdentifier tempTestObj = this.testObj;

      tempDeltaBits = DataSerializer.readByte(in);
      if (tempDeltaBits != 0) {
        tempHasDelta = true;
        if ((tempDeltaBits & INT_MASK) == INT_MASK) {
          tempIntVar = DataSerializer.readPrimitiveInt(in);
          checkInvalidInt2(tempIntVar);
        }
        if ((tempDeltaBits & STR_MASK) == STR_MASK) {
          tempStr = DataSerializer.readString(in);
          checkInvalidString(tempStr); // Simulates exception
        }
        if ((tempDeltaBits & DOUBLE_MASK) == DOUBLE_MASK) {
          tempDoubleVar = DataSerializer.readDouble(in);
        }
        if ((tempDeltaBits & BYTE_ARR_MASK) == BYTE_ARR_MASK) {
          tempByteArr = DataSerializer.readByteArray(in);
        }
        if ((tempDeltaBits & TEST_OBJ_MASK) == TEST_OBJ_MASK) {
          tempTestObj = DataSerializer.readObject(in);
        }
        if ((deltaBits | COMPLETE_MASK) != COMPLETE_MASK) {
          throw new IllegalArgumentException("Unknown field code: " + tempDeltaBits);
        }
      }
      if (tempHasDelta) {
        this.intVar = tempIntVar;
        this.str = tempStr;
        this.doubleVar = tempDoubleVar;
        this.byteArr = tempByteArr;
        this.testObj = tempTestObj;
      }
    } catch (IOException e) {
      GemFireCacheImpl.getInstance().getLogger().warning("DeltaTestImpl.fromDelta(): " + e);
      throw e;
    } catch (IllegalArgumentException iae) {
      GemFireCacheImpl.getInstance().getLogger().warning("DeltaTestImpl.fromDelta(): " + iae);
      throw new InvalidDeltaException(iae);
    } catch (ClassNotFoundException cnfe) {
      GemFireCacheImpl.getInstance().getLogger().warning("DeltaTestImpl.fromDelta(): " + cnfe);
      throw new InvalidDeltaException(cnfe);
    }
  }

  @Override
  public boolean hasDelta() {
    return this.hasDelta;
  }

  @Override
  public void toDelta(DataOutput out) throws IOException {
    try {
      toDeltaInvokations++;
      DataSerializer.writeByte(this.deltaBits, out);

      if (deltaBits != 0) {
        if ((deltaBits & INT_MASK) == INT_MASK) {
          DataSerializer.writePrimitiveInt(this.intVar, out);
          checkInvalidInt(this.intVar); // Simulates exception
        }
        if ((deltaBits & STR_MASK) == STR_MASK) {
          DataSerializer.writeString(this.str, out);
        }
        if ((deltaBits & DOUBLE_MASK) == DOUBLE_MASK) {
          DataSerializer.writeDouble(this.doubleVar, out);
        }
        if ((deltaBits & BYTE_ARR_MASK) == BYTE_ARR_MASK) {
          DataSerializer.writeByteArray(this.byteArr, out);
        }
        if ((deltaBits & TEST_OBJ_MASK) == TEST_OBJ_MASK) {
          DataSerializer.writeObject(this.testObj, out);
        }
        if ((deltaBits | COMPLETE_MASK) != COMPLETE_MASK) {
          throw new IllegalArgumentException("Unknown field code: " + deltaBits);
        }
      }
    } catch (IOException ioe) {
      GemFireCacheImpl.getInstance().getLogger().warning("DeltaTestImpl.toDelta(): " + ioe);
      throw ioe;
    } catch (IllegalArgumentException iae) {
      GemFireCacheImpl.getInstance().getLogger().warning("DeltaTestImpl.toDelta(): " + iae);
      throw new InvalidDeltaException(iae);
    } finally {
      if (NEED_TO_RESET_T0_DELTA) {
        // No need to reset if secondary needs to send delta again upon receiving
        // forceReattemptException
        this.deltaBits = 0x0;
        this.hasDelta = false;
      }
    }
  }

  @Override
  public void fromData(DataInput in) throws IOException, ClassNotFoundException {
    this.intVar = DataSerializer.readPrimitiveInt(in);
    this.str = DataSerializer.readString(in);
    this.doubleVar = DataSerializer.readDouble(in);
    this.byteArr = DataSerializer.readByteArray(in);
    this.testObj = DataSerializer.readObject(in);
  }

  @Override
  public void toData(DataOutput out) throws IOException {
    DataSerializer.writePrimitiveInt(this.intVar, out);
    DataSerializer.writeString(this.str, out);
    DataSerializer.writeDouble(this.doubleVar, out);
    DataSerializer.writeByteArray(this.byteArr, out);
    DataSerializer.writeObject(this.testObj, out);
  }
}


text:
using System;
using System.Text;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using MonoGame.Extended.BitmapFonts;
using MonoGame.Extended.Graphics.Effects;
using MonoGame.Extended.Graphics.Geometry;

namespace MonoGame.Extended.Graphics
{
    ///
    ///     A general purpose <see cref="Batcher{TDrawCallInfo}" /> for two-dimensional geometry that change
    ///     frequently between frames such as sprites and shapes.
    ///
    /// <seealso cref="IDisposable" />
    /// <remarks>
    ///     <para>For drawing user interfaces, consider using <see cref="UIBatcher(ref Matrix, ref Matrix, BlendState, SamplerState, DepthStencilState, RasterizerState, Effect)" /> instead because it supports scissor rectangles.</para>
    /// </remarks>
    public sealed class Batcher2D : Batcher<Batcher2D.DrawCallInfo>
    {

        internal const int DefaultMaximumVerticesCount = 8192;
        internal const int DefaultMaximumIndicesCount = 12288;

        private readonly VertexBuffer _vertexBuffer;
        private readonly IndexBuffer _indexBuffer;
        private readonly VertexPositionColorTexture[] _vertices;
        private int _vertexCount;
        private readonly ushort[] _indices;
        private int _indexCount;
        private readonly ushort[] _sortedIndices;
        private readonly GeometryBuilder2D _geometryBuilder;

        ///
        ///     Initializes a new instance of the <see cref="Batcher2D" /> class.
        ///
        /// <param name="graphicsDevice">The graphics device.</param>
        /// <param name="maximumVerticesCount">
        ///     The maximum number of vertices that can be enqueued before a
        ///     <see cref="Batcher{TDrawCallInfo}.Flush" /> is required. The default value is 8192.
        /// </param>
        /// <param name="maximumIndicesCount">
        ///     The maximum number of indices that can be enqueued before a
        ///     <see cref="Batcher{TDrawCallInfo}.Flush" /> is required. The default value is 12288.
        /// </param>
        /// <param name="maximumDrawCallsCount">
        ///     The maximum number of <see cref="DrawCallInfo" /> structs that can be enqueued before a
        ///     <see cref="Batcher{TDrawCallInfo}.Flush" /> is required. The default value is 2048.
        /// </param>
        /// <exception cref="ArgumentNullException"><paramref name="graphicsDevice" />.</exception>
        /// <exception cref="ArgumentOutOfRangeException">
        ///     <paramref name="maximumDrawCallsCount" /> is less than or equal
        ///     0, or <paramref name="maximumVerticesCount" /> is less than or equal to 0, or,
        ///     <paramref name="maximumVerticesCount" /> is less than or equal to 0.
        /// </exception>
        public Batcher2D(GraphicsDevice graphicsDevice,
            ushort maximumVerticesCount = DefaultMaximumVerticesCount,
            ushort maximumIndicesCount = DefaultMaximumIndicesCount,
            int maximumDrawCallsCount = DefaultBatchMaximumDrawCallsCount)
            : base(
                graphicsDevice,
                new DefaultEffect(graphicsDevice)
                {
                    TextureEnabled =  true,
                    VertexColorEnabled = true
                }, maximumDrawCallsCount)

        {
            _vertices = new VertexPositionColorTexture[maximumVerticesCount];
            _vertexBuffer = new DynamicVertexBuffer(graphicsDevice, VertexPositionColorTexture.VertexDeclaration, maximumVerticesCount, BufferUsage.WriteOnly);

            _indices = new ushort[maximumIndicesCount];
            _sortedIndices = new ushort[maximumIndicesCount];
            _indexBuffer = new DynamicIndexBuffer(graphicsDevice, IndexElementSize.SixteenBits, maximumIndicesCount, BufferUsage.WriteOnly);
            _geometryBuilder = new GeometryBuilder2D(4, 6);
        }

        protected override void SortDrawCallsAndBindBuffers()
        {
            // Upload the vertices to the GPU and then select that vertex stream for drawing
            _vertexBuffer.SetData(_vertices, 0, _vertexCount);
            GraphicsDevice.SetVertexBuffer(_vertexBuffer);

            Array.Sort(DrawCalls, 0, EnqueuedDrawCallCount);
            BuildSortedIndices();

            // Upload the indices to the GPU and then select that index stream for drawing
            _indexBuffer.SetData(_sortedIndices, 0, _indexCount);
            GraphicsDevice.Indices = _indexBuffer;

            _indexCount = 0;
            _vertexCount = 0;
        }

        private void BuildSortedIndices()
        {
            var newDrawCallsCount = 0;
            DrawCalls[0].StartIndex = 0;
            var currentDrawCall = DrawCalls[0];
            DrawCalls[newDrawCallsCount++] = DrawCalls[0];

            var drawCallIndexCount = currentDrawCall.PrimitiveCount * 3;
            Array.Copy(_indices, currentDrawCall.StartIndex, _sortedIndices, 0, drawCallIndexCount);
            var sortedIndexCount = drawCallIndexCount;

            // iterate through sorted draw calls checking if any can now be merged to reduce expensive draw calls to the graphics API
            // this might need to be changed for next-gen graphics API (Vulkan, Metal, DirectX 12) where the draw calls are not so expensive
            for (var i = 1; i < EnqueuedDrawCallCount; i++)
            {
                currentDrawCall = DrawCalls[i];
                drawCallIndexCount = currentDrawCall.PrimitiveCount * 3;
                Array.Copy(_indices, currentDrawCall.StartIndex, _sortedIndices, sortedIndexCount, drawCallIndexCount);
                sortedIndexCount += drawCallIndexCount;

                if (currentDrawCall.TryMerge(ref DrawCalls[newDrawCallsCount - 1]))
                    continue;

                currentDrawCall.StartIndex = sortedIndexCount;
                DrawCalls[newDrawCallsCount++] = currentDrawCall;
            }

            EnqueuedDrawCallCount = newDrawCallsCount;
        }

        ///
        ///     Submits a draw operation to the <see cref="GraphicsDevice" /> using the specified <see cref="DrawCallInfo"/>.
        ///
        /// <param name="drawCall">The draw call information.</param>
        protected override void InvokeDrawCall(ref DrawCallInfo drawCall)
        {
            GraphicsDevice.DrawIndexedPrimitives(drawCall.PrimitiveType, 0, drawCall.StartIndex, drawCall.PrimitiveCount);
        }

        ///
        ///     Draws a sprite using a specified <see cref="Texture" />, transform <see cref="Matrix2D" />, source
        ///     <see cref="Rectangle" />, and an optional
        ///     <see cref="Color" />, origin <see cref="Vector2" />, <see cref="FlipFlags" />, and depth <see cref="float" />.
        ///
        /// <param name="texture">The <see cref="Texture" />.</param>
        /// <param name="transformMatrix">The transform <see cref="Matrix2D" />.</param>
        /// <param name="sourceRectangle">
        ///     The texture region <see cref="Rectangle" /> of the <paramref name="texture" />. Use
        ///     null to use the entire <see cref="Texture2D" />.
        /// </param>
        /// <param name="color">The <see cref="Color" />. Use null to use the default <see cref="Color.White" />.</param>
        /// <param name="flags">The <see cref="FlipFlags" />. The default value is <see cref="FlipFlags.None" />.</param>
        /// <param name="depth">The depth <see cref="float" />. The default value is 0.</param>
        /// <exception cref="InvalidOperationException">The <see cref="Batcher{TDrawCallInfo}.Begin(ref Matrix, ref Matrix, BlendState, SamplerState, DepthStencilState, RasterizerState, Effect)" /> method has not been called.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="texture" /> is null.</exception>
        public void DrawSprite(Texture2D texture, ref Matrix2D transformMatrix, ref Rectangle sourceRectangle,
            Color? color = null, FlipFlags flags = FlipFlags.None, float depth = 0)
        {
            _geometryBuilder.BuildSprite(_vertexCount, ref transformMatrix, texture, ref sourceRectangle, color, flags, depth);
            EnqueueBuiltGeometry(texture, depth);
        }

        ///
        ///     Draws a <see cref="Texture" /> using the specified transform <see cref="Matrix2D" /> and an optional
        ///     <see cref="Color" />, origin <see cref="Vector2" />, <see cref="FlipFlags" />, and depth <see cref="float" />.
        ///
        /// <param name="texture">The <see cref="Texture" />.</param>
        /// <param name="transformMatrix">The transform <see cref="Matrix2D" />.</param>
        /// <param name="color">The <see cref="Color" />. Use null to use the default <see cref="Color.White" />.</param>
        /// <param name="flags">The <see cref="FlipFlags" />. The default value is <see cref="FlipFlags.None" />.</param>
        /// <param name="depth">The depth <see cref="float" />. The default value is 0.</param>
        /// <exception cref="InvalidOperationException">The <see cref="Batcher{TDrawCallInfo}.Begin(ref Matrix, ref Matrix, BlendState, SamplerState, DepthStencilState, RasterizerState, Effect)" /> method has not been called.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="texture" /> is null.</exception>
        public void DrawTexture(Texture2D texture, ref Matrix2D transformMatrix, Color? color = null,
            FlipFlags flags = FlipFlags.None, float depth = 0)
        {
            var rectangle = default(Rectangle);
            _geometryBuilder.BuildSprite(_vertexCount, ref transformMatrix, texture, ref rectangle, color, flags, depth);
            EnqueueBuiltGeometry(texture, depth);
        }

        private void EnqueueBuiltGeometry(Texture2D texture, float depth)
        {
            if ((_vertexCount + _geometryBuilder.VertexCount > _vertices.Length) ||
                (_indexCount + _geometryBuilder.IndexCount > _indices.Length))
                Flush();
            var drawCall = new DrawCallInfo(texture, _geometryBuilder.PrimitiveType, _indexCount,
                _geometryBuilder.PrimitivesCount, depth);
            Array.Copy(_geometryBuilder.Vertices, 0, _vertices, _vertexCount, _geometryBuilder.VertexCount);
            _vertexCount += _geometryBuilder.VertexCount;
            Array.Copy(_geometryBuilder.Indices, 0, _indices, _indexCount, _geometryBuilder.IndexCount);
            _indexCount += _geometryBuilder.IndexCount;
            Enqueue(ref drawCall);
        }

        ///
        ///     Draws unicode (UTF-16) characters as sprites using the specified <see cref="BitmapFont" />, text
        ///     <see cref="StringBuilder" />, transform <see cref="Matrix2D" /> and optional <see cref="Color" />, origin
        ///     <see cref="Vector2" />, <see cref="FlipFlags" />, and depth <see cref="float" />.
        ///
        /// <param name="bitmapFont">The <see cref="BitmapFont" />.</param>
        /// <param name="text">The text <see cref="StringBuilder" />.</param>
        /// <param name="transformMatrix">The transform <see cref="Matrix2D" />.</param>
        /// <param name="color">
        ///     The <see cref="Color" />. Use null to use the default
        ///     <see cref="Color.White" />.
        /// </param>
        /// <param name="flags">The <see cref="FlipFlags" />. The default value is <see cref="FlipFlags.None" />.</param>
        /// <param name="depth">The depth <see cref="float" />. The default value is 0f.</param>
        /// <exception cref="InvalidOperationException">The <see cref="Batcher{TDrawCallInfo}.Begin(ref Matrix, ref Matrix, BlendState, SamplerState, DepthStencilState, RasterizerState, Effect)" /> method has not been called.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="bitmapFont" /> is null or <paramref name="text" /> is null.</exception>
        public void DrawString(BitmapFont bitmapFont, StringBuilder text, ref Matrix2D transformMatrix,
            Color? color = null, FlipFlags flags = FlipFlags.None, float depth = 0f)
        {
            EnsureHasBegun();

            if (bitmapFont == null)
                throw new ArgumentNullException(nameof(bitmapFont));

            if (text == null)
                throw new ArgumentNullException(nameof(text));

            var lineSpacing = bitmapFont.LineHeight;
            var offset = new Vector2(0, 0);

            BitmapFontRegion lastGlyph = null;
            for (var i = 0; i < text.Length;)
            {
                int character;
                if (char.IsLowSurrogate(text[i]))
                {
                    character = char.ConvertToUtf32(text[i - 1], text[i]);
                    i += 2;
                }
                else if (char.IsHighSurrogate(text[i]))
                {
                    character = char.ConvertToUtf32(text[i], text[i - 1]);
                    i += 2;
                }
                else
                {
                    character = text[i];
                    i += 1;
                }

                // ReSharper disable once SwitchStatementMissingSomeCases
                switch (character)
                {
                    case '\r':
                        continue;
                    case '\n':
                        offset.X = 0;
                        offset.Y += lineSpacing;
                        lastGlyph = null;
                        continue;
                }

                var fontRegion = bitmapFont.GetCharacterRegion(character);
                if (fontRegion == null)
                    continue;

                var transform1Matrix = transformMatrix;
                transform1Matrix.M31 += offset.X + fontRegion.XOffset;
                transform1Matrix.M32 += offset.Y + fontRegion.YOffset;

                var textureRegion = fontRegion.TextureRegion;
                var bounds = textureRegion.Bounds;
                DrawSprite(textureRegion.Texture, ref transform1Matrix, ref bounds, color, flags, depth);

                var advance = fontRegion.XAdvance + bitmapFont.LetterSpacing;
                if (BitmapFont.UseKernings && lastGlyph != null)
                {
                    int amount;
                    if (lastGlyph.Kernings.TryGetValue(character, out amount))
                    {
                        advance += amount;
                    }
                }

                offset.X += i != text.Length - 1
                    ? advance
                    : fontRegion.XOffset + fontRegion.Width;

                lastGlyph = fontRegion;
            }
        }

        ///
        ///     Draws unicode (UTF-16) characters as sprites using the specified <see cref="BitmapFont" />, text
        ///     <see cref="StringBuilder" />, position <see cref="Vector2" /> and optional <see cref="Color" />, rotation
        ///     <see cref="float" />, origin <see cref="Vector2" />, scale <see cref="Vector2" /> <see cref="FlipFlags" />, and
        ///     depth <see cref="float" />.
        ///
        /// <param name="bitmapFont">The <see cref="BitmapFont" />.</param>
        /// <param name="text">The text <see cref="string" />.</param>
        /// <param name="position">The position <see cref="Vector2" />.</param>
        /// <param name="color">
        ///     The <see cref="Color" />. Use null to use the default
        ///     <see cref="Color.White" />.
        /// </param>
        /// <param name="rotation">
        ///     The angle <see cref="float" /> (in radians) to rotate each sprite about its <paramref name="origin" />. The default
        ///     value is 0f.
        /// </param>
        /// <param name="origin">
        ///     The origin <see cref="Vector2" />. Use null to use the default
        ///     <see cref="Vector2.Zero" />.
        /// </param>
        /// <param name="scale">
        ///     The scale <see cref="Vector2" />. Use null to use the default
        ///     <see cref="Vector2.One" />.
        /// </param>
        /// <param name="flags">The <see cref="FlipFlags" />. The default value is <see cref="FlipFlags.None" />.</param>
        /// <param name="depth">The depth <see cref="float" />. The default value is 0f</param>
        /// <exception cref="InvalidOperationException">The <see cref="Batcher{TDrawCallInfo}.Begin(ref Matrix, ref Matrix, BlendState, SamplerState, DepthStencilState, RasterizerState, Effect)" /> method has not been called.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="bitmapFont" /> is null or <paramref name="text" /> is null.</exception>
        public void DrawString(BitmapFont bitmapFont, StringBuilder text, Vector2 position, Color? color = null,
            float rotation = 0f, Vector2? origin = null, Vector2? scale = null,
            FlipFlags flags = FlipFlags.None, float depth = 0f)
        {
            Matrix2D transformMatrix;
            Matrix2D.CreateFrom(position, rotation, scale, origin, out transformMatrix);
            DrawString(bitmapFont, text, ref transformMatrix, color, flags, depth);
        }

        ///
        ///     Draws unicode (UTF-16) characters as sprites using the specified <see cref="BitmapFont" />, text
        ///     <see cref="string" />, transform <see cref="Matrix2D" /> and optional <see cref="Color" />, origin
        ///     <see cref="Vector2" />, <see cref="FlipFlags" />, and depth <see cref="float" />.
        ///
        /// <param name="bitmapFont">The <see cref="BitmapFont" />.</param>
        /// <param name="text">The text <see cref="string" />.</param>
        /// <param name="transformMatrix">The transform <see cref="Matrix2D" />.</param>
        /// <param name="color">
        ///     The <see cref="Color" />. Use null to use the default
        ///     <see cref="Color.White" />.
        /// </param>
        /// <param name="flags">The <see cref="FlipFlags" />. The default value is <see cref="FlipFlags.None" />.</param>
        /// <param name="depth">The depth <see cref="float" />. The default value is 0f</param>
        /// <exception cref="InvalidOperationException">The <see cref="Batcher{TDrawCallInfo}.Begin(ref Matrix, ref Matrix, BlendState, SamplerState, DepthStencilState, RasterizerState, Effect)" /> method has not been called.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="bitmapFont" /> is null or <paramref name="text" /> is null.</exception>
        public void DrawString(BitmapFont bitmapFont, string text, ref Matrix2D transformMatrix, Color? color = null,
            FlipFlags flags = FlipFlags.None, float depth = 0f)
        {
            EnsureHasBegun();

            if (bitmapFont == null)
                throw new ArgumentNullException(nameof(bitmapFont));

            if (text == null)
                throw new ArgumentNullException(nameof(text));

            var glyphs = bitmapFont.GetGlyphs(text);
            foreach (var glyph in glyphs)
            {
                var transform1Matrix = transformMatrix;
                transform1Matrix.M31 += glyph.Position.X;
                transform1Matrix.M32 += glyph.Position.Y;

                var texture = glyph.FontRegion.TextureRegion.Texture;
                var bounds = texture.Bounds;
                DrawSprite(texture, ref transform1Matrix, ref bounds, color, flags, depth);
            }
        }

        ///
        ///     Draws unicode (UTF-16) characters as sprites using the specified <see cref="BitmapFont" />, text
        ///     <see cref="string" />, position <see cref="Vector2" /> and optional <see cref="Color" />, rotation
        ///     <see cref="float" />, origin <see cref="Vector2" />, scale <see cref="Vector2" /> <see cref="FlipFlags" />, and
        ///     depth <see cref="float" />.
        ///
        /// <param name="bitmapFont">The <see cref="BitmapFont" />.</param>
        /// <param name="text">The text <see cref="string" />.</param>
        /// <param name="position">The position <see cref="Vector2" />.</param>
        /// <param name="color">
        ///     The <see cref="Color" />. Use null to use the default
        ///     <see cref="Color.White" />.
        /// </param>
        /// <param name="rotation">
        ///     The angle <see cref="float" /> (in radians) to rotate each sprite about its <paramref name="origin" />. The default
        ///     value is 0f.
        /// </param>
        /// <param name="origin">
        ///     The origin <see cref="Vector2" />. Use null to use the default
        ///     <see cref="Vector2.Zero" />.
        /// </param>
        /// <param name="scale">
        ///     The scale <see cref="Vector2" />. Use null to use the default
        ///     <see cref="Vector2.One" />.
        /// </param>
        /// <param name="flags">The <see cref="FlipFlags" />. The default value is <see cref="FlipFlags.None" />.</param>
        /// <param name="depth">The depth <see cref="float" />. The default value is 0f</param>
        /// <exception cref="InvalidOperationException">The <see cref="Batcher{TDrawCallInfo}.Begin(ref Matrix, ref Matrix, BlendState, SamplerState, DepthStencilState, RasterizerState, Effect)" /> method has not been called.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="bitmapFont" /> is null or <paramref name="text" /> is null.</exception>
        public void DrawString(BitmapFont bitmapFont, string text, Vector2 position, Color? color = null,
            float rotation = 0f, Vector2? origin = null, Vector2? scale = null,
            FlipFlags flags = FlipFlags.None, float depth = 0f)
        {
            Matrix2D matrix;
            Matrix2D.CreateFrom(position, rotation, scale, origin, out matrix);
            DrawString(bitmapFont, text, ref matrix, color, flags, depth);
        }

        [StructLayout(LayoutKind.Sequential, Pack = 1)]
        [EditorBrowsable(EditorBrowsableState.Never)]
        public struct DrawCallInfo : IBatchDrawCallInfo<DrawCallInfo>, IComparable<DrawCallInfo>
        {
            internal readonly PrimitiveType PrimitiveType;
            internal int StartIndex;
            internal int PrimitiveCount;
            internal readonly Texture2D Texture;
            internal readonly uint TextureKey;
            internal readonly uint DepthKey;

            internal unsafe DrawCallInfo(Texture2D texture, PrimitiveType primitiveType, int startIndex, int primitiveCount, float depth)
            {
                PrimitiveType = primitiveType;
                StartIndex = startIndex;
                PrimitiveCount = primitiveCount;
                Texture = texture;
                TextureKey = (uint)RuntimeHelpers.GetHashCode(texture);
                DepthKey = *(uint*)&depth;
            }

            public void SetState(Effect effect)
            {
                var textureEffect = effect as ITextureEffect;
                if (textureEffect != null)
                    textureEffect.Texture = Texture;
            }

            public bool TryMerge(ref DrawCallInfo drawCall)
            {
                if (PrimitiveType != drawCall.PrimitiveType || TextureKey != drawCall.TextureKey ||
                    DepthKey != drawCall.DepthKey)
                    return false;
                drawCall.PrimitiveCount += PrimitiveCount;
                return true;
            }

            [SuppressMessage("ReSharper", "ImpureMethodCallOnReadonlyValueField")]
            public int CompareTo(DrawCallInfo other)
            {
                var result = TextureKey.CompareTo(other.TextureKey);;
                if (result != 0)
                    return result;
                result = DepthKey.CompareTo(other.DepthKey);
                return result != 0 ? result : ((byte)PrimitiveType).CompareTo((byte)other.PrimitiveType);
            }
        }
    }
}


text:
const mongoose = require('mongoose'),
  Schema = mongoose.Schema;

const ArticleSchema = new Schema({
  _id: String,
  title: String,
  summary: String,
  descripton: String,
  pubdate: String,
  link: String,
  contentText: String,
  mediaImageURL: String,
  creditPercentage: { type: Number, defulat: 0 },
  totalNumberViews: { type: Number, defulat: 0 },
  totalNumberVotes: { type: Number, defulat: 0 },
  totalNumberSensationalVotes: { type: Number, defulat: 0 },
  totalNumberFactualVotes: { type: Number, defulat: 0 }
},
  {
    timestamps: true // Saves createdAt and updatedAt as dates. createdAt will be our timestamp.
  });

module.exports = mongoose.model('Article', ArticleSchema);


text:
#ifndef PTHREAD_H
#define PTHREAD_H

#include <stdlib.h>
#include <netbas/jthread.h>

/* CHECK */
typedef tid_t pthread_t;

struct pthread_mutex
{
	volatile long int _lock;
};

typedef struct pthread_mutex pthread_mutex_t;

typedef int pthread_mutexattr_t;
typedef int pthread_attr_t;
typedef unsigned int pthread_key_t;
typedef volatile unsigned int pthread_cond_t;

typedef unsigned int pthread_condattr_t;

#define PTHREAD_MUTEX_INITIALIZER	{0}
#define PTHREAD_MUTEX_RECURSIVE		{2}

#define PTHREAD_CREATE_JOINABLE		0x1
#define PTHREAD_CREATE_DETACHED		0x2

#define PTHREAD_COND_INITIALIZER	0x1

#define PTHREAD_COND_SIGNALLED		0x2

#define PTHREAD_STACK_MIN	8192

#define PTHREAD_SCOPE_SYSTEM	0x00000001

/* Functions */

int pthread_mutex_lock(pthread_mutex_t* mutex);
int pthread_mutex_trylock(pthread_mutex_t* mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);
void pthread_cleanup_push(void (*routine)(void*),void* arg);
void pthread_cleanup_pop(int execute);
int pthread_cond_signal(pthread_cond_t* cond);
int pthread_cond_broadcast(pthread_cond_t* cond);
int pthread_cond_wait(pthread_cond_t* cond,pthread_mutex_t* mutex);

/* Attributes */
int pthread_attr_init(pthread_attr_t* attr);
int pthread_attr_destroy(pthread_attr_t* attr);
int pthread_attr_setscope(pthread_attr_t* attr, int scope);
int pthread_attr_getstack(const pthread_attr_t* attr,void** stackAddr,size_t* stackSize);
int pthread_create(pthread_t *thread,const pthread_attr_t* attr,void* (*startRoutine)(void*),void* args);
#endif


text:
from ..hello import xx

print('bye was imported')


text:
import logging
from followthemoney import model
from ftmstore import get_dataset
from servicelayer.worker import Worker
from servicelayer.logs import apply_task_context

from ingestors import __version__
from ingestors.manager import Manager
from ingestors.analysis import Analyzer

log = logging.getLogger(__name__)
OP_INGEST = "ingest"
OP_ANALYZE = "analyze"

class IngestWorker(Worker):
    """A long running task runner that uses Redis as a task queue"""

    def _ingest(self, dataset, task):
        manager = Manager(dataset, task.stage, task.context)
        entity = model.get_proxy(task.payload)
        log.debug("Ingest: %r", entity)
        try:
            manager.ingest_entity(entity)
        finally:
            manager.close()
        return manager.emitted

    def _analyze(self, dataset, task):
        entity_ids = set(task.payload.get("entity_ids"))
        analyzer = None
        for entity in dataset.partials(entity_id=entity_ids):
            if analyzer is None or analyzer.entity.id != entity.id:
                if analyzer is not None:
                    entity_ids.update(analyzer.flush())
                # log.debug("Analyze: %r", entity)
                analyzer = Analyzer(dataset, entity, task.context)
            analyzer.feed(entity)
        if analyzer is not None:
            entity_ids.update(analyzer.flush())
        return list(entity_ids)

    def handle(self, task):
        apply_task_context(task, version=__version__)
        name = task.context.get("ftmstore", task.job.dataset.name)
        dataset = get_dataset(name, task.stage.stage)
        if task.stage.stage == OP_INGEST:
            entity_ids = self._ingest(dataset, task)
            payload = {"entity_ids": entity_ids}
            self.dispatch_pipeline(task, payload)
        elif task.stage.stage == OP_ANALYZE:
            entity_ids = self._analyze(dataset, task)
            payload = {"entity_ids": entity_ids}
            self.dispatch_pipeline(task, payload)


text:
/*
 * Initialize the graphic.
 */
var pymChild = null;
// Trackers container object
var trackers = {};

var onWindowLoaded = function() {
    pymChild = new pym.Child();
    var tracker = new PymChildScrollVisibility.Tracker('tracker-test-1', onVisible);
    trackers['tracker-test-1'] = tracker;
    tracker = new PymChildScrollVisibility.Tracker('tracker-test-2', onVisible);
    trackers['tracker-test-2'] = tracker;
    pymChild.onMessage('viewport-iframe-position', function(parentInfo) {
        for (var tracker in trackers) {
            if (trackers.hasOwnProperty(tracker)) {
                trackers[tracker].checkIfVisible(parentInfo, true);
            }
        }
    });
}

var onVisible = function(id) {
    console.log(id, 'visible');
    var el = document.getElementById(id);
    // Toggle class
    if (el.classList.contains('visible')) {
        el.classList.remove('visible');
    }
    else {
        el.classList.add('visible');
    }
    var tracker = trackers[id];
}

/*
 * Initially load the graphic
 * (NB: Use window.load to ensure all images have loaded)
 */
window.onload = onWindowLoaded;


text:
'use strict';

const updateUrl = require('../../lib/url-updater').updateUrl;

describe('url-updater', () => {
    const sandbox = sinon.sandbox.create();

    const sourceUrl = '/?text=text';

    afterEach(() => sandbox.restore());

    it('should add new parameters if they do not exist in url', () => {
        const query = [
            {name: 'foo', value: 'bar'},
            {name: 'baz', value: 'boo'}
        ];

        assert.equal(updateUrl(sourceUrl, query), '/?text=text&foo=bar&baz=boo');
    });

    describe('should concat parameters', () => {
        it('by default', () => {
            const result = updateUrl(sourceUrl, [{name: 'text', value: 'foo'}]);

            assert.equal(result, '/?text=text&text=foo');
        });

        it('if mode is "concat"', () => {
            const result = updateUrl(sourceUrl, [{name: 'text', value: 'foo', mode: 'concat'}]);

            assert.equal(result, '/?text=text&text=foo');
        });

        it('specified as number', () => {
            const result = updateUrl(sourceUrl, [{name: 'text', value: 15}]);

            assert.equal(result, '/?text=text&text=15');
        });

        it('from array of values', () => {
            const result = updateUrl(sourceUrl, [{name: 'text', value: ['foo', 'bar']}]);

            assert.equal(result, '/?text=text&text=foo&text=bar');
        });
    });

    it('should extend url only with uniq parameters', () => {
        const query = [
            {name: 'text', value: 'foo'},
            {name: 'text', value: 'foo'}
        ];
        const result = updateUrl(sourceUrl, query);

        assert.equal(result, '/?text=text&text=foo');
    });

    it('should override parameters if parameter mode is "override"', () => {
        const query = [{name: 'text', value: 'foo', mode: 'override'}];

        assert.equal(updateUrl(sourceUrl, query), '/?text=foo');
    });

    describe('should not add url parameters', () => {
        it('if they are specified as an empty object', () => {
            assert.equal(updateUrl(sourceUrl, [{name: 'text', value: {}}]), sourceUrl);
        });

        it('if they are specified as an object without "value" field', () => {
            assert.equal(updateUrl(sourceUrl, [{name: 'text'}]), sourceUrl);
        });

        it('if they are specified as an empty string', () => {
            assert.equal(updateUrl(sourceUrl, [{name: 'name', value: ''}]), sourceUrl);
        });

        it('if they are specified as an empty array', () => {
            assert.equal(updateUrl(sourceUrl, [{name: 'name', value: []}]), sourceUrl);
        });
    });
});


text:
package at.loup.filemanager.entities;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Lob;
import javax.persistence.Table;

import at.loup.commons.entities.AbstractEntityWithDefaultGenerator;
import at.loup.commons.utilities.ArgumentRuleUtilities;

@Entity
@Table(name = "binaries")
public class BinaryEntity extends AbstractEntityWithDefaultGenerator<BinaryEntity> {
	private static final long serialVersionUID = 4808540737164882902L;

	@Lob()
	@Column(length = 10000000, nullable = false)
	@Basic(fetch = FetchType.EAGER, optional = false)
	private byte[] data;

	// unique = false because different users might need control
	// of a different data element
	@Lob()
	@Column(length = 256, nullable = false, unique = false)
	@Basic(fetch = FetchType.LAZY, optional = false)
	private byte[] collisionHash;

	@Column(nullable = false)
	private Integer size;

	@Column(length = 12, nullable = false)
	private String uploaderIp;

	protected BinaryEntity() {

	}

	public byte[] getData() {
		return data;
	}

	public void setData(byte[] data) {
		ArgumentRuleUtilities.notNull("data", data);
		this.data = data;
		byte[] collisionHash = createCollisionHash(data);
		setCollisionHash(collisionHash);
		setSize(data.length);
	}

	public byte[] getCollisionHash() {
		return collisionHash;
	}

	public boolean checkCollisionHash(byte[] givenHash) {
		ArgumentRuleUtilities.notNull("givenHash", givenHash);
		boolean result = Arrays.equals(givenHash, getCollisionHash());
		return result;
	}

	public boolean checkCollisionHash(BinaryEntity otherEntity) {
		byte[] otherEntitiesCollisionHash = otherEntity.getCollisionHash();
		boolean result = checkCollisionHash(otherEntitiesCollisionHash);
		return result;
	}

	protected void setCollisionHash(byte[] collisionHash) {
		this.collisionHash = collisionHash;
	}

	public Integer getSize() {
		return size;
	}

	protected void setSize(Integer size) {
		this.size = size;
	}

	public String getUploaderIp() {
		return uploaderIp;
	}

	public void setUploaderIp(String uploaderIp) {
		this.uploaderIp = uploaderIp;
	}

	public static BinaryEntity create(byte[] data, String uploaderIp) {
		ArgumentRuleUtilities.notNull("data", data);
		BinaryEntity result = new BinaryEntity();
		result.setData(data);
		result.setUploaderIp(uploaderIp);
		return result;
	}

	public static byte[] createCollisionHash(byte[] input) {
		ArgumentRuleUtilities.notNull("input", input);
		MessageDigest messageDigestMD5;
		MessageDigest messageDigestMD2;
		try {
			messageDigestMD5 = MessageDigest.getInstance("MD5");
			messageDigestMD2 = MessageDigest.getInstance("MD2");
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		}
		// MD5 & MD2 hashes are each 128 bit long
		byte[] md5Hash = messageDigestMD5.digest(input);
		byte[] md2Hash = messageDigestMD2.digest(input);
		byte[] result = new byte[32];

		System.arraycopy(md5Hash, 0, result, 0, 16);
		System.arraycopy(md2Hash, 0, result, 16, 16);
		return result;
	}
}


text:
using Foundation;
using System;
using System.CodeDom.Compiler;
using UIKit;

namespace Localization.WatchAppExtension
{
    [Register ("InterfaceController")]
    partial class InterfaceController
    {
        [Outlet]
        [GeneratedCode ("iOS Designer", "1.0")]
        WatchKit.WKInterfaceButton HelloButton { get; set; }

        [Outlet]
        [GeneratedCode ("iOS Designer", "1.0")]
        WatchKit.WKInterfaceLabel Subheading { get; set; }

        [Outlet]
        [GeneratedCode ("iOS Designer", "1.0")]
        WatchKit.WKInterfaceImage WelcomeImage { get; set; }

        [Outlet]
        [GeneratedCode ("iOS Designer", "1.0")]
        WatchKit.WKInterfaceLabel WelcomeLabel { get; set; }

        void ReleaseDesignerOutlets ()
        {
            if (HelloButton != null) {
                HelloButton.Dispose ();
                HelloButton = null;
            }

            if (Subheading != null) {
                Subheading.Dispose ();
                Subheading = null;
            }

            if (WelcomeImage != null) {
                WelcomeImage.Dispose ();
                WelcomeImage = null;
            }

            if (WelcomeLabel != null) {
                WelcomeLabel.Dispose ();
                WelcomeLabel = null;
            }
        }
    }
}


text:
package com.microsoft.azure.management.devtestlabs.v2018_09_15;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * Properties for generating an upload URI.
 */
public class GenerateUploadUriParameter {
    /**
     * The blob name of the upload URI.
     */
    @JsonProperty(value = "blobName")
    private String blobName;

    /**
     * Get the blob name of the upload URI.
     *
     * @return the blobName value
     */
    public String blobName() {
        return this.blobName;
    }

    /**
     * Set the blob name of the upload URI.
     *
     * @param blobName the blobName value to set
     * @return the GenerateUploadUriParameter object itself.
     */
    public GenerateUploadUriParameter withBlobName(String blobName) {
        this.blobName = blobName;
        return this;
    }

}


text:
package com.flash3388.flashlib.scheduling.actions;

import com.flash3388.flashlib.global.GlobalDependencies;
import com.flash3388.flashlib.time.Clock;
import org.slf4j.Logger;

import java.util.ArrayList;
import java.util.Collection;
import java.util.function.Predicate;

public class ParallelRaceActionGroup extends ActionGroupBase {

    private final Clock mClock;
    private final Logger mLogger;

    private final Collection<ActionContext> mCurrentActions;
    private final Predicate<ActionContext> mContextRunner;

    private ActionContext mFinishedCommand;

    ParallelRaceActionGroup(Clock clock, Logger logger, Collection<Action> actions, Collection<ActionContext> currentActions) {
        super(actions, false);

        mClock = clock;
        mLogger = logger;
        mCurrentActions = currentActions;

        mContextRunner = (actionContext)-> {
            if (!actionContext.run()) {
                actionContext.runFinished();
                mLogger.debug("ActionGroup {} finished action {}", ParallelRaceActionGroup.this, actionContext);

                return true;
            }

            return false;
        };
        mRunWhenDisabled = false;
        mFinishedCommand = null;
    }

    public ParallelRaceActionGroup(Clock clock, Logger logger) {
        this(clock, logger, new ArrayList<>(3), new ArrayList<>(2));
    }

    public ParallelRaceActionGroup() {
        this(GlobalDependencies.getClock(), GlobalDependencies.getLogger());
    }

    @Override
    public ParallelRaceActionGroup add(Action action) {
        super.add(action);
        return this;
    }

    @Override
    public ParallelRaceActionGroup add(Action... actions) {
        super.add(actions);
        return this;
    }

    @Override
    public ParallelRaceActionGroup add(Collection<Action> actions) {
        super.add(actions);
        return this;
    }

    @Override
    public ParallelRaceActionGroup raceWith(Action... actions) {
        return add(actions);
    }

    @Override
    public final void initialize() {
        for (Action action : mActions) {
            ActionContext actionContext = new ActionContext(action, mClock);
            actionContext.prepareForRun();
            mLogger.debug("ActionGroup {} started action {}", this, actionContext);

            mCurrentActions.add(actionContext);
        }

        mFinishedCommand = null;
    }

    @Override
    public final void execute() {
        if (mCurrentActions.isEmpty()) {
            return;
        }

        for (ActionContext context : mCurrentActions) {
            if (!mContextRunner.test(context)) {
                mFinishedCommand = context;
                break;
            }
        }
    }

    @Override
    public boolean isFinished() {
        return mFinishedCommand != null;
    }

    @Override
    public void end(boolean wasInterrupted) {
        for (ActionContext context : mCurrentActions) {
            if (wasInterrupted || !context.equals(mFinishedCommand)) {
                mLogger.debug("ActionGroup {} interrupted, canceling action {}", this, context);
                context.runCanceled();
            }
        }

        if (!wasInterrupted && mFinishedCommand != null) {
            mFinishedCommand.runFinished();
            mLogger.debug("ActionGroup {} finished action {}", this, mFinishedCommand);
        }
    }
}


text:
package jp.co.ntt.oss.mapper.stub;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.sql.Clob;
import java.sql.NClob;
import java.sql.SQLException;

public class NclobStub implements NClob {

	@Override
	public void free() throws SQLException {
		// TODO 自動生成されたメソッド・スタブ

	}

	@Override
	public InputStream getAsciiStream() throws SQLException {
		// TODO 自動生成されたメソッド・スタブ
		return null;
	}

	@Override
	public Reader getCharacterStream() throws SQLException {
		// TODO 自動生成されたメソッド・スタブ
		return null;
	}

	@Override
	public Reader getCharacterStream(long pos, long length) throws SQLException {
		// TODO 自動生成されたメソッド・スタブ
		return null;
	}

	@Override
	public String getSubString(long pos, int length) throws SQLException {
		// TODO 自動生成されたメソッド・スタブ
		return null;
	}

	@Override
	public long length() throws SQLException {
		// TODO 自動生成されたメソッド・スタブ
		return 0;
	}

	@Override
	public long position(String searchstr, long start) throws SQLException {
		// TODO 自動生成されたメソッド・スタブ
		return 0;
	}

	@Override
	public long position(Clob searchstr, long start) throws SQLException {
		// TODO 自動生成されたメソッド・スタブ
		return 0;
	}

	@Override
	public OutputStream setAsciiStream(long pos) throws SQLException {
		// TODO 自動生成されたメソッド・スタブ
		return null;
	}

	@Override
	public Writer setCharacterStream(long pos) throws SQLException {
		// TODO 自動生成されたメソッド・スタブ
		return null;
	}

	@Override
	public int setString(long pos, String str) throws SQLException {
		// TODO 自動生成されたメソッド・スタブ
		return 0;
	}

	@Override
	public int setString(long pos, String str, int offset, int len)
			throws SQLException {
		// TODO 自動生成されたメソッド・スタブ
		return 0;
	}

	@Override
	public void truncate(long len) throws SQLException {
		// TODO 自動生成されたメソッド・スタブ

	}

}


text:
#ifndef PULSE_MOVE_H
#define PULSE_MOVE_H

#include "square.h"
#include "piece.h"
#include "piecetype.h"
#include "movetype.h"

namespace pulse {

/**
 * This class represents a move as a int value. The fields are represented by
 * the following bits.
 *

 *  0 -  2: type (required)
 *  3 -  9: origin square (required)
 * 10 - 16: target square (required)
 * 17 - 21: origin piece (required)
 * 22 - 26: target piece (optional)
 * 27 - 29: promotion type (optional)
 */
class Move {
private:
  // These are our bit masks
  static const int TYPE_SHIFT = 0;
  static const int TYPE_MASK = MoveType::MASK << TYPE_SHIFT;
  static const int ORIGIN_SQUARE_SHIFT = 3;
  static const int ORIGIN_SQUARE_MASK = Square::MASK << ORIGIN_SQUARE_SHIFT;
  static const int TARGET_SQUARE_SHIFT = 10;
  static const int TARGET_SQUARE_MASK = Square::MASK << TARGET_SQUARE_SHIFT;
  static const int ORIGIN_PIECE_SHIFT = 17;
  static const int ORIGIN_PIECE_MASK = Piece::MASK << ORIGIN_PIECE_SHIFT;
  static const int TARGET_PIECE_SHIFT = 22;
  static const int TARGET_PIECE_MASK = Piece::MASK << TARGET_PIECE_SHIFT;
  static const int PROMOTION_SHIFT = 27;
  static const int PROMOTION_MASK = PieceType::MASK << PROMOTION_SHIFT;

public:
  // We don't use 0 as a null value to protect against errors.
  static const int NOMOVE = (MoveType::NOMOVETYPE << TYPE_SHIFT)
      | (Square::NOSQUARE << ORIGIN_SQUARE_SHIFT)
      | (Square::NOSQUARE << TARGET_SQUARE_SHIFT)
      | (Piece::NOPIECE << ORIGIN_PIECE_SHIFT)
      | (Piece::NOPIECE << TARGET_PIECE_SHIFT)
      | (PieceType::NOPIECETYPE << PROMOTION_SHIFT);

  static int valueOf(int type, int originSquare, int targetSquare, int originPiece, int targetPiece, int promotion);
  static int getType(int move);
  static int getOriginSquare(int move);
  static int getTargetSquare(int move);
  static int getOriginPiece(int move);
  static int getTargetPiece(int move);
  static int getPromotion(int move);

private:
  Move();
  ~Move();
};

}

#endif


text:
<?php

/**
 * Spiral Framework.
 *
 * @license   MIT
 * @author    Anton Titov (Wolfy-J)
 */

declare(strict_types=1);

namespace Spiral\Stempler;

use Spiral\Stempler\Node\NodeInterface;

/**
 * Visitor context contains current node branch with all the previous nodes.
 */
final class VisitorContext
{
    /** @var NodeInterface[] */
    private $scope = [];

    /**
     * @param NodeInterface $node
     * @return VisitorContext
     */
    public function withNode(NodeInterface $node): self
    {
        $context = clone $this;
        $context->scope[] = $node;

        return $context;
    }

    /**
     * @return array
     */
    public function getScope(): array
    {
        return $this->scope;
    }

    /**
     * @return NodeInterface|null
     */
    public function getCurrentNode(): ?NodeInterface
    {
        return $this->scope[count($this->scope) - 1] ?? null;
    }

    /**
     * @return NodeInterface|null
     */
    public function getParentNode(): ?NodeInterface
    {
        return $this->scope[count($this->scope) - 2] ?? null;
    }

    /**
     * @return NodeInterface|null
     */
    public function getFirstNode(): ?NodeInterface
    {
        return $this->scope[0] ?? null;
    }
}


text:
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.junit.Ignore;
import org.junit.Test;

public class TestScripts {

	@Test
	@Ignore
	public void TestScripts() {
		File dir = new File("/Users/joahaa/Projects/eurekaj/EurekaJ.View/src/main/webapp/js/app");
		List<String> toplevelFileList = new ArrayList<String>();
		List<String> recursiveFileList = new ArrayList<String>();
		for (File currFile : dir.listFiles()) {
			if (currFile.isDirectory()) {
				work(currFile, recursiveFileList);
			} else {
				toplevelFileList.add(currFile.getAbsolutePath().substring(59));
			}
		}

		for (String filename : toplevelFileList) {
			System.out.println("<script type=\"text/javascript\" charset=\"utf-8\" src=\"" + filename + "\"></script>");
		}

		for (String filename : recursiveFileList) {
			System.out.println("<script type=\"text/javascript\" charset=\"utf-8\" src=\"" + filename + "\"></script>");
		}
	}

	private void work(File file, List<String> recursiveFileList) {
		for (File currFile : file.listFiles()) {
			if (currFile.isDirectory()) {
				work(currFile, recursiveFileList);
			} else {
				recursiveFileList.add(currFile.getAbsolutePath().substring(59));
			}
		}
	}
}


text:
package org.xmlcml.ami2.dictionary;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.xmlcml.ami2.wordutil.PorterStemmer;

public class TermPhrase implements Comparable<TermPhrase> {

	private static final Logger LOG = Logger.getLogger(TermPhrase.class);
	static {
		LOG.setLevel(Level.DEBUG);
	}

	private List<String> wordList;

	public static TermPhrase createTermPhrase(List<String> wordList) {
		if (wordList == null) return null;
		return new TermPhrase(wordList);
	}

	private TermPhrase(List<String> wordList) {
		this.wordList = new ArrayList<String>(wordList);
	}

	public static TermPhrase createTermPhrase(String word) {
		if (word == null) return null;
		return new TermPhrase(word);
	}

	private TermPhrase(String phrase) {
		wordList = Arrays.asList(phrase.trim().split("\\s+"));
		this.wordList = new ArrayList<String>(wordList);
	}

	public List<String> getWords() {
		return wordList;
	}

	public String getString() {
		return wordList == null ? null : StringUtils.join(wordList, " ");
	}

	public void applyPorterStemming() {
		PorterStemmer porterStemmer = new PorterStemmer();
		List<String> newWordList = new ArrayList<String>();
		for (String word : wordList) {
			newWordList.add(porterStemmer.stem(word));
		}
		wordList = newWordList;
	}

	public static void applyPorterStemming(List<TermPhrase> phraseList) {
		for (TermPhrase phrase : phraseList) {
			phrase.applyPorterStemming();
		}
	}

	public void toLowerCase() {
		List<String> newWordList = new ArrayList<String>();
		for (String word : wordList) {
			newWordList.add(word.toLowerCase());
		}
		wordList = newWordList;
	}

	public String toString() {
		return wordList.toString();
	}

	/** sorts by length and then alphabetically.
	 *
	 * @param termPhrase
	 * @return
	 */
	public int compareTo(TermPhrase termPhrase) {
		int result = 0;

		int sizeDiff = wordList.size() -  termPhrase.wordList.size();
		if (sizeDiff != 0) {
			return sizeDiff;
		}
		for (int i = 0; i < wordList.size(); i++) {
			int wordDiff = wordList.get(i).compareTo(termPhrase.wordList.get(i));
			if (wordDiff != 0) {
				return wordDiff;
			}
		}
		return 0;
	}

	public List<String> getWordList() {
		return wordList;
	}

}


text:
#region Copyright
// Copyright 2014 Myrcon Pty. Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections.Generic;

namespace Potato.Net.Shared.Models {
    /// <summary>
    /// Model describing a banned player
    /// </summary>
    [Serializable]
    public sealed class BanModel : NetworkModel {
        /// <summary>
        /// Initializes the underlying networkmodel with the required collections.
        /// </summary>
        public BanModel() : base() {
            this.Scope.Content = new List<String>();
            this.Scope.Players = new List<PlayerModel>();
            this.Scope.Times = new List<TimeSubsetModel>();
        }
    }
}


text:
from unittest import TestCase
from django.core.management.base import NoArgsCommand
from django.utils import unittest
from core.realtime.activity import post_activity
from spa.models.userprofile import UserProfile
from spa.models.activity import ActivityDownload
from spa.models.mix import Mix

class Command(NoArgsCommand):
    help = """
    If you need Arguments, please check other modules in
    django/core/management/commands.
    """

    def handle_noargs(self, **options):
        suite = unittest.TestLoader().loadTestsFromTestCase(TestRealtime)
        unittest.TextTestRunner().run(suite)

class TestRealtime(TestCase):
    def test_post_activity(self):
        try:
            mix = Mix.objects.order_by('?')[0]
            user = UserProfile.objects.get(slug='fergalmoran')
            activity = ActivityDownload(user=user, mix=mix)
            activity.save()

            """
                Try to find an active session for this user
                If it exists, post to the realtime controller
            """
            sessions = user.user.session_set.all()
            for session in sessions:
                result = post_activity(session.session_key, activity.get_activity_url())

            self.assertTrue(result == "", msg=result)

        except Exception, ex:
            print "Error: test_post_activity: %s" % ex.message


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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/label"
        android:layout_marginTop="10px"
        android:layout_marginBottom="10px"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Movie text"
        android:textSize="50px" />

</LinearLayout>


text:
package de.donotconnect.notary_cache.operator;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

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

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;

import de.donotconnect.notary_cache.operator.CacheImpl.InMemoryCache;
import de.donotconnect.notary_cache.operator.CacheStrategyImpl.ExampleCachingStrategy;
import de.donotconnect.notary_cache.operator.Interfaces.ICache;
import de.donotconnect.notary_cache.operator.Interfaces.ICacheStrategy;
import de.donotconnect.notary_cache.operator.Interfaces.IListener;
import de.donotconnect.notary_cache.operator.NotaryImpl.DefaultNotary;

/**
 * Main class for the operator.
 *
 * @author fabianletzkus
 *
 */
public class OperatorMain extends AbstractHandler implements IListener {

	public static final int _NOTARY_CACHE_VERSION_ = 1;

	public static void main(String[] args) {
		OperatorMain op = new OperatorMain();
		op.startOperator();
	}

	private final static Logger log = LogManager.getLogger("OperatorMain");
	private HwMonitor hwmon;
	private int hwmonPolling = 10000;
	private EventMgr evntMgr;
	private Server server;
	private ICacheStrategy cachingStrategy;
	private ICache cache;
	private DefaultNotary notary;

	public OperatorMain() {
		/**
		 * Initialize Modules
		 */
		this.evntMgr = EventMgr.getInstance();
		this.hwmon = new HwMonitor(this.hwmonPolling);
		this.server = new Server(this);

		/**
		 * Initialize Cache Elements
		 */
		this.cache = new InMemoryCache();
		this.cachingStrategy = new ExampleCachingStrategy();
		this.notary = new DefaultNotary();

		/**
		 * Register potential events
		 */
		this.evntMgr.registerEventListener("quit", this);
		this.evntMgr.registerEventListener("hwmon-notify", this);
	}

	/**
	 * Start the operator and its connected modules.
	 */
	public void startOperator() {
		this.hwmon.start();
		this.server.start();
		this.evntMgr.interactive();
		this.cachingStrategy.manage(this.cache);
	}

	/**
	 * Stops the operator.
	 */
	public void stopOperator() {
		server.stop();
	}

	/**
	 * If someone puts "quit" in the console...
	 */
	public void doAction(String evnt) {

		log.debug("Received Event: " + evnt);

		if (evnt.startsWith("quit")) {
			this.stopOperator();
		}
		if (evnt.startsWith("hwmon-notify")) {
			manageHwmonPolling(evnt);
		}
	}

	private void manageHwmonPolling(String evnt) {
		String[] attrs = evnt.split(" ");
		for (String attr : attrs) {
			if (attr.startsWith("load=")) {
				String[] load = attr.split("=")[1].split(",");
				if (Double.valueOf(load[0]) < Double.valueOf(load[1])) {
					if (Double.valueOf(load[1]) < Double.valueOf(load[2])) {
						// load is going down for 15min -> poll more often
						if (this.hwmonPolling - 2000 > this.hwmon._POLLING_MIN_)
							this.hwmonPolling -= 2000;
						else
							this.hwmonPolling = this.hwmon._POLLING_MIN_;
					} else {
						// load is going down for 5min -> poll more often
						if (this.hwmonPolling - 1000 > this.hwmon._POLLING_MIN_)
							this.hwmonPolling -= 1000;
						else
							this.hwmonPolling = this.hwmon._POLLING_MIN_;
					}
				} else {
					if (Double.valueOf(load[1]) < Double.valueOf(load[2])) {
						// load is going up for 15min - pull less often
						this.hwmonPolling += 2000;
					} else {
						// load is going up for 5min - pull less often
						this.hwmonPolling += 1000;
					}
				}

				// TODO remove comments to adapt hwmon polling

				// log.debug("Sending event: " + "hwmon-change-polling "
				// + this.hwmonPolling);

				// this.evntMgr.newEvent("hwmon-change-polling "
				// + this.hwmonPolling);

			}
		}
	}

	/**
	 * Request handling.
	 */
	@Override
	public void handle(String target, Request baseRequest,
			HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {

		// TODO implement interface

		if (baseRequest.getContextPath().startsWith(
				"/.well-known/notary-cache-config")) {

			resp.setContentType("application/x-notarycache-config; charset=utf-8");
			resp.setStatus(HttpServletResponse.SC_OK);

			PrintWriter out = resp.getWriter();
			out.println(Configuration.getInstance().getConfigAsString());

		} else if (baseRequest.getContextPath().startsWith(
				"/.well-known/notary-cache")) {

			resp.setContentType("application/x-notarycache; charset=utf-8");
			resp.setStatus(HttpServletResponse.SC_OK);

			StringBuffer result = new StringBuffer();
			Configuration conf = Configuration.getInstance();
			PrintWriter out = resp.getWriter();

			// Build header
			result.append(conf.getAttribute("external.ip") + ";"
					+ conf.getAttribute("external.port") + ";"
					+ conf.getAttribute("external.hostname") + ";"
					+ conf.getAttribute("cache.validity_start") + ";"
					+ conf.getAttribute("cache.validity_end") + ";"
					+ conf.getAttribute("crypto.hashalgo") + ";"
					+ conf.getAttribute("crypto.signalgo") + "\n");

			// Get Body
			result.append(this.cachingStrategy.getCacheAsString(';',','));

			// Build footer
			MessageDigest md;
			// Calculate digest
			try {
				md = MessageDigest.getInstance(conf
						.getAttribute("crypto.hashalgo"));
				md.update(result.toString().getBytes(
						Charset.forName(conf
								.getAttribute("instance.string_encoding"))));
				// Calculate signature and append to result;
				result.append(conf.sign((new java.math.BigInteger(1, md
						.digest())).toString(16)));
			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// Return everything
			out.println(result.toString());

		} else if (baseRequest.getContextPath().startsWith(
				"/.well-known/notary")) {

			this.notary.handleRequest(target, baseRequest, req, resp, this.cachingStrategy);

		}

		/*
		 * resp.setContentType("text/html; charset=utf-8");
		 * resp.setStatus(HttpServletResponse.SC_OK);
		 *
		 * PrintWriter out = resp.getWriter();
		 *
		 * out.println(target + " --- " + baseRequest.toString());
		 */

		baseRequest.setHandled(true);

	}
}