text:
#include "test/peer_scenario/peer_scenario.h"

#include "absl/flags/flag.h"
#include "absl/memory/memory.h"
#include "rtc_base/null_socket_server.h"
#include "rtc_base/string_encode.h"
#include "rtc_base/strings/string_builder.h"
#include "test/logging/file_log_writer.h"
#include "test/testsupport/file_utils.h"
#include "test/time_controller/real_time_controller.h"
#include "test/time_controller/simulated_time_controller.h"

ABSL_FLAG(bool, peer_logs, false, "Save logs from peer scenario framework.");
ABSL_FLAG(std::string,
          peer_logs_root,
          "",
          "Output root path, based on project root if unset.");

namespace webrtc {
namespace test {
namespace {
std::unique_ptr<FileLogWriterFactory> GetPeerScenarioLogManager(
    std::string file_name) {
  if (absl::GetFlag(FLAGS_peer_logs) && !file_name.empty()) {
    std::string output_root = absl::GetFlag(FLAGS_peer_logs_root);
    if (output_root.empty())
      output_root = OutputPath() + "output_data/";

    auto base_filename = output_root + file_name + ".";
    RTC_LOG(LS_INFO) << "Saving peer scenario logs to: " << base_filename;
    return std::make_unique<FileLogWriterFactory>(base_filename);
  }
  return nullptr;
}
}  // namespace

PeerScenario::PeerScenario(const testing::TestInfo& test_info, TimeMode mode)
    : PeerScenario(
          std::string(test_info.test_suite_name()) + "/" + test_info.name(),
          mode) {}

PeerScenario::PeerScenario(std::string file_name, TimeMode mode)
    : PeerScenario(GetPeerScenarioLogManager(file_name), mode) {}

PeerScenario::PeerScenario(
    std::unique_ptr<LogWriterFactoryInterface> log_writer_manager,
    TimeMode mode)
    : log_writer_manager_(std::move(log_writer_manager)),
      net_(mode),
      signaling_thread_(net_.time_controller()->GetMainThread()) {}

PeerScenarioClient* PeerScenario::CreateClient(
    PeerScenarioClient::Config config) {
  return CreateClient(
      std::string("client_") + rtc::ToString(peer_clients_.size() + 1), config);
}

PeerScenarioClient* PeerScenario::CreateClient(
    std::string name,
    PeerScenarioClient::Config config) {
  peer_clients_.emplace_back(net(), signaling_thread_,
                             GetLogWriterFactory(name), config);
  return &peer_clients_.back();
}

SignalingRoute PeerScenario::ConnectSignaling(
    PeerScenarioClient* caller,
    PeerScenarioClient* callee,
    std::vector<EmulatedNetworkNode*> send_link,
    std::vector<EmulatedNetworkNode*> ret_link) {
  return SignalingRoute(caller, callee, net_.CreateTrafficRoute(send_link),
                        net_.CreateTrafficRoute(ret_link));
}

void PeerScenario::SimpleConnection(
    PeerScenarioClient* caller,
    PeerScenarioClient* callee,
    std::vector<EmulatedNetworkNode*> send_link,
    std::vector<EmulatedNetworkNode*> ret_link) {
  net()->CreateRoute(caller->endpoint(), send_link, callee->endpoint());
  net()->CreateRoute(callee->endpoint(), ret_link, caller->endpoint());
  auto signaling = ConnectSignaling(caller, callee, send_link, ret_link);
  signaling.StartIceSignaling();
  std::atomic<bool> done(false);
  signaling.NegotiateSdp(
      [&](const SessionDescriptionInterface&) { done = true; });
  RTC_CHECK(WaitAndProcess(&done));
}

void PeerScenario::AttachVideoQualityAnalyzer(VideoQualityAnalyzer* analyzer,
                                              VideoTrackInterface* send_track,
                                              PeerScenarioClient* receiver) {
  video_quality_pairs_.emplace_back(clock(), analyzer);
  auto pair = &video_quality_pairs_.back();
  send_track->AddOrUpdateSink(&pair->capture_tap_, rtc::VideoSinkWants());
  receiver->AddVideoReceiveSink(send_track->id(), &pair->decode_tap_);
}

bool PeerScenario::WaitAndProcess(std::atomic<bool>* event,
                                  TimeDelta max_duration) {
  return net_.time_controller()->Wait([event] { return event->load(); },
                                      max_duration);
}

void PeerScenario::ProcessMessages(TimeDelta duration) {
  net_.time_controller()->AdvanceTime(duration);
}

std::unique_ptr<LogWriterFactoryInterface> PeerScenario::GetLogWriterFactory(
    std::string name) {
  if (!log_writer_manager_ || name.empty())
    return nullptr;
  return std::make_unique<LogWriterFactoryAddPrefix>(log_writer_manager_.get(),
                                                     name);
}

}  // namespace test
}  // namespace webrtc


text:
package nl.dvberkel.demo.configuration;

import nl.dvberkel.demo.configuration.FortuneTeller;

import java.util.Collections;
import java.util.List;

public class CannedResponseFortuneTeller implements FortuneTeller {
    private final List<String> fortunes;

    public CannedResponseFortuneTeller(List<String> fortunes) {
        this.fortunes = fortunes;
    }

    @Override
    public String fortune() {
        Collections.shuffle(fortunes);
        return fortunes.get(0);
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

  <meta charset="utf-8" />
  <title>JsNgram.loadHeader js-py-ngram-full-text-search</title>
  <link rel="stylesheet" href="../../thema.css" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />

js-py-ngram-full-text-search

JsNgram.loadHeader

    .. Reference
    . JsNgram static class

method of static class JsNgram

      Description

Show header at result.

      Example

JsNgram.loadHeader(['search', 'result', 'header']);

      Usage

loadHeader(arr);

Argument arr is an array of header text.
This makes a header at the top of result block.

Currently, header is set to blank,
because the method whenSearchRequestDone calls this method
without arguments.

  .. Reference
  . JsNgram static class
  sources are available at github.


text:
package streamflow.server.resource;

import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Scopes;
import com.google.inject.servlet.GuiceFilter;
import com.google.inject.servlet.GuiceServletContextListener;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.guice.JerseyServletModule;
import com.sun.jersey.guice.spi.container.servlet.GuiceContainer;
import com.sun.jersey.test.framework.JerseyTest;
import com.sun.jersey.test.framework.WebAppDescriptor;
import com.sun.jersey.test.framework.spi.container.TestContainerFactory;
import com.sun.jersey.test.framework.spi.container.grizzly.web.GrizzlyWebTestContainerFactory;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.core.MediaType;
import streamflow.model.Serialization;
import streamflow.model.test.IntegrationTest;
import streamflow.service.SerializationService;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import static org.mockito.Mockito.*;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;

@RunWith(MockitoJUnitRunner.class)
@Category(IntegrationTest.class)
public class SerializationResourceTest extends JerseyTest {

    @Mock
    public static SerializationService serializationServiceMock;

    public SerializationResourceTest() {
        super(new WebAppDescriptor.Builder()
                .contextListenerClass(SerializationWebConfig.class)
                .filterClass(GuiceFilter.class)
                .build());
    }

    @Test
    public void listSerialiations() {
        Serialization serialization1 = new Serialization();
        serialization1.setId("serialization-1");

        Serialization serialization2 = new Serialization();
        serialization2.setId("serialization-2");

        List<Serialization> mockedSerializations = new ArrayList<Serialization>();
        mockedSerializations.add(serialization1);
        mockedSerializations.add(serialization2);

        when(serializationServiceMock.listSerializations()).thenReturn(mockedSerializations);

        List<Serialization> responseSerializations = resource().path("/api/serializations")
            .accept(MediaType.APPLICATION_JSON).get(new GenericType<List<Serialization>>(){});

        assertEquals("Response serializations should be equal to the mocked serializations",
                mockedSerializations, responseSerializations);

        verify(serializationServiceMock).listSerializations();
    }

    @Test
    public void getSerialization() {
        final Serialization mockedSerialization = new Serialization();
        mockedSerialization.setId("serialization-1");

        when(serializationServiceMock.getSerialization(anyString())).then(new Answer<Serialization>() {
            @Override
            public Serialization answer(InvocationOnMock invocation) throws Throwable {
                String argSerializationId = (String) invocation.getArguments()[0];

                assertEquals("Service serialization ID should match the requested serialization ID",
                        argSerializationId, mockedSerialization.getId());

                return mockedSerialization;
            }
        });

        Serialization responseSerialization = resource().path("/api/serializations/"
                + mockedSerialization.getId())
            .accept(MediaType.APPLICATION_JSON).get(Serialization.class);

        assertEquals("Response serialization should match the mocked serialization",
                mockedSerialization, responseSerialization);

        verify(serializationServiceMock).getSerialization(anyString());
    }

    @Override
    public TestContainerFactory getTestContainerFactory() {
        return new GrizzlyWebTestContainerFactory();
    }

    public static class SerializationWebConfig extends GuiceServletContextListener {
        @Override
        protected Injector getInjector() {
            return Guice.createInjector(new JerseyServletModule() {

                @Override
                protected void configureServlets() {
                    bind(SerializationService.class).toInstance(serializationServiceMock);
                    bind(SerializationResource.class);

                    serve("/api/*").with(GuiceContainer.class);

                    // hook Jackson into Jersey as the POJO <-> JSON mapper
                    bind(JacksonJsonProvider.class).in(Scopes.SINGLETON);
                }
            });
        }
    }
}


text:
package kafka.producer;

import kafka.common.Config;
import kafka.common.InvalidConfigException;
import kafka.message.CompressionCodec;
import kafka.message.CompressionCodecs;
import kafka.message.NoCompressionCodec;
import kafka.producer.async.AsyncProducerConfig;
import kafka.utils.Utils;
import kafka.utils.VerifiableProperties;

import java.util.List;
import java.util.Properties;

public class ProducerConfig extends AsyncProducerConfig {
    public static void validate(ProducerConfig config) {
        validateClientId(config.clientId);
        validateBatchSize(config.batchNumMessages, config.queueBufferingMaxMessages);
        validateProducerType(config.producerType);
    }

    public static void validateClientId(String clientId) {
        Config.validateChars("client.id", clientId);
    }

    public static void validateBatchSize(int batchSize, int queueSize) {
        if (batchSize > queueSize)
            throw new InvalidConfigException("Batch size = " + batchSize + " can't be larger than queue size = " + queueSize);
    }

    public static void validateProducerType(String producerType) {
        if (producerType.equals("sync") || producerType.equals("async")) {
        } else {
            throw new InvalidConfigException("Invalid value " + producerType + " for producer.type, valid values are sync/async");
        }
    }

    public ProducerConfig(VerifiableProperties props) {
        super(props);
        init();
    }

    public ProducerConfig(Properties originalProps) {
        this(new VerifiableProperties(originalProps));
        props.verify();
    }

    public String brokerList;
    public String partitionerClass;
    public String producerType;
    public CompressionCodec compressionCodec;
    public List<String> compressedTopics;
    public int messageSendMaxRetries;
    public int retryBackoffMs;
    public int topicMetadataRefreshIntervalMs;

    private void init() {
        /** This is for bootstrapping and the producer will only use it for getting metadata
         * (topics, partitions and replicas). The socket connections for sending the actual data
         * will be established based on the broker information returned in the metadata. The
         * format is host1:port1,host2:port2, and the list can be a subset of brokers or
         * a VIP pointing to a subset of brokers.
         */
        brokerList = props.getString("metadata.broker.list");

        /** the partitioner class for partitioning events amongst sub-topics */
        partitionerClass = props.getString("partitioner.class", "kafka.producer.DefaultPartitioner");

        /** this parameter specifies whether the messages are sent asynchronously *
         * or not. Valid values are - async for asynchronous send                 *
         *                            sync for synchronous send                   */
        producerType = props.getString("producer.type", "sync");

        /**
         * This parameter allows you to specify the compression codec for all data generated *
         * by this producer. The default is NoCompressionCodec
         */
        {
            String prop = props.getString("compression.codec", NoCompressionCodec.instance.name());
            try {
                compressionCodec = CompressionCodecs.getCompressionCodec(Integer.parseInt(prop));
            } catch (NumberFormatException e) {
                compressionCodec = CompressionCodecs.getCompressionCodec(prop);
            }
        }

        /** This parameter allows you to set whether compression should be turned *
         *  on for particular topics
         *
         *  If the compression codec is anything other than NoCompressionCodec,
         *
         *    Enable compression only for specified topics if any
         *
         *    If the list of compressed topics is empty, then enable the specified compression codec for all topics
         *
         *  If the compression codec is NoCompressionCodec, compression is disabled for all topics
         */
        compressedTopics = Utils.parseCsvList(props.getString("compressed.topics", null));

        /** The leader may be unavailable transiently, which can fail the sending of a message.
         *  This property specifies the number of retries when such failures occur.
         */
        messageSendMaxRetries = props.getInt("message.send.max.retries", 3);

        /** Before each retry, the producer refreshes the metadata of relevant topics. Since leader
         * election takes a bit of time, this property specifies the amount of time that the producer
         * waits before refreshing the metadata.
         */
        retryBackoffMs = props.getInt("retry.backoff.ms", 100);

        /**
         * The producer generally refreshes the topic metadata from brokers when there is a failure
         * (partition missing, leader not available...). It will also poll regularly (default: every 10min
         * so 600000ms). If you set this to a negative value, metadata will only get refreshed on failure.
         * If you set this to zero, the metadata will get refreshed after each message sent (not recommended)
         * Important note: the refresh happen only AFTER the message is sent, so if the producer never sends
         * a message the metadata is never refreshed
         */
        topicMetadataRefreshIntervalMs = props.getInt("topic.metadata.refresh.interval.ms", 600000);

        validate(this);
    }

}


text:
#ifndef INCLUDE_MIDSO_LAYER_DROP_OUT_LAYER_H_
#define INCLUDE_MIDSO_LAYER_DROP_OUT_LAYER_H_
#include "midso/common.h"
#include "midso/layer/layer_interface.h"

namespace midso {

class DropOutLayer : public LayerInterface {
 public:
    DropOutLayer() {}
    ~DropOutLayer() {}
    DropOutLayer(const Float & drop_rate = 0.5);
    static DropOutLayer * load(const KeyValueTree & config);
    void init(const Tensor & in_tensor);
    void set_input(const Tensor & in_tensor);
    void propagate();
    BackwardLayerInterface & backward_layer();
    const Tensor & get_output() const;

 private:
    DISALLOW_COPY_AND_ASSIGN(DropOutLayer);
};

}  // namespace midso

#endif  // INCLUDE_MIDSO_LAYER_DROP_OUT_LAYER_H_


text:
import external from './../externalModules.js';
import BaseTool from './base/BaseTool.js';

import { getNewContext } from '../drawing/index.js';
import renderActiveReferenceLine from './referenceLines/renderActiveReferenceLine.js';
import { waitForEnabledElementImageToLoad } from '../util/wait.js';
import { getLogger } from '../util/logger.js';

const logger = getLogger('tools:ReferenceLinesTool');

/**
 * When enabled, this tool will display references lines for each source
 * enabledElement in the provided synchronizer. This tool can also be configured
 * to use a custom renderer for alternative reference line rendering behavior
 *
 * TODO: Need to watch for configuration changes to update ToolState
 * TODO:
 *
 * @export @public @class
 * @name ReferenceLinesTool
 * @classdesc Tool for displaying reference lines of other enabledElements
 * @extends Tools.Base.BaseTool
 */
export default class ReferenceLinesTool extends BaseTool {
  constructor(props = {}) {
    const defaultProps = {
      name: 'ReferenceLines',
      mixins: ['enabledOrDisabledBinaryTool'],
      configuration: {
        renderer: renderActiveReferenceLine,
      },
    };

    super(props, defaultProps);

    this.renderer = null;
    this.synchronizationContext = null;
  }

  async enabledCallback(element, { synchronizationContext } = {}) {
    const renderer = this.configuration.renderer;
    const enabledElement = await waitForEnabledElementImageToLoad(element);

    if (!enabledElement || !renderer || !synchronizationContext) {
      // TODO: Unable to add tool state, image never loaded.
      // Should we `setToolDisabledForElement` here?
      logger.warn(
        `Unable to enable ${this.name}. Exiting enable callback. Tool will be enabled, but will not render.`
      );

      return;
    }
    this.renderer = renderer;
    this.synchronizationContext = synchronizationContext;

    this.forceImageUpdate(element);
  }

  disabledCallback(element) {
    this.forceImageUpdate(element);
  }

  forceImageUpdate(element) {
    const enabledElement = external.cornerstone.getEnabledElement(element);

    if (enabledElement.image) {
      external.cornerstone.updateImage(element);
    }
  }

  renderToolData(evt) {
    const eventData = evt.detail;

    // No renderer or synch context? Adios
    if (!this.renderer || !this.synchronizationContext) {
      return;
    }

    // Get the enabled elements associated with this synchronization context and draw them
    const enabledElements = this.synchronizationContext.getSourceElements();
    const context = getNewContext(eventData.canvasContext.canvas);

    external.cornerstone.setToPixelCoordinateSystem(
      eventData.enabledElement,
      context
    );
    enabledElements.forEach(referenceEnabledElement => {
      // Don't draw ourselves
      if (referenceEnabledElement === evt.currentTarget) {
        return;
      }

      // Render it
      this.renderer(
        context,
        eventData,
        evt.currentTarget,
        referenceEnabledElement
      );
    });
  }
}


text:
const FactionId GameFactions::FACTION_PLAYER = 0;
//AI allied to the player is on this team
const FactionId GameFactions::FACTION_PLAYERALLY = 1;
//Enemies hostile to all are on this team, or any other
const FactionId GameFactions::FACTION_HOSTILE = 3;
//The terrain (such is if you fall from a great height or a physics voxel hits you)
const FactionId GameFactions::FACTION_EARTH = 4;
//AI factions start at this and go up
const FactionId GameFactions::FACTION_AIFACTION = 100;
//The number of AI factions
const int GameFactions::AI_FACTION_COUNT = 5;
//To make an actor hostile to all other actors
//just randomly assign a faction id

GameFactions::GameFactions() {
	//Create normal alliances
	SetAllies(FACTION_PLAYER,FACTION_PLAYERALLY);
}

//To save allies use manual save/load embedded in these functions
void GameFactions::Save(Json::Value & parentValue) {
	Json::Value & allySets = parentValue["allies"];
	int allyNumber = 0;
	//save each ally
	for (auto allyPair : allies) {
		Json::Value & pair = allySets[allyNumber];
		pair["first"] = allyPair.first;
		pair["second"] = allyPair.second;
		allyNumber++;
	}
}

void GameFactions::Load(Json::Value & parentValue, LoadData & loadData) {
	//Clear existing allies
	allies.clear();

	//Load new ones
	Json::Value & allySets = parentValue["allies"];
	for (auto ally : allySets) {
		allies.insert(pair<FactionId,FactionId>(ally["first"].asInt(),ally["second"].asInt()));
	}
}

//Retrieve the color of the given faction
vec4 GameFactions::FactionColor(FactionId faction) {
	static const vec4 factionColorLookup[] = {
		vec4(0,0,1,1),
		vec4(1,1,0,1),
		vec4(1,0,1,1),
		vec4(.5,0,.75,1),
		vec4(0,1,1,1),
	};
	//The player's faction is green
	if (faction == FACTION_PLAYERALLY)
		return vec4(0,1,0,1);
	//Check if the faction is an AI faction
	if ((faction < FACTION_AIFACTION) || (faction >= (FACTION_AIFACTION+AI_FACTION_COUNT)))
		return vec4();
	return factionColorLookup[faction-FACTION_AIFACTION];
}

//Check if two factions are allies
bool GameFactions::IsAlly(FactionId a, FactionId b) {
	return (a == b) || allies.find(pair<FactionId,FactionId>(a,b)) != allies.end();
}
//Check if two factions are enemies
bool GameFactions::IsEnemy(FactionId a, FactionId b) {
	return (a != b) && allies.find(pair<FactionId,FactionId>(a,b)) == allies.end();
}

//Make two factions allies
void GameFactions::SetAllies(FactionId a, FactionId b) {
	if (!IsAlly(a,b)) {
		allies.insert(pair<FactionId,FactionId>(a,b));
		allies.insert(pair<FactionId,FactionId>(b,a));
	}

}
//Make two factions enemies
void GameFactions::SetEnemies(FactionId a, FactionId b) {
	if (IsAlly(a,b)) {
		allies.erase(allies.find(pair<FactionId,FactionId>(a,b)));
		allies.erase(allies.find(pair<FactionId,FactionId>(b,a)));
	}

}


text:
package com.intellij.diagnostic;

import com.intellij.openapi.application.ApplicationManager;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

interface PluginProblemReporter {
  static PluginProblemReporter getInstance() {
    if (ApplicationManager.getApplication() == null) {
      //if the application isn't initialized yet return silly implementation which reports all plugins problems as platform ones
      return new PluginProblemReporter() {
        @NotNull
        @Override
        public PluginException createPluginExceptionByClass(@NotNull String errorMessage,
                                                            @Nullable Throwable cause,
                                                            @NotNull Class pluginClass) {
          return new PluginException(errorMessage, cause, null);
        }
      };
    }

    return ApplicationManager.getApplication().getService(PluginProblemReporter.class);
  }

  @NotNull
  PluginException createPluginExceptionByClass(@NotNull String errorMessage, @Nullable Throwable cause, @NotNull Class<?> pluginClass);
}


text:
using System;
using Avalonia.VisualTree;

namespace Avalonia.Media.Immutable
{
    /// <summary>
    /// Paints an area with an <see cref="IVisual"/>.
    /// </summary>
    internal class ImmutableVisualBrush : ImmutableTileBrush, IVisualBrush
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ImmutableImageBrush"/> class.
        /// </summary>
        /// <param name="visual">The visual to draw.</param>
        /// <param name="alignmentX">The horizontal alignment of a tile in the destination.</param>
        /// <param name="alignmentY">The vertical alignment of a tile in the destination.</param>
        /// <param name="destinationRect">The rectangle on the destination in which to paint a tile.</param>
        /// <param name="opacity">The opacity of the brush.</param>
        /// <param name="sourceRect">The rectangle of the source image that will be displayed.</param>
        /// <param name="stretch">
        /// How the source rectangle will be stretched to fill the destination rect.
        /// </param>
        /// <param name="tileMode">The tile mode.</param>
        public ImmutableVisualBrush(
            IVisual visual,
            AlignmentX alignmentX = AlignmentX.Center,
            AlignmentY alignmentY = AlignmentY.Center,
            RelativeRect? destinationRect = null,
            double opacity = 1,
            RelativeRect? sourceRect = null,
            Stretch stretch = Stretch.Uniform,
            TileMode tileMode = TileMode.None)
            : base(
                  alignmentX,
                  alignmentY,
                  destinationRect ?? RelativeRect.Fill,
                  opacity,
                  sourceRect ?? RelativeRect.Fill,
                  stretch,
                  tileMode)
        {
            Visual = visual;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ImmutableVisualBrush"/> class.
        /// </summary>
        /// <param name="source">The brush from which this brush's properties should be copied.</param>
        public ImmutableVisualBrush(IVisualBrush source)
            : base(source)
        {
            Visual = source.Visual;
        }

        /// <inheritdoc/>
        public IVisual Visual { get; }
    }
}


text:
package sbt
package inc

import java.io.File

import org.scalacheck._
import Arbitrary._
import Gen._

import sbt.Relation
import xsbti.api._
import xsbti.SafeLazy

/**
 * Scalacheck generators for Analysis objects and their substructures.
 * Fairly complex, as Analysis has interconnected state that can't be
 * independently generated.
 */
object TestCaseGenerators {
	// We restrict sizes, otherwise the generated Analysis objects get huge and the tests take a long time.
	val maxSources = 10  // Max number of source files.
	val maxRelatives = 10  // Max number of things that a source x can relate to in a single Relation.
	val maxPathSegmentLen = 10  // Max number of characters in a path segment.
	val maxPathLen = 6  // Max number of path segments in a path.

	// Ensure that we generate unique class names and file paths every time.
	// Using repeated strings may lead to all sorts of undesirable interactions.
	val used = scala.collection.mutable.Set.empty[String]

	def unique[T](g: Gen[T]) = g retryUntil { o: T => used.add(o.toString) }

	def identifier: Gen[String] = sized { size =>
		resize(Math.max(size, 3), Gen.identifier)
	}

	def genFilePathSegment: Gen[String] = for {
		n <- choose(3, maxPathSegmentLen)  // Segments have at least 3 characters.
		c <- alphaChar
		cs <- listOfN(n - 1, alphaNumChar)
	} yield (c::cs).mkString

	def genFile: Gen[File] = for {
		n <- choose(2, maxPathLen)  // Paths have at least 2 segments.
		path <- listOfN(n, genFilePathSegment)
	} yield new File(path.mkString("/"))

	def genStamp: Gen[Stamp] = for {
		b <- oneOf(true, false)
	} yield new Exists(b)

	def zipMap[A, B](a: Seq[A], b: Seq[B]): Map[A, B] = (a zip b).toMap

	def genStamps(rel: Relations): Gen[Stamps] = {
		val prod = rel.allProducts.toList
		val src = rel.allSources.toList
		val bin = rel.allBinaryDeps.toList
		for {
			prodStamps <- listOfN(prod.length, genStamp)
			srcStamps <- listOfN(src.length, genStamp)
			binStamps <- listOfN(bin.length, genStamp)
			binClassNames <- listOfN(bin.length, unique(identifier))
		} yield Stamps(zipMap(prod, prodStamps), zipMap(src, srcStamps), zipMap(bin, binStamps), zipMap(bin, binClassNames))
	}

	// We need "proper" definitions with specific class names, as groupBy use these to pick a representative top-level class when splitting.
	private[this] def makeDefinition(name: String): Definition =
	new ClassLike(DefinitionType.ClassDef, lzy(new EmptyType()),
		lzy(new Structure(lzy(Array()), lzy(Array()), lzy(Array()))), Array(), Array(),
		name, new Public(), new Modifiers(false, false, false, false, false, false, false), Array())

	private [this] def lzy[T <: AnyRef](x: T) = SafeLazy.strict(x)

	def genNameHash(defn: String): Gen[xsbti.api._internalOnly_NameHash] =
        value(new xsbti.api._internalOnly_NameHash(defn, defn.hashCode()))

	def genNameHashes(defns: Seq[String]): Gen[xsbti.api._internalOnly_NameHashes] = {
	        def partitionAccordingToMask[T](mask: List[Boolean], xs: List[T]): (List[T], List[T]) = {
	                val (p1, p2) = (mask zip xs).partition(_._1)
	                (p1.map(_._2), p2.map(_._2))
	        }
	        val pairsOfGenerators = for (defn <- defns) yield {
	                for {
	                        isRegularMember <- arbitrary[Boolean]
	                        nameHash <- genNameHash(defn)
	                } yield (isRegularMember, nameHash)
	        }
	        val genNameHashesList = Gen.sequence[List, xsbti.api._internalOnly_NameHash](defns.map(genNameHash))
	        val genTwoListOfNameHashes = for {
	                nameHashesList <- genNameHashesList
	                isRegularMemberList <- listOfN(nameHashesList.length, arbitrary[Boolean])
	        } yield partitionAccordingToMask(isRegularMemberList, nameHashesList)
	        for {
	                (regularMemberNameHashes, implicitMemberNameHashes) <- genTwoListOfNameHashes
	        } yield new xsbti.api._internalOnly_NameHashes(regularMemberNameHashes.toArray, implicitMemberNameHashes.toArray)
	}

	def genSource(defns: Seq[String]): Gen[Source] = for {
		startTime <- arbitrary[Long]
		hashLen <- choose(10, 20)  // Requred by SameAPI to be > 0.
		hash <- Gen.containerOfN[Array,Byte](hashLen, arbitrary[Byte])
		apiHash <- arbitrary[Int]
		hasMacro <- arbitrary[Boolean]
		nameHashes <- genNameHashes(defns)
	} yield new Source(new Compilation(startTime, Array()), hash, new SourceAPI(Array(), Array(defns map makeDefinition:_*)), apiHash, nameHashes, hasMacro)

	def genSources(all_defns: Seq[Seq[String]]): Gen[Seq[Source]] = Gen.sequence[List, Source](all_defns.map(genSource))

	def genAPIs(rel: Relations): Gen[APIs] = {
		val internal = rel.allInternalSrcDeps.toList.sorted
		val external = rel.allExternalDeps.toList.sorted
		for {
			internalSources <- genSources(internal map { f: File => rel.classNames(f).toList.sorted })
			externalSources <- genSources(external map { s: String => s :: Nil })
		} yield APIs(zipMap(internal, internalSources), zipMap(external, externalSources))
	}

	def genRelation[T](g: Gen[T])(srcs: List[File]): Gen[Relation[File, T]] = for {
		n <- choose(1, maxRelatives)
		entries <- listOfN(srcs.length, containerOfN[Set, T](n, g))
	} yield Relation.reconstruct(zipMap(srcs, entries))

	val genFileRelation = genRelation[File](unique(genFile)) _
	val genStringRelation = genRelation[String](unique(identifier)) _

	def genRSource(srcs: List[File]): Gen[Relations.Source] = for {
		internal <- listOfN(srcs.length, someOf(srcs))  // Internal dep targets must come from list of sources.
		external <- genStringRelation(srcs)
	} yield Relations.makeSource(  // Ensure that we don't generate a dep of some file on itself.
			Relation.reconstruct((srcs zip (internal map { _.toSet } ) map {case (a, b) => (a, b - a) }).toMap),
			external)

	def genSubRSource(src: Relations.Source): Gen[Relations.Source] = for {
		internal <- someOf(src.internal.all.toList)
		external <- someOf(src.external.all.toList)
	} yield Relations.makeSource(Relation.empty ++ internal, Relation.empty ++ external)

	def genRelations: Gen[Relations] = for {
		numSrcs <- choose(0, maxSources)
		srcs <- listOfN(numSrcs, genFile)
		srcProd <- genFileRelation(srcs)
		binaryDep <- genFileRelation(srcs)
		direct <- genRSource(srcs)
		publicInherited <- genSubRSource(direct)
		classes <- genStringRelation(srcs)

	} yield Relations.make(srcProd, binaryDep, direct, publicInherited , classes)

	def genAnalysis: Gen[Analysis] = for {
		rels <- genRelations
		stamps <- genStamps(rels)
		apis <- genAPIs(rels)
	} yield new MAnalysis(stamps, apis, rels, SourceInfos.empty, Compilations.empty)
}


text:
import { ChartConfiguration } from './ChartConfiguration.class';
import { ChartAxisConfiguration } from './ChartAxisConfiguration.class';
import { ChartLegendConfiguration } from './ChartLegendConfiguration.class';
import { ChartZoomConfiguration } from './ChartZoomConfiguration.class';

export class OHLCChartConfiguration extends ChartConfiguration {
  readonly type: string = 'ohlcBarChart';

  x1Axis: ChartAxisConfiguration;
  showXAxis: boolean = true;
  y1Axis: ChartAxisConfiguration;
  showYAxis: boolean = true;
  rightAlignYAxis: boolean = false;

  legend: ChartLegendConfiguration;
  showLegend: boolean = false;

  zoom: ChartZoomConfiguration;

  low: any;
  high: any;

  useInteractiveGuideline: boolean = true;
  padData: boolean = false;
  clidEdge: boolean = true;

  //Properties for select the values of date, open,
  // close, high and low in data adapter
  xColumn: string;
  openAxis: string;
  closeAxis: string;
  highAxis: string;
  lowAxis: string;

  constructor() {
    super();
    this.x1Axis = new ChartAxisConfiguration();
    this.y1Axis = new ChartAxisConfiguration();
    this.legend = new ChartLegendConfiguration();
    this.zoom = new ChartZoomConfiguration();
  }
}


text:
/**
 *  Entry point for common data
 */

$(function() {

  var CommonData = cdb.core.View.extend({

    el: document.body,

    initialize: function() {
      this._initModels();
      this._initViews();
    },

    _initModels: function() {
      this.user = new cdb.admin.User(this.options.user_data);
      this.common_tables = new cdb.admin.CommonTables(this.options.common_data);
      this.tables = new cdb.admin.Tables();
      this.first_time = true;

      // The user model has to update every time the table model
      this.tables.bind('add remove reset', function(){
        if (!this.first_time)
          this.user.fetch();

        this.first_time = false;
      }, this);
      this.tables.bind('error', function(e) {
        cdb.log.info("error", e);
      });
    },

    _initViews: function() {
      // User menu
      var user_menu = this.user_menu = new cdb.admin.DropdownMenu({
        target:         $('a.account'),
        host:           config.account_host,
        username:       username,
        template_base:  'common/views/settings_item'
      });
      cdb.god.bind("closeDialogs", user_menu.hide, user_menu);
      this.$el.append(this.user_menu.render().el);

      // Background Importer
      var bkg_importer = this.bkg_importer = new cdb.ui.common.BackgroundImporter({
        template_base: 'common/views/background_importer'
      });
      this.$el.append(this.bkg_importer.render().el);

      // Create new table view
      var createTable = this.createTable = new cdb.admin.CreateTable({
        el:       this.$el,
        importer: this.bkg_importer,
        tables:   this.tables,
        model:    this.user,
        config:   this.options.config
      });

      // Check imports
      this._checkActiveImports();

      // Common data list
      var common_list = this.common_list = new cdb.admin.CommonTablesView({
        collection: this.common_tables,
        user: this.user,
        el: this.$('table')
      }).bind('create', function(e) {
        createTable.importExample(e);
      }).bind('upgrade', function(e) {
        createTable.showUpgrade(e);
      })
      common_list.render();

      // global click
      enableClickOut(this.$el);
    },

    /**
     *  Check if there is any pending import in the background
     */
    _checkActiveImports: function() {
      // Check pending importations
      var imports = new cdb.admin.Imports()
        , self    = this;

      // Start background importer
      this.bkg_importer.changeState({ state: "checking" });

      imports.bind("importsFinished", function(e){
        self.bkg_importer.changeState({ state: "complete" });

        $.when(self.tables.fetch()).done(function() {
          self.tables.trigger('forceReload');
        }).fail(function(){
          self.tables.trigger('loadFailed');
        });

        setTimeout(self.bkg_importer.hide, 3000);
        imports.unbind();
      },this).bind("importsFailed", function(imp){
        self.bkg_importer.changeState(imp[0].toJSON());
      },this).bind("importsStart", function(e){
        self.bkg_importer.changeState({ state: "preprocessing" });
      },this).bind("importsEmpty", function(e){
        self.bkg_importer.hide();
        imports.unbind();
      });

      imports.pollCheck();
    }
  });

  cdb.init(function() {

    cdb.templates.namespace = 'cartodb/';
    var common_data = new CommonData({
      user_data:    user_data,
      common_data:  public_data,
      config:       config
    });

    // Expose to debug
    window.common_data = common_data;
  });

});


text:
package com.linkedin.pinot.core.query.aggregation.function;

import com.linkedin.pinot.common.data.FieldSpec;
import com.linkedin.pinot.core.common.BlockValSet;
import com.linkedin.pinot.core.query.aggregation.AggregationResultHolder;
import com.linkedin.pinot.core.query.aggregation.DoubleAggregationResultHolder;
import com.linkedin.pinot.core.query.aggregation.groupby.DoubleGroupByResultHolder;
import com.linkedin.pinot.core.query.aggregation.groupby.GroupByResultHolder;
import javax.annotation.Nonnull;

public class CountAggregationFunction implements AggregationFunction<Long, Long> {
  private static final String NAME = AggregationFunctionFactory.AggregationFunctionType.COUNT.getName();
  private static final double DEFAULT_INITIAL_VALUE = 0.0;

  @Nonnull
  @Override
  public String getName() {
    return NAME;
  }

  @Nonnull
  @Override
  public String getColumnName(@Nonnull String[] columns) {
    return NAME + "_star";
  }

  @Override
  public void accept(@Nonnull AggregationFunctionVisitorBase visitor) {
    visitor.visit(this);
  }

  @Nonnull
  @Override
  public AggregationResultHolder createAggregationResultHolder() {
    return new DoubleAggregationResultHolder(DEFAULT_INITIAL_VALUE);
  }

  @Nonnull
  @Override
  public GroupByResultHolder createGroupByResultHolder(int initialCapacity, int maxCapacity, int trimSize) {
    return new DoubleGroupByResultHolder(initialCapacity, maxCapacity, trimSize, DEFAULT_INITIAL_VALUE);
  }

  @Override
  public void aggregate(int length, @Nonnull AggregationResultHolder aggregationResultHolder,
      @Nonnull BlockValSet... blockValSets) {
    aggregationResultHolder.setValue(aggregationResultHolder.getDoubleResult() + length);
  }

  @Override
  public void aggregateGroupBySV(int length, @Nonnull int[] groupKeyArray,
      @Nonnull GroupByResultHolder groupByResultHolder, @Nonnull BlockValSet... blockValSets) {
    for (int i = 0; i < length; i++) {
      int groupKey = groupKeyArray[i];
      groupByResultHolder.setValueForKey(groupKey, groupByResultHolder.getDoubleResult(groupKey) + 1);
    }
  }

  @Override
  public void aggregateGroupByMV(int length, @Nonnull int[][] groupKeysArray,
      @Nonnull GroupByResultHolder groupByResultHolder, @Nonnull BlockValSet... blockValSets) {
    for (int i = 0; i < length; i++) {
      for (int groupKey : groupKeysArray[i]) {
        groupByResultHolder.setValueForKey(groupKey, groupByResultHolder.getDoubleResult(groupKey) + 1);
      }
    }
  }

  @Nonnull
  @Override
  public Long extractAggregationResult(@Nonnull AggregationResultHolder aggregationResultHolder) {
    return (long) aggregationResultHolder.getDoubleResult();
  }

  @Nonnull
  @Override
  public Long extractGroupByResult(@Nonnull GroupByResultHolder groupByResultHolder, int groupKey) {
    return (long) groupByResultHolder.getDoubleResult(groupKey);
  }

  @Nonnull
  @Override
  public Long merge(@Nonnull Long intermediateResult1, @Nonnull Long intermediateResult2) {
    return intermediateResult1 + intermediateResult2;
  }

  @Override
  public boolean isIntermediateResultComparable() {
    return true;
  }

  @Nonnull
  @Override
  public FieldSpec.DataType getIntermediateResultDataType() {
    return FieldSpec.DataType.LONG;
  }

  @Nonnull
  @Override
  public Long extractFinalResult(@Nonnull Long intermediateResult) {
    return intermediateResult;
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace RationalVote
{
	public class RouteConfig
	{
		public static void RegisterRoutes( RouteCollection routes )
		{
			routes.MapMvcAttributeRoutes();

			routes.IgnoreRoute( "{resource}.axd/{*pathInfo}" );

			routes.MapRoute(
				name: "Default",
				url: "{controller}/{action}/{id}",
				defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
			);

			// Add this code to handle non-existing urls
			routes.MapRoute(
				name: "404-PageNotFound",
				// This will handle any non-existing urls
				url: "{*url}",
				// "Shared" is the name of your error controller, and "Error" is the action/page
				// that handles all your custom errors
				defaults: new { controller = "Shared", action = "Error" }
			);
		}
	}
}


text: Lowrezjam entry


text:
{{ $cover := .HasShortcode "blocks/cover" }}

		{{ if .Site.Params.ui.navbar_logo }}{{ with resources.Get "icons/logo.svg" }}{{ ( . | minify).Content | safeHTML }}{{ end }}{{ end }}{{ .Site.Title }}

			{{ $p := . }}
			{{ range .Site.Menus.main }}

				{{ $active := or ($p.IsMenuCurrent "main" .) ($p.HasMenuCurrent "main" .) }}
				{{ with .Page }}
				{{ $active = or $active ( $.IsDescendant .)  }}
				{{ end }}
				{{ $url := urls.Parse .URL }}
                {{ $baseurl := urls.Parse $.Site.Params.Baseurl }}

                    {{ if .Name }}{{ .Name }}{{ end }}
                    {{ .Pre }}

			{{ end }}
			{{ if  .Site.Params.versions }}

				{{ partial "navbar-version-selector.html" . }}

			{{ end }}
			{{ if  (gt (len .Site.Home.Translations) 0) }}

				{{ partial "navbar-lang-selector.html" . }}

			{{ end }}

{{ partial "search-input.html" . }}


text:
package io.dwak.holohackernews.app.dagger.module;

import android.app.Application;
import android.content.Context;
import android.content.res.Resources;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import javax.inject.Named;
import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;
import io.dwak.holohackernews.app.BuildConfig;
import io.dwak.holohackernews.app.cache.CacheManager;
import io.dwak.holohackernews.app.network.LoganSquareConvertor;
import io.dwak.holohackernews.app.network.LongTypeAdapter;
import retrofit.RestAdapter;

@Module
public class AppModule {
    public static final String CACHE_MANAGER = "cacheManager";
    public static final String RESOURCES = "resources";
    Application mApplication;

    public AppModule(Application application) {
        mApplication = application;
    }

    @Provides
    @Named("context")
    Context providesApplication() {
        return mApplication;
    }

    @Provides
    @Named(RESOURCES)
    Resources providesResources() {
        return mApplication.getResources();
    }

    @Provides
    @Named("gson")
    Gson providesGson() {
        return new GsonBuilder().registerTypeAdapter(Long.class, new LongTypeAdapter())
                                .create();
    }

    @Provides
    @Singleton
    @Named("loganSquare")
    LoganSquareConvertor providesLoganSquare(){
        return new LoganSquareConvertor();
    }

    @Provides
    @Named("retrofit-loglevel")
    RestAdapter.LogLevel providesLogLevel(){
        if(BuildConfig.DEBUG) {
            return RestAdapter.LogLevel.FULL;
        }
        else {
            return RestAdapter.LogLevel.NONE;
        }
    }

    @Provides
    @Named(CACHE_MANAGER)
    CacheManager providesCacheManager(@Named("context")Context context,
                                      @Named("gson") Gson gson){
        return CacheManager.getInstance(context, gson);
    }
}


text:
package com.github.daylily.mt.lock.sync;

import com.github.daylily.mt.lock.CustomService;

public class ThreadAA extends Thread {

	private CustomService service;

	public ThreadAA(CustomService service) {
		super();
		this.service = service;
	}

	@Override
	public void run() {
		service.serviceA();
	}
}


text:
BucketList::Engine.routes.draw do
  resources :lists
end


text:
<?php

namespace Simple\Type\Test;

use Simple\Type\String;

class StringManipulationTest extends \PHPUnit_Framework_TestCase
{
    public function testIsAppending()
    {
        $string = new String('ipsum Dolor amet');
        $result = $string->append(" lorem");

        $this->assertInstanceOf('Simple\\Type\\String', $result);
        $this->assertEquals('ipsum Dolor amet lorem', $result->toString());
    }

    public function testIsPrepending()
    {
        $string = new String('ipsum Dolor amet lorem');
        $result = $string->prepend("Lorem ");

        $this->assertInstanceOf('Simple\\Type\\String', $result);
        $this->assertEquals('Lorem ipsum Dolor amet lorem', $result->toString());
    }

    public function testIsChopping()
    {
        $string = new String('Lorem ipsum Dolor amet lorem');
        $result = $string->chop();

        $this->assertInstanceOf('Simple\\Type\\String', $result);
        $this->assertEquals('Lorem ipsum Dolor amet lore', $result->toString());
    }

    public function testIsShortening()
    {
        $string = new String('Lorem ipsum dolor sit amet nepet quisquam');
        $result = $string->shorten(10);
        $this->assertInstanceOf('Simple\\Type\\String', $result);
        $this->assertEquals('Lorem ipsu', $result->toString());

        $result = $string->shorten(10, true);
        $this->assertInstanceOf('Simple\\Type\\String', $result);
        $this->assertEquals('Lorem', $result->toString());

        $string = new String('Lorem ipsum Dolor');
        $result = $string->shorten(3, true);
        $this->assertInstanceOf('Simple\\Type\\String', $result);
        $this->assertEquals('', $result->toString());

        $string = new String('Lorem ipsum Dolor');
        $result = $string->shorten(6, true);
        $this->assertInstanceOf('Simple\\Type\\String', $result);
        $this->assertEquals('Lorem', $result->toString());
    }

    public function testIsReversing()
    {
        $string = new String('Lorem ipsum Dolor amet lore');
        $result = $string->reverse();

        $this->assertInstanceOf('Simple\\Type\\String', $result);
        $this->assertEquals('erol tema roloD muspi meroL', $result->toString());

        $normal = $result->reverse();
        $this->assertInstanceOf('Simple\\Type\\String', $normal);
        $this->assertEquals('Lorem ipsum Dolor amet lore', $normal->toString());
    }

    public function testIsScrambling()
    {
        $string = new String('Lorem ipsum dolor');
        $result = $string->scramble();

        $this->assertInstanceOf('Simple\\Type\\String', $result);
        $this->assertRegExp('/[Lorem]+ [ipsum]+ [dolor]+/', $result->toString());
    }

    public function testIsShuffling()
    {
        $string = new String('Lorem ipsum dolor');
        $result = $string->shuffle();

        $this->assertInstanceOf('Simple\\Type\\String', $result);
        $this->assertRegExp('/[Loremipsudl ]+/', $result->toString());
    }

    public function testIsIntersectingStrings()
    {
        $string = new String('Lorem ipsum dolor sit amet');
        $result = $string->intersect('Avis sit amet nepet quisquam');

        $this->assertInstanceOf('Simple\\Type\\String', $result);
        $this->assertEquals('sit amet', $result->toString());
    }

    public function testIsCountingWords()
    {
        $string = new String('Lorem ipsum Dolor amet lore');
        $this->assertEquals(5, $string->words());

        $string = new String('Lorem');
        $this->assertEquals(1, $string->words());

        $string = new String('    ');
        $this->assertEquals(0, $string->words());
    }
}


text:
from msrest.serialization import Model

class PoolSpecification(Model):
    """Specification for creating a new pool.

    :param display_name: The display name for the pool. The display name need
     not be unique and can contain any Unicode characters up to a maximum
     length of 1024.
    :type display_name: str
    :param vm_size: The size of the virtual machines in the pool. All virtual
     machines in a pool are the same size. For information about available
     sizes of virtual machines for Cloud Services pools (pools created with
     cloudServiceConfiguration), see Sizes for Cloud Services
     (http://azure.microsoft.com/documentation/articles/cloud-services-sizes-specs/).
     Batch supports all Cloud Services VM sizes except ExtraSmall, A1V2 and
     A2V2. For information about available VM sizes for pools using images from
     the Virtual Machines Marketplace (pools created with
     virtualMachineConfiguration) see Sizes for Virtual Machines (Linux)
     (https://azure.microsoft.com/documentation/articles/virtual-machines-linux-sizes/)
     or Sizes for Virtual Machines (Windows)
     (https://azure.microsoft.com/documentation/articles/virtual-machines-windows-sizes/).
     Batch supports all Azure VM sizes except STANDARD_A0 and those with
     premium storage (STANDARD_GS, STANDARD_DS, and STANDARD_DSV2 series).
    :type vm_size: str
    :param cloud_service_configuration: The cloud service configuration for
     the pool. This property must be specified if the pool needs to be created
     with Azure PaaS VMs. This property and virtualMachineConfiguration are
     mutually exclusive and one of the properties must be specified. If neither
     is specified then the Batch service returns an error; if you are calling
     the REST API directly, the HTTP status code is 400 (Bad Request). This
     property cannot be specified if the Batch account was created with its
     poolAllocationMode property set to 'UserSubscription'.
    :type cloud_service_configuration: :class:`CloudServiceConfiguration
     <azure.batch.models.CloudServiceConfiguration>`
    :param virtual_machine_configuration: The virtual machine configuration
     for the pool. This property must be specified if the pool needs to be
     created with Azure IaaS VMs. This property and cloudServiceConfiguration
     are mutually exclusive and one of the properties must be specified. If
     neither is specified then the Batch service returns an error; if you are
     calling the REST API directly, the HTTP status code is 400 (Bad Request).
    :type virtual_machine_configuration: :class:`VirtualMachineConfiguration
     <azure.batch.models.VirtualMachineConfiguration>`
    :param max_tasks_per_node: The maximum number of tasks that can run
     concurrently on a single compute node in the pool. The default value is 1.
     The maximum value of this setting depends on the size of the compute nodes
     in the pool (the vmSize setting).
    :type max_tasks_per_node: int
    :param task_scheduling_policy: How tasks are distributed among compute
     nodes in the pool.
    :type task_scheduling_policy: :class:`TaskSchedulingPolicy
     <azure.batch.models.TaskSchedulingPolicy>`
    :param resize_timeout: The timeout for allocation of compute nodes to the
     pool. This timeout applies only to manual scaling; it has no effect when
     enableAutoScale is set to true. The default value is 15 minutes. The
     minimum value is 5 minutes. If you specify a value less than 5 minutes,
     the Batch service rejects the request with an error; if you are calling
     the REST API directly, the HTTP status code is 400 (Bad Request).
    :type resize_timeout: timedelta
    :param target_dedicated_nodes: The desired number of dedicated compute
     nodes in the pool. This property must not be specified if enableAutoScale
     is set to true. If enableAutoScale is set to false, then you must set
     either targetDedicatedNodes, targetLowPriorityNodes, or both.
    :type target_dedicated_nodes: int
    :param target_low_priority_nodes: The desired number of low-priority
     compute nodes in the pool. This property must not be specified if
     enableAutoScale is set to true. If enableAutoScale is set to false, then
     you must set either targetDedicatedNodes, targetLowPriorityNodes, or both.
    :type target_low_priority_nodes: int
    :param enable_auto_scale: Whether the pool size should automatically
     adjust over time. If false, at least one of targetDedicateNodes and
     targetLowPriorityNodes must be specified. If true, the autoScaleFormula
     element is required. The pool automatically resizes according to the
     formula. The default value is false.
    :type enable_auto_scale: bool
    :param auto_scale_formula: The formula for the desired number of compute
     nodes in the pool. This property must not be specified if enableAutoScale
     is set to false. It is required if enableAutoScale is set to true. The
     formula is checked for validity before the pool is created. If the formula
     is not valid, the Batch service rejects the request with detailed error
     information.
    :type auto_scale_formula: str
    :param auto_scale_evaluation_interval: The time interval at which to
     automatically adjust the pool size according to the autoscale formula. The
     default value is 15 minutes. The minimum and maximum value are 5 minutes
     and 168 hours respectively. If you specify a value less than 5 minutes or
     greater than 168 hours, the Batch service rejects the request with an
     invalid property value error; if you are calling the REST API directly,
     the HTTP status code is 400 (Bad Request).
    :type auto_scale_evaluation_interval: timedelta
    :param enable_inter_node_communication: Whether the pool permits direct
     communication between nodes. Enabling inter-node communication limits the
     maximum size of the pool due to deployment restrictions on the nodes of
     the pool. This may result in the pool not reaching its desired size. The
     default value is false.
    :type enable_inter_node_communication: bool
    :param network_configuration: The network configuration for the pool.
    :type network_configuration: :class:`NetworkConfiguration
     <azure.batch.models.NetworkConfiguration>`
    :param start_task: A task to run on each compute node as it joins the
     pool. The task runs when the node is added to the pool or when the node is
     restarted.
    :type start_task: :class:`StartTask <azure.batch.models.StartTask>`
    :param certificate_references: A list of certificates to be installed on
     each compute node in the pool. For Windows compute nodes, the Batch
     service installs the certificates to the specified certificate store and
     location. For Linux compute nodes, the certificates are stored in a
     directory inside the task working directory and an environment variable
     AZ_BATCH_CERTIFICATES_DIR is supplied to the task to query for this
     location. For certificates with visibility of 'remoteUser', a 'certs'
     directory is created in the user's home directory (e.g.,
     /home/{user-name}/certs) and certificates are placed in that directory.
    :type certificate_references: list of :class:`CertificateReference
     <azure.batch.models.CertificateReference>`
    :param application_package_references: The list of application packages to
     be installed on each compute node in the pool. This property is currently
     not supported on auto pools created with the virtualMachineConfiguration
     (IaaS) property.
    :type application_package_references: list of
     :class:`ApplicationPackageReference
     <azure.batch.models.ApplicationPackageReference>`
    :param application_licenses: The list of application licenses the Batch
     service will make available on each compute node in the pool. The list of
     application licenses must be a subset of available Batch service
     application licenses. If a license is requested which is not supported,
     pool creation will fail.
    :type application_licenses: list of str
    :param user_accounts: The list of user accounts to be created on each node
     in the pool.
    :type user_accounts: list of :class:`UserAccount
     <azure.batch.models.UserAccount>`
    :param metadata: A list of name-value pairs associated with the pool as
     metadata. The Batch service does not assign any meaning to metadata; it is
     solely for the use of user code.
    :type metadata: list of :class:`MetadataItem
     <azure.batch.models.MetadataItem>`
    """

    _validation = {
        'vm_size': {'required': True},
    }

    _attribute_map = {
        'display_name': {'key': 'displayName', 'type': 'str'},
        'vm_size': {'key': 'vmSize', 'type': 'str'},
        'cloud_service_configuration': {'key': 'cloudServiceConfiguration', 'type': 'CloudServiceConfiguration'},
        'virtual_machine_configuration': {'key': 'virtualMachineConfiguration', 'type': 'VirtualMachineConfiguration'},
        'max_tasks_per_node': {'key': 'maxTasksPerNode', 'type': 'int'},
        'task_scheduling_policy': {'key': 'taskSchedulingPolicy', 'type': 'TaskSchedulingPolicy'},
        'resize_timeout': {'key': 'resizeTimeout', 'type': 'duration'},
        'target_dedicated_nodes': {'key': 'targetDedicatedNodes', 'type': 'int'},
        'target_low_priority_nodes': {'key': 'targetLowPriorityNodes', 'type': 'int'},
        'enable_auto_scale': {'key': 'enableAutoScale', 'type': 'bool'},
        'auto_scale_formula': {'key': 'autoScaleFormula', 'type': 'str'},
        'auto_scale_evaluation_interval': {'key': 'autoScaleEvaluationInterval', 'type': 'duration'},
        'enable_inter_node_communication': {'key': 'enableInterNodeCommunication', 'type': 'bool'},
        'network_configuration': {'key': 'networkConfiguration', 'type': 'NetworkConfiguration'},
        'start_task': {'key': 'startTask', 'type': 'StartTask'},
        'certificate_references': {'key': 'certificateReferences', 'type': '[CertificateReference]'},
        'application_package_references': {'key': 'applicationPackageReferences', 'type': '[ApplicationPackageReference]'},
        'application_licenses': {'key': 'applicationLicenses', 'type': '[str]'},
        'user_accounts': {'key': 'userAccounts', 'type': '[UserAccount]'},
        'metadata': {'key': 'metadata', 'type': '[MetadataItem]'},
    }

    def __init__(self, vm_size, display_name=None, cloud_service_configuration=None, virtual_machine_configuration=None, max_tasks_per_node=None, task_scheduling_policy=None, resize_timeout=None, target_dedicated_nodes=None, target_low_priority_nodes=None, enable_auto_scale=None, auto_scale_formula=None, auto_scale_evaluation_interval=None, enable_inter_node_communication=None, network_configuration=None, start_task=None, certificate_references=None, application_package_references=None, application_licenses=None, user_accounts=None, metadata=None):
        self.display_name = display_name
        self.vm_size = vm_size
        self.cloud_service_configuration = cloud_service_configuration
        self.virtual_machine_configuration = virtual_machine_configuration
        self.max_tasks_per_node = max_tasks_per_node
        self.task_scheduling_policy = task_scheduling_policy
        self.resize_timeout = resize_timeout
        self.target_dedicated_nodes = target_dedicated_nodes
        self.target_low_priority_nodes = target_low_priority_nodes
        self.enable_auto_scale = enable_auto_scale
        self.auto_scale_formula = auto_scale_formula
        self.auto_scale_evaluation_interval = auto_scale_evaluation_interval
        self.enable_inter_node_communication = enable_inter_node_communication
        self.network_configuration = network_configuration
        self.start_task = start_task
        self.certificate_references = certificate_references
        self.application_package_references = application_package_references
        self.application_licenses = application_licenses
        self.user_accounts = user_accounts
        self.metadata = metadata


text:
class QComboBox;
class QDialogButtonBox;
class QLineEdit;
class QTextEdit;

class Project;
class Sequence;

class SequencePropertiesDialog:public QDialog
{
	Q_OBJECT

	public:

		SequencePropertiesDialog(Project *, Sequence *,QWidget* parent = 0, Qt::WindowFlags f = 0 );
		~SequencePropertiesDialog();

		QString structureFile();
		QString comment();
		int selectedChain();

	public slots:

		virtual void accept();

	private slots:

		void browseStructures();

	private:

		QLineEdit *nameEditor_,*structureEditor_;
		QTextEdit *commentEditor_;
		QDialogButtonBox *buttonBox_;
		QComboBox *selChain_;

		Sequence *seq_;
		Project  *project_;
		QString name_;
};

#endif


text:
@interface MLLoadableViewController : MLContainerViewController

@end


text:
import * as avalon from 'avalon2';

avalon.component('ms-upload-card', {
    template: require('./ms-upload-card.html'),
    defaults: {
        fileList: [],
        getTextClass(file) {
            switch (file.status) {
                case 'done': return 'text-primary';
                case 'uploading': return 'text-muted';
                case 'error': return 'text-danger';
            }
            return '';
        },
        onRemove: avalon.noop,
        del(file) {
            this.onRemove(file);
        }
    }
});


text:
/*
 * collection.h:  Garbage collection for handles
 *
 * Author:
 *	Dick Porter (dick@ximian.com)
 *
 * (C) 2004 Novell, Inc.
 */

#ifndef _WAPI_COLLECTION_H_
#define _WAPI_COLLECTION_H_

#include <glib.h>

G_BEGIN_DECLS

#define _WAPI_HANDLE_COLLECTION_UPDATE_INTERVAL		10
#define _WAPI_HANDLE_COLLECTION_EXPIRED_INTERVAL	60

#include <mono/io-layer/shared.h>

extern void _wapi_collection_init (void);
extern void _wapi_handle_collect (void);

G_END_DECLS

#endif /* _WAPI_COLLECTION_H_ */


text:
getTimestamp(){ date +"%s"; }
#getTimestamp(){ date +"%H%M%S"; }
#callTime=$(date +"%H%M%S")
callTime=$(getTimestamp)
#timeout=1
timeout=$1
contentRead=$(
  while read line
  do
    #if [ ! "$callTime" -lt $(( $(date +"%H%M%S") + "$timeout" )) ] break; fi  # Right idea, but wrong order ( I'm tired ;p ) nb: useful to know: valid syntax ;D
    #if [ ! $(date +"%H%M%S") -lt $(( $callTime + $timeout )) ]; then break; fi
    if [ ! $(getTimestamp) -lt $(( $callTime + $timeout )) ]; then break; fi
    echo "$line"
  done
)
echo 'read ended'

echo '=== content ==='
echo -n 'number of lines:'
echo "$contentRead" | wc -l
echo '=== BUFFER START ==='
echo -e "$contentRead"
echo '==== BUFFER END ===='

# GET / POST & content fetching
method="${contentRead:0:4}"
if [[ "$method" == "GET " ]]; then
  echo "METHOD: GET";
  firstLine="${contentRead%%$'\n*'}"
  data=$(echo "${firstLine:18:-9}" | base64 -d)
elif [[ "$method" == "POST" ]]; then
  echo "METHOD: POST";
  data=$(echo "${contentRead##$'*\n'}" | base64 -d)
else echo "UNKNOWN METHOD: $method";
fi

echo '=== DATA START ==='
echo "$data"
echo '==== DATA END ===='

exit 0


text:
@interface DoubleSeries : NSObject

@property(nonatomic, readonly) SCIGenericType xValues;

@property(nonatomic, readonly) SCIGenericType yValues;

@property(nonatomic, readonly) int size;

- (instancetype)initWithCapacity: (int) capacity;

- (void)addX: (double)x Y:(double)y;

- (void)clear;

- (SCIArrayController *)getXArray;

- (SCIArrayController *)getYArray;

@end


text:
#pragma once

#ifdef __cplusplus
extern "C" {
#endif // __cplusplus

    /** \defgroup capi C API */
    /*@{*/

    /** @name Spacer facilities */
    /*@{*/
    /**
        \brief Pose a query against the asserted rules at the given level.

        \code
           query ::= (exists (bound-vars) query)
                 |  literals
        \endcode

        query returns
        - \c Z3_L_FALSE if the query is unsatisfiable.
        - \c Z3_L_TRUE if the query is satisfiable. Obtain the answer by calling #Z3_fixedpoint_get_answer.
        - \c Z3_L_UNDEF if the query was interrupted, timed out or otherwise failed.

        def_API('Z3_fixedpoint_query_from_lvl', INT, (_in(CONTEXT), _in(FIXEDPOINT), _in(AST), _in(UINT)))
    */
    Z3_lbool Z3_API Z3_fixedpoint_query_from_lvl (Z3_context c,Z3_fixedpoint d, Z3_ast query, unsigned lvl);

     /**
       \brief Retrieve a bottom-up (from query) sequence of ground facts

       The previous call to #Z3_fixedpoint_query must have returned \c Z3_L_TRUE.

       def_API('Z3_fixedpoint_get_ground_sat_answer', AST, (_in(CONTEXT), _in(FIXEDPOINT)))
    */
    Z3_ast Z3_API Z3_fixedpoint_get_ground_sat_answer(Z3_context c,Z3_fixedpoint d);

    /**
       \brief Obtain the list of rules along the counterexample trace.

       def_API('Z3_fixedpoint_get_rules_along_trace', AST_VECTOR, (_in(CONTEXT), _in(FIXEDPOINT)))
    */
    Z3_ast_vector Z3_API Z3_fixedpoint_get_rules_along_trace(Z3_context c,Z3_fixedpoint d);

    /**
       \brief Obtain the list of rules along the counterexample trace.

       def_API('Z3_fixedpoint_get_rule_names_along_trace', SYMBOL, (_in(CONTEXT), _in(FIXEDPOINT)))
    */
    Z3_symbol Z3_API Z3_fixedpoint_get_rule_names_along_trace(Z3_context c,Z3_fixedpoint d);

    /**
       \brief Add an invariant for the predicate \c pred.
       Add an assumed invariant of predicate \c pred.

       Note: this functionality is Spacer specific.

       def_API('Z3_fixedpoint_add_invariant', VOID, (_in(CONTEXT), _in(FIXEDPOINT), _in(FUNC_DECL), _in(AST)))
    */
    void Z3_API Z3_fixedpoint_add_invariant(Z3_context c, Z3_fixedpoint d, Z3_func_decl pred, Z3_ast property);

    /**
       Retrieve reachable states of a predicate.
       Note: this functionality is Spacer specific.

       def_API('Z3_fixedpoint_get_reachable', AST, (_in(CONTEXT), _in(FIXEDPOINT), _in(FUNC_DECL)))
     */
    Z3_ast Z3_API Z3_fixedpoint_get_reachable(Z3_context c, Z3_fixedpoint d, Z3_func_decl pred);

    /**
       \brief Project variables given a model

       def_API('Z3_qe_model_project', AST, (_in(CONTEXT), _in(MODEL), _in(UINT), _in_array(2, APP), _in(AST)))
    */
    Z3_ast Z3_API Z3_qe_model_project
      (Z3_context c,
       Z3_model m,
       unsigned num_bounds,
       Z3_app const bound[],
       Z3_ast body);

    /**
       \brief Project variables given a model

       def_API('Z3_qe_model_project_skolem', AST, (_in(CONTEXT), _in(MODEL), _in(UINT), _in_array(2, APP), _in(AST), _in(AST_MAP)))
    */
    Z3_ast Z3_API Z3_qe_model_project_skolem
      (Z3_context c,
       Z3_model m,
       unsigned num_bounds,
       Z3_app const bound[],
       Z3_ast body,
       Z3_ast_map map);

    /**
       \brief Extrapolates a model of a formula

       def_API('Z3_model_extrapolate', AST, (_in(CONTEXT), _in(MODEL), _in(AST)))
    */
    Z3_ast Z3_API Z3_model_extrapolate
      (Z3_context c,
       Z3_model m,
       Z3_ast fml);

    /**
       \brief Best-effort quantifier elimination

       def_API ('Z3_qe_lite', AST, (_in(CONTEXT), _in(AST_VECTOR), _in(AST)))
    */
    Z3_ast Z3_API Z3_qe_lite
      (Z3_context c,
       Z3_ast_vector vars,
       Z3_ast body);

    /*@}*/
    /*@}*/

#ifdef __cplusplus
}
#endif // __cplusplus


text:
const express = require('express');
const router = express.Router();
const passport = require('passport');
const multer = require('multer');
const fs = require('fs');
const Gridfs = require('gridfs-stream');

const Mail = require('../mail.ts');

const jwt = require('express-jwt');

const mongoose = require('mongoose');

var mongoDriver = mongoose.mongo;
var db = mongoose.connection;

// TODO: allow for multiple file uploads
var upload = multer({ dest: 'tmp/'}).single('file');

/*var authCheck = jwt({
  secret: new Buffer('auth0secret'),
  audience: '1QKH2NdD18m2ddQ5kXCzDuJeYTdQk1eA'
});*/

// we'll authenticate users from here
router.use((req, res, next) => {
  //console.log(authCheck);
  if (req.isAuthenticated()) {
    console.log(req.user.mail + " logged in and is using the api");
    next();
  } else {
    console.log("You're not logged in yet.");
  }
});

/* GET api listing. */
router.get('/', (req, res) => {
  res.status(200).json('Successfully connected to API');
});

var Company = require('../models/company.ts');
var Course = require('../models/course.ts');
var Employee = require('../models/employee.ts');
var Ext_examiner = require('../models/ext_examiner.ts');
var Student = require('../models/student.ts');
var File = require('../models/file.ts');
var Project = require('../models/project.ts');

router.route('/sendMail')
  .post((req, res) => {
    var body = 'You received a message from ' + req.user.eduPersonPrincipalName + ':\n' + req.body.bodyText;
    Mail.sendMail(req.body.mail, req.body.subject, body);
    return res.status(200).send('Mail sent.');
  });

router.route('/projects/notify/:_id')
  .get((req,res) => {
    if(req.user.eduPersonAffiliation.includes('employee')) {
      Project.findOne({ _id : req.params._id}, (err, project) => {
        if (err) {
          res.status(500).send(err);
        } else {
          if (project.status == 'delivered' && project.file) {
            Employee.findOne({ user: project.examiner.user }, (err, examiner) => {
              Mail.sendMail(examiner.mail, 'Project submission of ' + project.title + ' is ready for evaluation',
              'Go to http:localhost:3000/projects/' + project._id + '/submission to download file');

              return res.status(200).send('Mail sent to ' + examiner.name);
            });
          } else {
            res.send("Could not find a submission for this project");
          }
        }
      });
    }
  });

// TODO: change name more appropriate to the fact that it's pending and completed projects
router.route('/projects/unreviewed')
  .get((req, res) => {
    if (req.user.eduPersonAffiliation.includes('employee')) {
      //console.log("trying to find all pending projects");
      Project.find({ $or: [{ status : 'pending' }, { submission : { $exists: true }}]}, (err, projects) => {
        //console.log('unreviewed projects');
        //onsole.log(projects);
        if (err) {
          return res.status(500).send(err);
        } else {
          return res.status(200).json(projects);
        }
      })
      .populate('course')
      .populate('proposer._id')
      .populate('responsible._id')
      .populate('advisor._id')
      .populate('examiner._id')
      .populate('student')
      .populate('file');
    } else {
      return res.send("You're not authorized to access this.");
    }
  });

router.route('/projects/:_id/submission')
  // Reads the file from database and creates a stream the client can use
  .get((req, res) => {
    var gfs = new Gridfs(db.db, mongoDriver);
    Project.findOne({ _id : req.params._id }, (err, project) => {
      if (err) {
        return res.status(500).send(err);
      } else {
        if (project.submission) {
          File.findOne({ _id : project.submission }, (err, file) => {
            if (err) {
              return res.send(err);
            } else {
              var readStream = gfs.createReadStream(file);
              // this will stream the file directly to the browser, adobe has a nice browser handler for pdfs
              console.log(readStream.pipe(res));
              //readStream.pipe(res);
            }
          });
        }
      }
    });
  })
  .post((req, res) => {
    var gfs = new Gridfs(db.db, mongoDriver);
    var date = new Date();
    Project.findOne({ _id : req.params._id }, (err, project) => {
      /* multer's upload uploads a file to a tmp folder on disk, we use
        gridfs-stream and fs to read the file here and write it to the database,
        we then delete the file from the tmp folder
      */
      Course.findOne({ _id: project.course }, (err, course) => {
        if (!course.deadlines.studentSubmit) {
          return res.status(500).send("Submission date has not yet been set.");
        } else if (Date.parse(course.deadlines.studentSubmit) > Date.parse(date)) {
          return res.send("Late submission!");
        } else {
          upload(req, res, (err) => {
            var writeStream = gfs.createWriteStream({
              filename: req.file.originalname
            });

            var readStream = fs.createReadStream('tmp/' + req.file.filename)
            // Deletes file from client tmp folder
              .on("end", () => {
                fs.unlink("tmp/" + req.file.filename, (err) => {
                  res.status(200).json(readStream.id);
                })
              })
              .on("err", () => {
                res.send("error uploading file");
              })
              // reads the input as it writes the output
              .pipe(writeStream);
              // saves the id reference of child file to parent project
              project.status = 'delivered';
              project.submission = readStream.id;
              project.save();
          });
        }
      });
    });
  });

router.route('/company')
  // get all companies
  .get((req, res) => {
    Company
    .find((err, companies) => {
      if (err) {
        res.status(500).send(err);
      } else {
        res.status(200).json(companies);
      }
    });
  })

  // create new company
  .post((req, res) => {
    // increments id to a new company
    Company.find((err, companies) => {
      var obj = req.body;
      var company = new Company(obj);

      var id = 0;
      companies.forEach((c) => {
        if (id < parseInt(c._id)) {
          id = parseInt(c._id);
        }
      });
      company._id = String(id + 1);

      company.save((err) => {
        if (err) {
          res.status(500).send(err);
        } else {
          res.status(200).json({ message: 'Your company has been created.'});
        }
      });
    });
  });

  router.route('/company/:name')
    .get((req,res) => {
      Company.findOne({ name: req.params.name }, (err, company) => {
        if (err) {
          return res.send(err);
        } else {
          return res.json(company);
        }
      });
    });

router.route('/course')
  // get all courses
  .get((req, res) => {
    Course
    .find((err, courses) => {
      if (err) {
        res.status(500).send(err);
      }
      res.status(200).json(courses);
    })
  });

router.route('/course/:_id')
  .get((req, res) => {
    Course.findOne({_id: req.params._id}, (err, course) => {
      if (err) {
        return res.status(500).send(err);
      } else {
        return res.status(200).json(course);
      }
    });
  })
  .put((req, res) => {
    if (req.user.eduPersonAffiliation.includes('employee')) {
      var obj = req.body;
      var course = new Course(obj);
      Course.findOneAndUpdate({_id: req.params._id}, course, (err) => {
        if (err) {
          return res.status(500).send(err);
        } else {
          return res.status(200).send(req.params._id + 'has been updated');
        }
      });
    }
  });

router.route('/employee')

  // get all employees

  .get((req, res) => {
    Employee
    .find((err, employees) => {
      if (err) {
        res.status(500).send(err);
      } else {
      res.status(200).json(employees);
    }
  });
  })

  // create new employee
  .post((req, res) => {
    var obj = req.body;
    var employee = new Employee(obj);
    employee.save((err) => {
      if (err) {
        res.status(500).send(err);
      } else {
      res.status(200).json({ message: 'Your employee has been created.'});
      }
    });
  });

  router.route('/employee/:name')
  // get a employee by name
  .get((req, res) => {
    Employee.findOne({ name : req.params.name }, (err, employee) => {
      if (err) {
        res.status(500).send(err);
      } else {
        res.status(200).json(employee);
      }
    })
  });

router.route('/ext_examiner')

  // get all ext_examiners
  .get((req, res) => {
    Ext_examiner
    .find((err, ext_examiners) => {
      if (err) {
        res.status(500).send(err);
      } else {
        res.status(200).json(ext_examiners);
      }
    });
  })

  // create new ext_examiner
  .post((req, res) => {
    var obj = req.body;
    var ext_examiner = new Ext_examiner(obj);
    console.log(ext_examiner);
    ext_examiner.save((err) => {
      if (err) {
        res.status(500).send(err);
      } else {
        res.status(200).json({ message: 'Your ext_examiner has been created.'});
      }
    });
  });

// returns a students project
router.route('/my_project')
  .get((req, res) => {
    if(req.user.eduPersonAffiliation.includes('student')) {
      // finds student based on his mail, so we can retrieve his id
      Student.findOne({ mail: req.user.mail }, (err, student) => {
        if(err) {
          return res.status(500).send(err);
        } else {
          Project
          // finds all the projects that are approved or projects related to the student by email
          .find({$or:[{ assigned: student._id }, { proposer: student.name } ] }, (err, projects) => {
            console.log(projects);
            if (err) {
              return res.status(500).send(err);
            } else {
              return res.status(200).json(projects);
            }
          })
          .populate('course')
          .populate('proposer._id')
          .populate('responsible._id')
          .populate('advisor._id')
          .populate('examiner._id')
          .populate('student')
        }
      });
    } else {
      return res.send("You're not authorized to access this.");
    }
  });

router.route('/projects')

  // get all projects
  .get((req, res) => {
    if(req.user.eduPersonAffiliation.includes('student')) {

      // finds student based on his mail, so we can retrieve his id
      Student.findOne({ mail: req.user.mail }, (err, student) => {
        if(err) {
          return res.status(500).send(err);
        } else {
          Project
          // finds all the projects that are approved or projects related to the student by email
          .find({$or:[{ status: 'unassigned' }, { student: student._id }]}, (err, projects) => {
            if (err) {
              return res.status(500).send(err);
            } else {
              return res.status(200).json(projects);
            }
          })
          .populate('course')
          .populate('proposer._id')
          .populate('responsible._id')
          .populate('advisor._id')
          .populate('examiner._id')
          .populate('student');
        }
      });

    }
    // return all projects if the user is an employee
    else if(req.user.eduPersonAffiliation.includes('employee')) {
      //console.log("trying to find all projects");
      Project
      .find((err, projects) => {
        if (err) {
          return res.status(500).send(err);
        } else {
          return res.status(200).json(projects);
        }
      })
      .populate('course')
      .populate('proposer._id')
      .populate('responsible._id')
      .populate('advisor._id')
      .populate('examiner._id')
      .populate('student')
    } else {
      console.log("not an employee or student");
      return res.send("Could not verify your affiliation.");
    }

  })

  // create new project
  .post((req, res) => {
    var obj = req.body;
    var project = new Project(obj);
    var date = new Date();
    project.Created = date;

    // increments id to a new project
    Project.find((err, projects) => {
      var id = 0;
      projects.forEach((p) => {
        if (id < p._id) {
          id = p._id;
        }
      });
      project._id = id + 1;

      Course.findOne({ _id: project.course }, (err, course) => {
        // creates a project with status unassigned for employees
        if(req.user.eduPersonAffiliation.includes('employee')) {
          project.status = 'unassigned'
          project.save((err) => {
            if (err) {
              res.status(500).send(err);
            } else {
              res.status(200).json({ message: 'Your project has been created.'});
            }
          });
        } else {
          // checks if student is submitting a project late or not.
          if (course.deadlines.studentSuggest) {
            return res.status(500).send("The server could not find a date.");
          } else if (Date.parse(course.deadlines.studentSuggest) < Date.parse(project.created)) {
            return res.send("the deadline for creating projects has passed");
          } else {
            project.status = 'pending';
            project.save((err) => {
              if (err) {
                res.status(500).send(err);
              } else {
                res.status(200).json({ message: 'Your project has been created.'});
              }
            });
          }
        }
      });
    });
  });

router.route('/projects/:_id')

  // get a project by id
  .get((req, res) => {

    Project.findOne({ _id : req.params._id }, (err, project) => {
      if (err) {
        res.status(500).send(err);
      } else {
        res.status(200).json(project);
      }
    })
    .populate('course')
    .populate('proposer._id')
    .populate('responsible._id')
    .populate('advisor._id')
    .populate('examiner._id')
    .populate('student')
    .populate('assigned')
    .populate('file');
  })

  // update a project by id
  .put((req, res) => {
    var obj = req.body;
    var resProject = new Project(obj);
    Project.findOne({ _id : resProject._id }, (err, project) =>{
      if (err) {
        res.status(500).send(err);
      } else {
        if ( req.user.eduPersonAffiliation.includes('student') && (resProject.status == 'assigned' && project.status == 'unassigned')){
          return res.send('Unauthorized access!');
        } else if(req.user.eduPersonAffiliation.includes('employee') && (resProject.status == 'assigned' && project.status == 'unassigned') && resProject.assigned[0] == null){
          return res.send('No students to assign the project to');
        } else {
          Project.findOneAndUpdate({ _id: resProject}, resProject, (err) => {
            if (err) {
              return res.send(err);
            } else {
              return res.status(200).json({ message: 'Your project has been updated.'});
            }
          });
        }
      }
    });
  })

  // delete a project by id
  .delete((req, res) => {
    var obj = req.body;
    var project = new Project(obj);

    Project.findOneAndRemove({ _id : project._id }, project, (err) => {
      if (err) {
        res.status(500).send(err);
      } else {
        res.status(200).json({ message: 'Your project has been deleted.'});
      }
    });
  });

router.route('/student')

  // get all students
  .get((req, res) => {
    Student
    .find((err, students) => {
      if (err) {
        res.status(500).send(err);
      } else {
        res.status(200).json(students);
      }
    });
  })

  // create new student
  .post((req, res) => {
    var obj = req.body;
    var student = new Student(obj);
    console.log(student);
    student.save((err) => {
      if (err) {
        res.status(500).send(err);
      } else {
        res.status(200).json({ message: 'Your student has been created.'});
      }
    });
  });

router.route('/student/:name')
  // get a student by name
  .get((req, res) => {
    Student.findOne({ name : req.params.name }, (err, student) => {
      if (err) {
        res.status(500).send(err);
      } else {
        res.status(200).json(student);
      }
    });
  });

  router.route('/student/byid/:_id')
  // get a student by id
  .get((req, res) => {
    console.log(req.params._id);
    Student.findOne({ _id : req.params._id }, (err, student) => {
      if (err) {
        res.status(500).send(err);
      } else {
        res.status(200).json(student);
      }
    });
  });

module.exports = router;


text:
            {{getWord('Create VM')}}

                {{getWord('Edit Server')}}

                {{getWord('Delete Server')}}

                {{getWord('Migrate Server')}}

                {{getWord('Refresh Server')}}

                {{getWord('Start VMs')}}

                {{getWord('Shutdown VMs')}}

                {{getWord('Force Shutdown VMs')}}


text:
package com.clicktravel.infrastructure.persistence.aws.dynamodb;

import static com.clicktravel.common.random.Randoms.randomString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.util.HashSet;
import java.util.Set;

import org.junit.Test;

import com.amazonaws.services.dynamodbv2.document.KeyConditions;
import com.amazonaws.services.dynamodbv2.document.RangeKeyCondition;
import com.clicktravel.cheddar.infrastructure.persistence.database.query.InvalidConditionOperatorException;
import com.clicktravel.cheddar.infrastructure.persistence.database.query.Operators;
import com.clicktravel.common.random.Randoms;
import com.clicktravel.common.validation.ValidationException;

public class RangeKeyConditionBuilderTest {

    @Test
    public void shouldBuildRangeKeyCondition_withAttributeNameConditionValueAndEqualComparisonOperator() {
        // Given
        final String attributeName = randomString();
        final String conditionValue = randomString();
        final Operators operator = Operators.EQUALS;

        // When
        final RangeKeyCondition rangeKeyCondition = RangeKeyConditionBuilder.build(attributeName, conditionValue,
                operator);

        // Then
        assertEquals(attributeName, rangeKeyCondition.getAttrName());
        assertTrue(rangeKeyCondition.getValues().length == 1);
        assertEquals(conditionValue, rangeKeyCondition.getValues()[0]);
        assertEquals(KeyConditions.EQ, rangeKeyCondition.getKeyCondition());
    }

    @Test
    public void shouldBuildRangeKeyCondition_withAttributeNameConditionValueAndLessThanOrEqualToComparisonOperator() {
        // Given
        final String attributeName = randomString();
        final String conditionValue = randomString();
        final Operators operator = Operators.LESS_THAN_OR_EQUALS;

        // When
        final RangeKeyCondition rangeKeyCondition = RangeKeyConditionBuilder.build(attributeName, conditionValue,
                operator);

        // Then
        assertEquals(attributeName, rangeKeyCondition.getAttrName());
        assertTrue(rangeKeyCondition.getValues().length == 1);
        assertEquals(conditionValue, rangeKeyCondition.getValues()[0]);
        assertEquals(KeyConditions.LE, rangeKeyCondition.getKeyCondition());
    }

    @Test
    public void shouldBuildRangeKeyCondition_withAttributeNameConditionValueAndGreaterThanOrEqualToComparisonOperator() {
        // Given
        final String attributeName = randomString();
        final String conditionValue = randomString();
        final Operators operator = Operators.GREATER_THAN_OR_EQUALS;

        // When
        final RangeKeyCondition rangeKeyCondition = RangeKeyConditionBuilder.build(attributeName, conditionValue,
                operator);

        // Then
        assertEquals(attributeName, rangeKeyCondition.getAttrName());
        assertTrue(rangeKeyCondition.getValues().length == 1);
        assertEquals(conditionValue, rangeKeyCondition.getValues()[0]);
        assertEquals(KeyConditions.GE, rangeKeyCondition.getKeyCondition());
    }

    @Test
    public void shouldNotBuildRangeKeyCondition_withInvalidComparisonOperator() {
        // Given
        final String attributeName = randomString();
        final String conditionValue = randomString();
        final Set<Operators> validOperators = new HashSet<>();
        validOperators.add(Operators.NOT_NULL);
        validOperators.add(Operators.NULL);
        final Operators operator = Randoms.randomEnumInSet(validOperators);

        // When
        InvalidConditionOperatorException expectedException = null;
        try {
            RangeKeyConditionBuilder.build(attributeName, conditionValue, operator);
        } catch (final InvalidConditionOperatorException e) {
            expectedException = e;
        }

        // Then
        assertNotNull(expectedException);
    }

    @Test
    public void shouldNotBuildRangeKeyCondition_withEmptyAttributeName() {
        // Given
        final String attributeName = "";
        final String conditionValue = randomString();
        final Set<Operators> invalidOperators = buildValidOperatorsSet();
        final Operators operator = Randoms.randomEnumInSet(invalidOperators);

        // When
        ValidationException expectedException = null;
        try {
            RangeKeyConditionBuilder.build(attributeName, conditionValue, operator);
        } catch (final ValidationException e) {
            expectedException = e;
        }

        // Then
        assertNotNull(expectedException);
        assertEquals("attributeName", expectedException.getFields()[0]);
    }

    @Test
    public void shouldNotBuildRangeKeyCondition_withNullAttributeName() {
        // Given
        final String attributeName = null;
        final String conditionValue = randomString();
        final Set<Operators> invalidOperators = buildValidOperatorsSet();
        final Operators operator = Randoms.randomEnumInSet(invalidOperators);

        // When
        ValidationException expectedException = null;
        try {
            RangeKeyConditionBuilder.build(attributeName, conditionValue, operator);
        } catch (final ValidationException e) {
            expectedException = e;
        }

        // Then
        assertNotNull(expectedException);
        assertEquals("attributeName", expectedException.getFields()[0]);
    }

    @Test
    public void shouldNotBuildRangeKeyCondition_withNullConditionValue() {
        // Given
        final String attributeName = randomString();
        final String conditionValue = null;
        final Set<Operators> invalidOperators = buildValidOperatorsSet();
        final Operators operator = Randoms.randomEnumInSet(invalidOperators);

        // When
        ValidationException expectedException = null;
        try {
            RangeKeyConditionBuilder.build(attributeName, conditionValue, operator);
        } catch (final ValidationException e) {
            expectedException = e;
        }

        // Then
        assertNotNull(expectedException);
        assertEquals("conditionValue", expectedException.getFields()[0]);
    }

    private Set<Operators> buildValidOperatorsSet() {
        final Set<Operators> invalidOperators = new HashSet<>();
        invalidOperators.add(Operators.EQUALS);
        invalidOperators.add(Operators.GREATER_THAN_OR_EQUALS);
        invalidOperators.add(Operators.LESS_THAN_OR_EQUALS);
        return invalidOperators;
    }
}


text: angular.module('app.services', ['app.service.login','app.service.firebase']);


text:
package mysql;

import java.util.ArrayList;

public class Polygon {
	ArrayList<Coordinate> coordinates;
	Polygon(ArrayList<Coordinate> points){
		this.coordinates = points;
	}
}


text:
using NUnit.Framework;
using Our.Umbraco.Ditto.Tests.Mocks;

namespace Our.Umbraco.Ditto.Tests
{
    [TestFixture]
    [Category("Processors")]
    public class PrefixedPropertyTests
    {
        [UmbracoProperties(Prefix = "Site", Recursive = true)]
        public class MyModel
        {
            public string Name { get; set; }

            public string Description { get; set; }

            public string Fallback { get; set; }

            [UmbracoProperty("UnprefixedProp")]
            public string UnprefixedProp { get; set; }
        }

        [Test]
        public void Prefixed_Properties_Can_Resolve()
        {
            var value1 = "Name";
            var value2 = "Description";
            var value3 = "Fallback";

            var content = new MockPublishedContent
            {
                Properties = new[]
                {
                    new MockPublishedContentProperty("siteName", value1),
                    new MockPublishedContentProperty("siteDescription", value2),
                    new MockPublishedContentProperty("fallback", value3)
                }
            };

            var converted = content.As<MyModel>();

            Assert.That(converted.Name, Is.EqualTo(value1));
            Assert.That(converted.Description, Is.EqualTo(value2));
            Assert.That(converted.Fallback, Is.EqualTo(value3));
        }

        [Test]
        public void Prefixed_Properties_Can_UmbracoPropertyAttribute_Override()
        {
            var value1 = "Site Unprefixed";
            var value2 = "Unprefixed";

            var content = new MockPublishedContent
            {
                Properties = new[]
                {
                    new MockPublishedContentProperty("siteUnprefixedProp", value1),
                    new MockPublishedContentProperty("unprefixedProp", value2)
                }
            };

            var converted = content.As<MyModel>();

            Assert.That(converted.UnprefixedProp, Is.EqualTo(value2));
        }

        [Test]
        public void Prefixed_Properties_Can_Resolve_Recursive()
        {
            var value = "Description";

            var childContent = new MockPublishedContent();

            var parentContent = new MockPublishedContent
            {
                Properties = new[] { new MockPublishedContentProperty("siteDescription", value) },
                Children = new[] { childContent }
            };

            childContent.Parent = parentContent;

            var converted = childContent.As<MyModel>();

            Assert.That(converted.Description, Is.EqualTo(value));
        }
    }
}


text:
<?php

/**
 * sfGuardUserGroup form.
 *
 * @package    sf_sandbox
 * @subpackage form
 * @author     Your name here
 * @version    SVN: $Id: sfDoctrinePluginFormTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class sfGuardUserGroupForm extends PluginsfGuardUserGroupForm
{
  public function configure()
  {
  }
}