text:
package generator

import examples.ExampleJson
import generator.Heuristics.PathVariable
import generator.Utils.Description
import io.apibuilder.spec.v0.models._
import io.apibuilder.postman.collection.v21.v0.{models => postman}
import models.attributes.PostmanAttributes
import play.api.Logging
import play.api.libs.json.Json

object PostmanItemBuilder extends Logging {

  /**
    * Builds a runnable Postman Item from ApiBuilder operation.
    * All fields are filled with example values generated by {{ExampleJson}}.
    *
    * @param operation an input ApiBuilder operation
    * @param serviceSpecificHeaders a set of service-specific headers that will be added to the headers from the input operation
    * @param modelExampleProvider an example provider, which will be used to generate example values
    * @param pathVariableOpt optionally, provides a Postman variable for given path param
    * @return a runnable Postman Item
    */
  def build(
    operation: Operation,
    serviceSpecificHeaders: Seq[postman.Header],
    modelExampleProvider: ExampleJson,
    pathVariableOpt: Option[PathVariable]
  ): postman.Item = {
    val postmanRequest = buildPostmanRequest(operation, serviceSpecificHeaders, modelExampleProvider, pathVariableOpt)

    postman.Item(
      id = None,
      name = Some(s"${operation.method} ${operation.path}"),
      description = operation.description.map(Description(_)),
      request = postmanRequest,
      response = Some(buildExampleResponses(postmanRequest, operation, modelExampleProvider))
    )
  }

  private def buildPostmanRequest(
    operation: Operation,
    serviceSpecificHeaders: Seq[postman.Header],
    modelExampleProvider: ExampleJson,
    pathVariableOpt: Option[PathVariable]
  ): postman.Request = {

    val parameterMap = operation.parameters.groupBy(_.location)

    def getParameters(location: ParameterLocation): Seq[Parameter] =
      parameterMap.getOrElse(location, default = Seq.empty)

    def getDescription(p: Parameter): Option[String] =
      p.description.orElse(Some(s"Type: ${p.`type`}  | Required: ${p.required}"))

    val queryParams = getParameters(ParameterLocation.Query).map { p =>
      postman.QueryParam(
        key = Some(p.name),
        value = p.example.orElse(p.default),
        description = getDescription(p).map(Description(_)),
        disabled = Some(!p.required))
    }

    val headersFromParams = getParameters(ParameterLocation.Header).map { p =>
      postman.Header(
        key = p.name,
        value = p.example.orElse(p.default).getOrElse(""),
        description = getDescription(p).map(Description(_))
      )
    }

    val pathParams =
      getParameters(ParameterLocation.Path).map { p =>
        postman.Variable(
          key = Some(p.name),
          value = Some {
            if (pathVariableOpt.exists(_.name == p.name))
              pathVariableOpt.get.postmanVarRef
            else
              generatePathParamValue(p)
          },
          description = getDescription(p).map(Description(_)),
          disabled = Some(!p.required))
      }

    val postmanUrl = postman.Url(
      raw = Some(s"{{${PostmanGeneratorConstants.BaseUrl}}}" + operation.path),
      protocol = None,
      host = Some(Seq(s"{{${PostmanGeneratorConstants.BaseUrl}}}")),
      path = Some(operation.path.stripPrefix("/").split('/').toSeq),
      query = Some(queryParams),
      variable = Some(pathParams)
    )

    val requestBodyOpt = operation.body.flatMap { body =>
      val jsonOpt = modelExampleProvider.sample(body.`type`)
      jsonOpt.map { json =>
        postman.Body(
          Some(Json.prettyPrint(json)),
          mode = Some(postman.BodyMode.Raw)
        )
      }
    }

    val headers: Seq[postman.Header] = operation.body.foldLeft(serviceSpecificHeaders ++ headersFromParams) { (headers, _)  =>
      headers :+ postman.Header("Content-Type", "application/json", description = Some(Description("Required to send JSON body")))
    }

    postman.Request(
      url = Option(postmanUrl),
      method = Option(postman.Method(operation.method.toString)),
      description = operation.description.map(Description(_)),
      auth = None,
      header = Some(headers),
      body = requestBodyOpt
    )
  }

  private def generatePathParamValue(parameter: Parameter): String = {
    val defaults = List(parameter.example, parameter.default).flatten
    defaults.headOption.getOrElse {
      PostmanAttributes.postmanVariableNameFrom(parameter).reference
    }
  }

  private def buildExampleResponses(
    postmanRequest: postman.Request,
    operation: Operation,
    modelExampleProvider: ExampleJson
  ): Seq[postman.Response] = {
    operation.responses.flatMap { response =>

      response.code match {
        case ResponseCodeInt(responseCode) =>

          val responseBodyExampleOpt =
            if (response.`type`.equalsIgnoreCase("unit")) None
            else modelExampleProvider.sample(response.`type`).map(Json.prettyPrint)

          val responseTypeSimpleName = extractSimpleName(response)

          val responseHeadersOpt = response.headers.map { headers =>
            headers.map { header =>
              postman.Header(
                key = header.name,
                value = header.default.getOrElse(""),
                disabled = None,
                description = header.description.map(Description(_)))
            }
          }

          val exampleResponse = postman.Response(
            id = None,
            name = Some(s"Example $responseCode - $responseTypeSimpleName"),
            originalRequest = Some(postmanRequest),
            responseTime = None,
            header = responseHeadersOpt,
            body = responseBodyExampleOpt,
            status = None,
            code = Some(responseCode)
          )
          Some(exampleResponse)

        case unrecognized =>
          logger.warn(s"Unrecognized response code in operation ${operation.method} ${operation.path} examples - $unrecognized. " +
            s"Dropping this example from the result Postman Collection")
          None
      }
    }
  }

  private def extractSimpleName(response: Response): String = {
    val typ = response.`type`
    val startIndex = typ.lastIndexOf('.') + 1
    typ.slice(startIndex, typ.length)
  }

}


text:
require 'spec_helper'

describe Weeler::TranslationsController, type: :controller do

  before do
    routes.draw do
      mount_weeler_at "/weeler"
    end
  end

  describe "GET #index" do
    before do
      FactoryBot.create(:translation, key: 'foo.bar')
      FactoryBot.create(:translation, key: 'bar.foo')
    end

    it "list translations" do
      get :index
      expect(assigns(:translations).size).to eq(2)
    end
  end

  describe "#create" do
    it "creates translation in DB" do
      expect(I18n.t("title", locale: :en)).to eq("Title")
      I18n::Backend::Weeler::Translation.delete_all

      post :create, params: { i18n_backend_weeler_translation: FactoryBot.attributes_for(:translation) }

      expect(I18n.t("title", locale: :en)).to eq("This is weeler")
    end

    it "doesnt create a duplicate key" do
      I18n::Backend::Weeler::Translation.delete_all

      post :create, params: { i18n_backend_weeler_translation: {locale: "en", key: "no.dup.title", value: "This is weeler"} }
      expect(I18n.t("no.dup.title", locale: :en)).to eq("This is weeler")

      post :create, params: { i18n_backend_weeler_translation: {locale: "en", key: "no.dup.title", value: "This is weeler"} }
      expect(response).to render_template(:edit)
    end
  end

  describe "PUT #update" do
    it "update translation in DB" do
      I18n::Backend::Weeler::Translation.delete_all
      translation = FactoryBot.create(:translation, key: 'foo.updated', value: nil)

      put "update", params: { id: translation.id, i18n_backend_weeler_translation: {value: "Updated weeler!"} }
      expect(I18n.t("foo.updated", locale: :en)).to eq("Updated weeler!")
    end

    it "dont updates if key is empty" do
      I18n::Backend::Weeler::Translation.delete_all
      translation = FactoryBot.create(:translation, key: 'foo.updated', value: nil)

      put "update", params: { id: translation.id, i18n_backend_weeler_translation: {value: "Updated weeler!", key: nil} }
      expect(response).to render_template(:edit)
    end
  end

  describe "GET #new" do
    it "retern new translation form" do
      get "new"
      expect(response).to render_template(:new)
    end
  end

  describe "GET #edit" do
    it "retern edit translation form" do
      translation = FactoryBot.create(:translation, key: 'foo.updated', value: nil)
      get "edit", params: { id: translation.id }
      expect(response).to render_template(:edit)
    end
  end

  describe "DELETE #destroy" do
    it "destroys translation" do
      translation = FactoryBot.create(:translation, key: 'foo.removing', value: "Bla bla")
      delete "destroy", params: { id: translation.id }

      expect(I18n.t("foo.removing", locale: :en)).to eq("Removing") # Returns empty key
    end
  end

  describe "POST #import" do
    context "submiting a file" do
      it "adds translation from files" do
        I18n::Backend::Weeler::Translation.delete_all
        Setting.i18n_updated_at = Time.current

        expect(I18n.t("welcome.title", locale: :en)).to eq("Title") # Missing translation
        post "import", params: { file: fixture_file_upload(File.dirname(__FILE__) + '/../fixtures/test.xlsx', 'application/xlsx') }
        expect(I18n.t("welcome.title", locale: :en)).to eq("EN welcome")
      end
    end

    context "no file" do
      it "redirects back" do
        post "import"
        expect(response).to redirect_to :weeler_translations
      end

    end

  end

  describe "GET #export" do
    it "retursns translation file" do
      get "export", format: :xlsx
      expect(response.headers["Content-Type"]).to eq("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
      expect(response.headers["Content-Disposition"]).to eq("attachment; filename=\"translations.xlsx\"; filename*=UTF-8''translations.xlsx")
    end
  end

end

redpajama_set_name: RedPajamaGithub


text:
package org.aesh.command.impl.invocation;

import java.io.Console;
import java.io.IOException;

import org.aesh.command.CommandException;
import org.aesh.command.CommandNotFoundException;
import org.aesh.command.CommandRuntime;
import org.aesh.command.Executor;
import org.aesh.command.container.CommandContainer;
import org.aesh.command.shell.Shell;
import org.aesh.command.invocation.CommandInvocation;
import org.aesh.command.invocation.CommandInvocationConfiguration;
import org.aesh.command.parser.CommandLineParserException;
import org.aesh.command.validator.CommandValidatorException;
import org.aesh.command.validator.OptionValidatorException;
import org.aesh.readline.Prompt;
import org.aesh.readline.action.KeyAction;
import org.aesh.readline.terminal.Key;
import org.aesh.readline.util.Parser;
import org.aesh.terminal.tty.Size;
import org.aesh.terminal.utils.ANSI;

/**
 * @author Ståle W. Pedersen
 */
public class DefaultCommandInvocation implements CommandInvocation{

    private final Shell shell;

    private final CommandRuntime<DefaultCommandInvocation> processor;

    private final CommandInvocationConfiguration config;

    private final CommandContainer<DefaultCommandInvocation> commandContainer;

    public DefaultCommandInvocation(CommandRuntime< DefaultCommandInvocation> processor,
                                    CommandInvocationConfiguration config,
                                    CommandContainer<DefaultCommandInvocation> commandContainer,
                                    Shell shell) {
        this.processor = processor;
        this.config = config;
        this.commandContainer = commandContainer;
        if(shell != null)
            this.shell = shell;
        else
            this.shell = new DefaultShell();
    }

    @Override
    public Shell getShell() {
        return shell;
    }

    @Override
    public void setPrompt(Prompt prompt) {
    }

    @Override
    public Prompt getPrompt() {
        return null;
    }

    @Override
    public String getHelpInfo(String commandName) {
        return processor.commandInfo(commandName);
    }

    @Override
    public String getHelpInfo() {
        return commandContainer.getParser().parsedCommand().printHelp();
    }

    @Override
    public void stop() {

    }

    // XXX JFDENISE SHOULD BE REMOVED
    @Override
    public KeyAction input() {
        try {
            return getShell().read();
        }
        catch (InterruptedException ignored) {
        }
        return null;
    }

    @Override
    public String inputLine() {
        return inputLine(null);
    }

    @Override
    public String inputLine(Prompt prompt) {
        try {
            return getShell().readLine(prompt);
        }
        catch (InterruptedException ignored) {
        }
        return null;
    }

    @Override
    public void executeCommand(String input) throws CommandNotFoundException,
            CommandLineParserException,
            OptionValidatorException,
            CommandValidatorException,
            CommandException,
            InterruptedException,
            IOException {
        processor.executeCommand(input);
    }

    @Override
    public void print(String msg, boolean paging) {
        shell.write(msg, paging);
    }

    @Override
    public void println(String msg, boolean paging) {
        shell.writeln(msg, paging);
    }

    @Override
    public Executor<? extends CommandInvocation> buildExecutor(String line) throws CommandNotFoundException,
            CommandLineParserException,
            OptionValidatorException,
            CommandValidatorException,
            IOException {
        return processor.buildExecutor(line);
    }

    @Override
    public CommandInvocationConfiguration getConfiguration() {
        return config;
    }

    private static class DefaultShell implements Shell {

        @Override
        public void write(String out, boolean paging) {
            System.out.print(out);
        }

        @Override
        public void writeln(String out, boolean paging) {
            System.out.println(out);
        }

        @Override
        public void write(int[] out) {
            Console console = System.console();
            if(console != null) {
                console.writer().write(Parser.fromCodePoints(out));
                console.writer().flush();
            }
        }

        @Override
        public void write(char out) {
            System.out.println(out);
        }

        @Override
        public String readLine() {
            return readLine(new Prompt());
        }

        @Override
        public String readLine(Prompt prompt) {
            Console console = System.console();
            if(console != null) {
                if(prompt != null) {
                    console.writer().print(Parser.fromCodePoints(prompt.getANSI()));
                    console.writer().flush();
                    if (prompt.isMasking()) {
                        return new String(console.readPassword());
                    }
                }
                return console.readLine();
            }
            return null;
        }

        @Override
        public Key read() {
            return read(null);
        }

        @Override
        public Key read(Prompt prompt) {
            Console console = System.console();
            if(console != null) {
                try {
                    if(prompt != null) {
                        console.writer().print(Parser.fromCodePoints(prompt.getANSI()));
                        console.writer().flush();
                    }
                    int input = console.reader().read();
                    return Key.getKey(new int[]{input});
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        public boolean enableAlternateBuffer() {
            return false;
        }

        @Override
        public boolean enableMainBuffer() {
            return false;
        }

        @Override
        public Size size() {
            return new Size(1, -1);
        }

        @Override
        public void clear() {
            Console console = System.console();
            if(console != null) {
                console.writer().write(Parser.fromCodePoints(ANSI.CLEAR_SCREEN));
            }
        }
    }
}


text:
from __future__ import absolute_import

from fabric import colors
from fabric.api import local

from lib.base import (
    BGPContainer,
    CmdBuffer,
)

class BagpipeContainer(BGPContainer):

    SHARED_VOLUME = '/root/shared_volume'

    def __init__(self, name, asn, router_id,
                 ctn_image_name='yoshima/bagpipe-bgp'):
        super(BagpipeContainer, self).__init__(name, asn, router_id,
                                               ctn_image_name)
        self.shared_volumes.append((self.config_dir, self.SHARED_VOLUME))

    def run(self):
        super(BagpipeContainer, self).run()
        cmd = CmdBuffer(' ')
        cmd << 'docker exec'
        cmd << '{0} cp {1}/bgp.conf'.format(self.name, self.SHARED_VOLUME)
        cmd << '/etc/bagpipe-bgp/'
        local(str(cmd), capture=True)
        cmd = 'docker exec {0} service bagpipe-bgp start'.format(self.name)
        local(cmd, capture=True)

    def create_config(self):
        c = CmdBuffer()
        c << '[BGP]'
        if len(self.ip_addrs) > 0:
            c << 'local_address={0}'.format(self.ip_addrs[0][1].split('/')[0])
        for info in self.peers.values():
            c << 'peers={0}'.format(info['neigh_addr'].split('/')[0])
        c << 'my_as={0}'.format(self.asn)
        c << 'enable_rtc=True'
        c << '[API]'
        c << 'api_host=localhost'
        c << 'api_port=8082'
        c << '[DATAPLANE_DRIVER_IPVPN]'
        c << 'dataplane_driver = DummyDataplaneDriver'
        c << '[DATAPLANE_DRIVER_EVPN]'
        c << 'dataplane_driver = DummyDataplaneDriver'

        with open('{0}/bgp.conf'.format(self.config_dir), 'w') as f:
            print colors.yellow(str(c))
            f.writelines(str(c))

    def reload_config(self):
        cmd = CmdBuffer(' ')
        cmd << 'docker exec'
        cmd << '{0} cp {1}/bgp.conf'.format(self.name, self.SHARED_VOLUME)
        cmd << '/etc/bagpipe-bgp/'
        local(str(cmd), capture=True)
        cmd = 'docker exec {0} service bagpipe-bgp restart'.format(self.name)
        local(cmd, capture=True)

    def pipework(self, bridge, ip_addr, intf_name=""):
        super(BagpipeContainer, self).pipework(bridge, ip_addr, intf_name)
        self.create_config()
        if self.is_running:
            self.reload_config()


text: module Autograde; end


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

namespace ExcerciseSix
{
    class Program
    {
        static void Main()
        {
            var numbers = Console
                .ReadLine()
                .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                .Select(int.Parse)
                .ToList();

            var numberOccurrences = new Dictionary<int, int>();

            foreach (int number in numbers)
            {
                if (!numberOccurrences.ContainsKey(number))
                {
                    numberOccurrences.Add(number, 0);
                }

                numberOccurrences[number]++;
            }

            foreach (var number in numberOccurrences.Keys)
            {
                if (numberOccurrences[number] % 2 != 0)
                {
                    numbers.RemoveAll(x => x == number);
                }
            }

            Console.WriteLine(string.Join(" ", numbers));
        }
    }
}


text:
package org.metacsp.sensing;

import org.metacsp.multi.allenInterval.AllenIntervalConstraint;

import cern.colt.Arrays;

public class NetworkMaintenanceError extends Error {

	private static final long serialVersionUID = -5616267862743820271L;

	public NetworkMaintenanceError(AllenIntervalConstraint ... con) {
		super("Cannot add maintenance constraint(s) " + Arrays.toString(con));
	}

	public NetworkMaintenanceError(long timeNow, long timeSensor) {
		super("Cannot add maintenance constraint(s) because sensor value is ahead by " + (timeSensor - timeNow));
	}

}