text:
using System;
using System.Linq;
using System.Messaging;
using System.Threading;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
using Castle.Windsor.Configuration.Interpreters;
using Rhino.ServiceBus.Impl;
using Rhino.ServiceBus.Internal;
using Rhino.ServiceBus.LoadBalancer;
using Rhino.ServiceBus.Messages;
using Rhino.ServiceBus.Msmq;
using Xunit;

namespace Rhino.ServiceBus.Tests.LoadBalancer
{
    public class With_accepting_work_queue : LoadBalancingTestBase
    {
        private readonly IWindsorContainer container;

        private const string acceptingWorkQueue = "msmq://localhost/test_queue.acceptingWork";
        private readonly string acceptingWorkQueuePath = MsmqUtil.GetQueuePath(new Uri(acceptingWorkQueue).ToEndpoint()).QueuePath;

        public With_accepting_work_queue()
        {
            if (MessageQueue.Exists(acceptingWorkQueuePath) == false)
                MessageQueue.Create(acceptingWorkQueuePath);
            var acceptingWork = new MessageQueue(acceptingWorkQueuePath);
            acceptingWork.Purge();

            var interpreter = new XmlInterpreter(@"LoadBalancer\BusWithAcceptingWorkLoadBalancer.config");
            container = new WindsorContainer(interpreter);
            container.Kernel.AddFacility("rhino.esb", new RhinoServiceBusFacility());

            container.AddComponent<MyHandler>();

            container.Register(
                Component.For<MsmqLoadBalancer>()
                    .DependsOn(new
                    {
                        threadCount = 1,
                        endpoint = new Uri(loadBalancerQueue),
                        transactional = TransactionalOptions.FigureItOut,
                        secondaryLoadBalancer = TestQueueUri2.Uri
                    })
                );

            container.Register(
               Component.For<MsmqReadyForWorkListener>()
                   .DependsOn(new
                   {
                       threadCount = 1,
                       endpoint = new Uri(acceptingWorkQueue),
                       transactional = TransactionalOptions.FigureItOut
                   })
               );

            container.Register(
               Component.For<MsmqSecondaryLoadBalancer>()
                   .DependsOn(new
                   {
                       threadCount = 1,
                       endpoint = TestQueueUri2.Uri,
                       primaryLoadBalancer = new Uri(loadBalancerQueue),
                       transactional = TransactionalOptions.FigureItOut
                   })
               );
        }

        [Fact]
        public void Can_send_message_through_load_balancer()
        {
            MyHandler.ResetEvent = new ManualResetEvent(false);

            using (var loadBalancer = container.Resolve<MsmqLoadBalancer>())
            using (var bus = container.Resolve<IStartableServiceBus>())
            {
                loadBalancer.Start();
                bus.Start();

                bus.Send(loadBalancer.Endpoint, "abcdefg");

                MyHandler.ResetEvent.WaitOne(TimeSpan.FromSeconds(30), false);
                Assert.True(
                        MyHandler.Message.ResponseQueue.Path.Contains(@"private$\test_queue")
                        );

                Assert.Equal("abcdefg", MyHandler.Value);

            }
        }

        [Fact]
        public void When_worker_tell_load_balancer_that_it_is_ready_the_worker_will_be_added_to_known_queues()
        {
            using (var loadBalancer = new MessageQueue(loadBalancerQueuePath + ";Workers", QueueAccessMode.SendAndReceive))
            {
                loadBalancer.Purge();
            }

            using (var loadBalancer = container.Resolve<MsmqLoadBalancer>())
            using (var bus = container.Resolve<IStartableServiceBus>())
            {
                loadBalancer.Start();
                bus.Start();

                using (var workers = new MessageQueue(loadBalancerQueuePath + ";Workers", QueueAccessMode.SendAndReceive))
                {
                    workers.Formatter = new XmlMessageFormatter(new[] { typeof(string) });
                    var knownWorker = workers.Peek(TimeSpan.FromSeconds(30));
                    Assert.Equal(bus.Endpoint.Uri.ToString(), knownWorker.Body.ToString());
                }

                Assert.True(loadBalancer.KnownWorkers.GetValues().Contains(TestQueueUri.Uri));
            }
        }

        [Fact]
        public void when_start_load_balancer_that_has_secondary_will_send_reroute_to_ready_for_work_queue_to_workers_to_relieve_secondary()
        {
            using (var loadBalancer = container.Resolve<MsmqLoadBalancer>())
            {
                loadBalancer.KnownWorkers.Add(TestQueueUri.Uri);
                loadBalancer.Start();

                var message = queue.Receive(TimeSpan.FromSeconds(5));
                var serializer = container.Resolve<IMessageSerializer>();
                var reroute = serializer.Deserialize(message.BodyStream)
                    .OfType<Reroute>().First();

                Assert.Equal(loadBalancer.ReadyForWorkListener.Endpoint.Uri, reroute.NewEndPoint);
                Assert.Equal(loadBalancer.ReadyForWorkListener.Endpoint.Uri, reroute.OriginalEndPoint);
            }
        }

        [Fact]
        public void When_secondary_starts_it_will_ask_primary_to_get_ready_to_work_uri()
        {
            using (var secondary = container.Resolve<MsmqSecondaryLoadBalancer>())
            {
                secondary.Start();

                using (var loadBalancerMsmqQueue = new MessageQueue(loadBalancerQueuePath))
                {
                    int tries = 5;
                    QueryReadyForWorkQueueUri query = null;
                    var serializer = container.Resolve<IMessageSerializer>();
                    while (query == null)
                    {
                        var message = loadBalancerMsmqQueue.Receive(TimeSpan.FromSeconds(30));
                        query = serializer.Deserialize(message.BodyStream)
                            .OfType<QueryReadyForWorkQueueUri>().FirstOrDefault();
                        Assert.True(tries > 0);
                        tries -= 1;
                    }

                    Assert.NotNull(query);
                }
            }
        }

        [Fact]
        public void When_secondary_takes_over_it_will_let_workers_know_that_it_took_over_and_reroute_to_ready_to_work_queue()
        {
            using (var primary = container.Resolve<MsmqLoadBalancer>())
            using (var secondary = container.Resolve<MsmqSecondaryLoadBalancer>())
            {
                primary.Start();
                secondary.TimeoutForHeartBeatFromPrimary = TimeSpan.FromMilliseconds(900);
                secondary.KnownWorkers.Add(TestQueueUri.Uri);
                secondary.KnownEndpoints.Add(TestQueueUri.Uri);//any worker is also endpoint

                var wait = new ManualResetEvent(false);
                secondary.TookOverAsActiveLoadBalancer += () => wait.Set();
                secondary.Start();

                Assert.True(wait.WaitOne());

                int tries = 5;
                var serializer = container.Resolve<IMessageSerializer>();
                Reroute reroute = null;
                while (reroute == null)
                {
                    var message = queue.Receive(TimeSpan.FromSeconds(30));
                    reroute = serializer.Deserialize(message.BodyStream)
                        .OfType<Reroute>().FirstOrDefault();
                    Assert.True(tries > 0);
                    tries -= 1;
                }

                Assert.Equal(secondary.PrimaryLoadBalancer, reroute.OriginalEndPoint);
                Assert.Equal(secondary.Endpoint.Uri, reroute.NewEndPoint);

                reroute = null;
                while (reroute == null)
                {
                    var message = queue.Receive(TimeSpan.FromSeconds(30));
                    reroute = serializer.Deserialize(message.BodyStream)
                        .OfType<Reroute>().FirstOrDefault();
                    Assert.True(tries > 0);
                    tries -= 1;
                }

                Assert.Equal(primary.ReadyForWorkListener.Endpoint.Uri, reroute.OriginalEndPoint);
                Assert.Equal(secondary.ReadyForWorkListener.Endpoint.Uri, reroute.NewEndPoint);
            }
        }

        public class MyHandler : ConsumerOf<string>
        {
            public static ManualResetEvent ResetEvent;
            public static string Value;
            public static Message Message;

            public void Consume(string message)
            {
                Message = MsmqTransport.MsmqCurrentMessageInformation.MsmqMessage;
                Value = message;
                ResetEvent.Set();
            }

        }

    }
}


text:
int main()
{
    ConfigINI *ini = new ConfigINI("test.ini");
    ini->setIntValue("section1", "intValue", 1);
    ini->setFloatValue("section1", "floatValue", 0.1);
    ini->setStringValue("section2", "stringValue", "hello, world");
    ini->setBoolValue("section2", "boolValue", true);
    ini->writeConfigFile();

    int intValue = ini->getIntValue("section1", "intValue");
    float floatValue = ini->getFloatValue("section1", "floatValue");
    const char *stringValue = ini->getStringValue("section2", "stringValue");
    bool boolValue = ini->getBoolValue("section2", "boolValue");

    cout<<"[section1]-intValue:\t"<<intValue<<endl;
    cout<<"[section1]-floatValue:\t"<<floatValue<<endl;
    cout<<"[section2]-stringValue:\t"<<stringValue<<endl;
    cout<<"[section2]-boolValue:\t"<<boolValue<<endl;

    delete ini;
    return 0;
}

redpajama_set_name: RedPajamaGithub


text:
package cl.uchile.dcc.cc5604.servlets.lifecycle;

import semantikos.core.IConceptManagerLocal;
import semantikos.model.Description;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

/**
 * Created by andres on 5/24/16.
 */
@WebServlet("findDescription")
public class DescriptionFinderServlet extends HttpServlet {

    @EJB
    private IConceptManagerLocal conceptManager;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        /* TODO: Recuperar el ID desde el request */
        int conceptID = Integer.parseInt(req.getParameter("ID_DESCRIPTION"));

        /* Se recupera las descripciones */
        ArrayList<Description> descriptions = conceptManager.findDescriptionByIDConcept(conceptID);

        // TODO: Escribir al response la descriion (setAttribute)

        for (int i = 0; i < descriptions.size(); i++) {
            System.out.println(descriptions.get(i).toString());
        }

        // TODO: Escribir el Servlet que tiene este mapping para mostrar la descripcion.
        req.getRequestDispatcher("showDescripcion").forward(req, resp);
    }
}


text:
package com.karumi.calendardatepicker;

import android.content.Context;
import android.util.Log;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import static java.util.Calendar.DAY_OF_MONTH;
import static java.util.Calendar.MONTH;
import static java.util.Calendar.YEAR;

/**
 *
 */
class CalendarDatePickerModel {

  private static final int MODE_SINGLE_SELECTION = 0;
  private static final int MODE_MULTIPLE_SELECTION = 1;
  private static final int MODE_RANGE_SELECTION = 2;

  private final Calendar calendar;
  private final SimpleDateFormat monthNameFormat;
  private final Locale locale;
  private final Calendar today;
  private SimpleDateFormat weekdayNameFormat;
  private Date currentDate;

  private List<Calendar> selectedDays = new ArrayList<Calendar>();
  private Calendar currentMonth;
  private int selectedMode = MODE_RANGE_SELECTION;

  private Calendar startRange;
  private Calendar endRange;

  CalendarDatePickerModel(Context context, Locale locale, Calendar today) {
    this.today = today;
    this.calendar = Calendar.getInstance(locale);
    this.currentMonth = Calendar.getInstance(locale);
    calendar.setTime(today.getTime());
    currentMonth.setTime(today.getTime());
    this.locale = locale;

    weekdayNameFormat =
        new SimpleDateFormat(context.getString(R.string.cdp_dayofweek_format), locale);
    monthNameFormat = new SimpleDateFormat(context.getString(R.string.cdp_month_format), locale);
  }

  public String getDayOfWeek(int position) {
    Calendar calendarDays = Calendar.getInstance(locale);
    int day = calendarDays.getFirstDayOfWeek() + position;
    calendar.set(Calendar.DAY_OF_WEEK, day);
    return weekdayNameFormat.format(calendar.getTime());
  }

  public void setToday(Date date) {
    currentDate = date;
    today.setTime(date);
    currentMonth.setTime(date);
    calendar.setTime(date);
  }

  public String getCurrentMonth() {
    return monthNameFormat.format(currentDate);
  }

  public Calendar getCalendar() {
    return calendar;
  }

  public void resetToCurrentDay() {
    calendar.setTime(currentDate);
  }

  public void nextMonth() {
    calendar.add(Calendar.MONTH, 1);
    currentDate = calendar.getTime();
    currentMonth.setTime(currentDate);
  }

  public void previousMonth() {
    calendar.add(Calendar.MONTH, -1);
    currentDate = calendar.getTime();
    currentMonth.setTime(currentDate);
  }

  public void firstOfMonth() {
    calendar.set(Calendar.DAY_OF_MONTH, 1);
  }

  public int getCalendarValue(int field) {
    return calendar.get(field);
  }

  public int getFirstDayOfWeek() {
    return calendar.getFirstDayOfWeek();
  }

  public void addCalendarDate(int field, int value) {
    calendar.add(field, value);
  }

  public DayModel getDay() {

    DayModel day = new DayModel();

    day.setDate(calendar.getTime());
    day.setDay(Integer.toString(calendar.get(Calendar.DAY_OF_MONTH)));

    if (selectedMode != MODE_RANGE_SELECTION) {
      if (containsSelectedDay(calendar)) {
        day.setSelected(true);
      }
    } else {
      if (sameDate(calendar, startRange)) {
        day.setRegionFirstDay(true);
      } else if (sameDate(calendar, endRange)) {
        day.setRegionLastDay(true);
      } else if ((startRange != null)
          && (endRange != null)
          && (calendar.after(startRange))
          && (calendar.before(endRange))) {
        day.setRegionMiddle(true);
      }
    }

    day.setCurrentMont(sameMonth(calendar, currentMonth));

    day.setToday(sameDate(calendar, today));

    return day;
  }

  private boolean sameMonth(Calendar calendar, Calendar selectedDate) {
    return calendar.get(MONTH) == selectedDate.get(MONTH) && calendar.get(YEAR) == selectedDate.get(
        YEAR);
  }

  private boolean sameDate(Calendar calendar, Calendar selectedDate) {
    if (selectedDate == null || calendar == null) {
      return false;
    }
    return calendar.get(MONTH) == selectedDate.get(MONTH) && calendar.get(YEAR) == selectedDate.get(
        YEAR) && calendar.get(DAY_OF_MONTH) == selectedDate.get(DAY_OF_MONTH);
  }

  public void daySelected(Date date) {
    Calendar calendarSelected = Calendar.getInstance();
    calendarSelected.setTime(date);

    if (selectedMode == MODE_SINGLE_SELECTION) {
      selectedSingleSelection(calendarSelected);
    } else if (selectedMode == MODE_MULTIPLE_SELECTION) {
      selectedMultipleSelection(calendarSelected);
    } else if (selectedMode == MODE_RANGE_SELECTION) {
      selectedRange(calendarSelected);
    }
  }

  private void selectedRange(Calendar calendarSelected) {
    if ((startRange != null) && (endRange != null)) {
      startRange = calendarSelected;
      endRange = null;
    } else {
      if ((startRange == null) || (calendarSelected.before(startRange))) {
        startRange = calendarSelected;
      } else {
        endRange = calendarSelected;
      }
    }
  }

  private void selectedSingleSelection(Calendar calendarSelected) {
    selectedDays.clear();
    selectedDays.add(calendarSelected);
  }

  private void selectedMultipleSelection(Calendar calendarSelected) {
    if (!containsSelectedDay(calendarSelected)) {
      selectedDays.add(calendarSelected);
    } else {
      int position = getSelectedDayIndex(calendarSelected);
      selectedDays.remove(position);
    }
  }

  private int getSelectedDayIndex(Calendar calendarSelected) {
    int postion = 0;
    for (Calendar selectedDay : selectedDays) {
      if (sameDate(calendarSelected, selectedDay)) {
        return postion;
      }
      postion++;
    }
    return -1;
  }

  private boolean containsSelectedDay(Calendar calendarSelected) {
    for (Calendar selectedDay : selectedDays) {
      if (sameDate(calendarSelected, selectedDay)) {
        return true;
      }
    }
    return false;
  }
}


text:
<?php

namespace Core\Lib;

use Core\Execute;
use Core\Factory;

/**
 * Class Hook
 *
 * @package Core\Lib
 */
class Hook extends Factory
{
    public App    $app;
    public Router $router;

    public array $before = [];
    public array $after  = [];

    /**
     * Hook constructor.
     */
    public function __construct()
    {
        $this->app    = App::new();
        $this->router = Router::new();
    }

    /**
     * Add hook fn before input_c
     *
     * @param string $input_c
     * @param string $hook_class
     * @param string $hook_method
     *
     * @return $this
     */
    public function addBefore(string $input_c, string $hook_class, string $hook_method): self
    {
        $this->before[$this->router->getCmd($input_c, true)][] = [$hook_class, $hook_method];

        unset($input_c, $hook_class, $hook_method);
        return $this;
    }

    /**
     * Add hook fn after input_c
     *
     * @param string $input_c
     * @param string $hook_class
     * @param string $hook_method
     *
     * @return $this
     */
    public function addAfter(string $input_c, string $hook_class, string $hook_method): self
    {
        $this->after[$this->router->getCmd($input_c, true)][] = [$hook_class, $hook_method];

        unset($input_c, $hook_class, $hook_method);
        return $this;
    }

    /**
     * Check hook pass status
     *
     * @param Execute $execute
     * @param string  $input_c
     * @param array   $hook_list
     *
     * @return bool
     */
    public function checkPass(Execute $execute, string $input_c, array $hook_list): bool
    {
        $fn_list = $this->getHook($input_c, $hook_list);

        foreach ($fn_list as $hook_fn) {
            if (!$this->callHook($execute, $hook_fn)) {
                unset($execute, $input_c, $hook_list, $fn_list, $hook_fn);
                return false;
            }
        }

        unset($execute, $input_c, $hook_list, $fn_list, $hook_fn);
        return true;
    }

    /**
     * Get hook list for input_c
     *
     * @param string $input_c
     * @param array  $h_list
     *
     * @return array
     */
    private function getHook(string $input_c, array $h_list): array
    {
        $fn_list = [];

        ksort($h_list);

        foreach ($h_list as $c_path => $c_hooks) {
            if (0 === strpos($input_c, $c_path)) {
                $fn_list = array_merge($fn_list, $c_hooks);
            }
        }

        unset($input_c, $h_list, $c_path, $c_hooks);
        return $fn_list;
    }

    /**
     * Call hook function
     *
     * @param Execute $execute
     * @param array   $hook_fn
     *
     * @return bool
     */
    private function callHook(Execute $execute, array $hook_fn): bool
    {
        try {
            $result = $execute->runScript($hook_fn[0], $hook_fn[1], implode('/', $hook_fn));

            unset($execute, $hook_fn);
            return (empty($result) || true === current($result));
        } catch (\Throwable $throwable) {
            $this->app->showDebug($throwable, true);
            unset($execute, $hook_fn, $throwable);
            return false;
        }
    }
}


text:
        <input id="password-search-box" type="search"
            i18n-values="placeholder:passwordSearchPlaceholder" incremental>

    <list id="saved-passwords-list" class="settings-list"></list>

    <list id="password-exceptions-list" class="settings-list"></list>

        <button id="password-manager-confirm" i18n-content="ok"></button>


text:
<?xml version="1.0" encoding="utf-8"?>
<CrawlItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Text>Probali smo kinesku hranu i odlično je bilo, Za 6! :)</Text>
  <Rating>6</Rating>
  <Source>http://pauza.hr/menu/meduza-catering-savica</Source>
</CrawlItem>


text:
package net.teamio.director;

public class ServerProxy extends CommonProxy {

	@Override
	public void registerKeyBindings() {
	}

	@Override
	public void registerClientTick() {

	}

}


text:
/* Zero prefix is ignored */
import java.util.*;
import java.io.*;
import static java.lang.Long.parseLong;

public class access_gk_prefix {
    static Scanner in;
    static PrintWriter out;
    Map<Long, Boolean> acl = new HashMap<Long, Boolean>();

    long prefix(long ip, long mask) {
        return (ip >> (32 - mask)) & ((1L << mask) - 1);
    }

    Boolean getDeepest(long ip, long mask) {
        for (long i = mask; i > 0; i--) {
            Boolean allow = acl.get(prefix(ip, i));
            if (allow != null) {
                System.out.println(i);
                return allow;
            }
        }
        return null;
    }

    public void nextNetwork(boolean allow) {
        String[] a = in.next().split("[./]");
        long ip = ((parseLong(a[0]) * 256 + parseLong(a[1])) * 256 + parseLong(a[2])) * 256 + parseLong(a[3]);
        long mask = a.length == 4 ? 32 : parseLong(a[4]);
        if (getDeepest(ip, mask) == null) {
            System.out.println("add " + Long.toString(ip, 2) + " " + Long.toString(prefix(ip, mask), 2));
            acl.put(prefix(ip, mask), allow);
        }
    }

    public long nextIp() {
        String[] a = in.next().split("[.]");
        return ((parseLong(a[0]) * 256 + parseLong(a[1])) * 256 + parseLong(a[2])) * 256 + parseLong(a[3]);
    }

    public void run() {
        int n = in.nextInt();
        for (int i = 0; i < n; i++) {
            boolean allow = in.next().equals("allow");
            in.next();
            nextNetwork(allow);
        }

        int m = in.nextInt();
        for (int i = 0; i < m; i++) {
            Boolean allow = getDeepest(nextIp(), 32);
            out.print(allow == null || allow ? 'A' : 'D');
        }
        out.println();
    }

    public static void main(String[] args) throws Exception {
        in = new Scanner(new File("access.in"));
        out = new PrintWriter("access.out");

        new access_gk_prefix().run();

        in.close();
        out.close();
    }
}


text:
class UsersController < ApplicationController

  hobo_user_controller

  auto_actions :all, :lifecycle, :except => :index

  show_action :dashboard, :tutorial, :pending, :unsubscribe, :kanban

  index_action :check_corporate_login

  # Allow only the omniauth_callback action to skip the condition that
  # we're logged in. my_login_required is defined in application_controller.rb.
  skip_before_filter :my_login_required, :only => :omniauth_callback

  after_filter :update_data, :only => :omniauth_callback

  before_filter :collect_azure_attributes, :only => :omniauth_callback

  include HoboOmniauth::Controller

  include RestController

  def check_corporate_login
    email = params[:email]
    domain = email.split("@").last if email.present? and email.include?("@")
    user = model.where(email_address: email) if domain.present?
    prov = AuthProvider.where(:email_domain => domain).first
    prov ||= AuthProvider.where(:company_id => UserCompany.unscoped.where(user_id: user.first.id).*.company_id).first if user.present?
    prov ||= AuthProvider.where(company_id: (CompanyEmailDomain.where(:domain => domain).*.company_id)).first
    user = user.present?
    exists = false
    if prov
      if prov.type == 'OpenidProvider' and user
        exists = true
        oi = prov.openid_url
        url = oi.gsub('{user}', user)
        render js: "window.location.href = '/auth/openid?openid_url=#{url}'"
      elsif prov.type == 'SamlProvider'
        exists = true
        render js: "window.location.href = '/auth/saml_#{prov.email_domain}'"
      else
        flash[:error] = "Unknown provider: " + prov.type.to_s
        render js: "window.location.href = '/'"
      end
    else
      @provider = {exists: exists, email: email}
      hobo_ajax_response
    end
  end

  def collect_azure_attributes
    if request.env["omniauth.auth"].present? && request.env["omniauth.auth"]["info"].present? && request.env["omniauth.auth"]["info"]["email"].nil?
      extra = request.env["omniauth.auth"].extra._?.raw_info.to_h
      if extra
        request.env["omniauth.auth"]["info"]["email"] ||= extra["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"]._?[0]
        request.env["omniauth.auth"]["info"]["first_name"] ||= extra["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname"]._?[0]
        request.env["omniauth.auth"]["info"]["last_name"] ||= extra["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname"]._?[0]
        request.env["omniauth.auth"]["info"]["name"] ||= extra["http://schemas.microsoft.com/identity/claims/displayname"]._?[0]
      end
    end
  end

  def create_auth_cookie
    cookies[:auth_token] = {:value => "#{current_user.remember_token} #{current_user.class.name}",
                            :expires => current_user.remember_token_expires_at, :domain => :all}
  end

  def accept_invitation
    begin
      transition_page_action :accept_invitation
    rescue Hobo::PermissionDeniedError => e
      unless request.xhr? || this.lifecycle.valid_key?
        render template: 'users/invalid_invitation_key'
      else
        fail e
      end
    end
  end

  def do_accept_invitation
    do_transition_action :accept_invitation do
      if valid?
        self.current_user = model.find(params[:id])
        self.current_user.from_invitation = true
        self.current_user.save
        redirect_to home_page
        log_event "Accept invitation"
      end
    end
  end

  def do_activate
    do_transition_action :activate do
      if valid?
        self.current_user = model.find(params[:id])
        redirect_to home_page
        log_event "Activate"
      end
    end
  end

  def do_resend_activation
    do_transition_action :resend_activation do
      flash.now[:notice] = I18n.translate('user.messages.activation_mail_resent')
      hobo_ajax_response
      log_event "Resend activation"
    end
  end

  def activate
    begin
      #self.this = find_instance
      transition_page_action :activate do
        @partner = self.this.partner
      end
    rescue Hobo::PermissionDeniedError => e
      unless request.xhr? || this.lifecycle.valid_key?
        if @this.state.to_s == 'active'
          flash[:info] = I18n.translate('user.messages.already_active') unless logged_in?
          redirect_to "/login"
        else
          render template: 'users/invalid_activation_key'
        end
      else
        fail e
      end
    end
  end

  def admin_only
    render :text => "Permission Denied", :status => 403 unless current_user.administrator?
  end

  def dashboard
    redirect_to current_user
  end

  def show
    begin
      ActiveRecord::Associations::Preloader.new.preload(self.this,
                                                        [:dashboard_tasks, :dashboard_indicators])
      raise Hobo::PermissionDeniedError if self.this.nil?
      self.this.all_active_user_companies_and_hoshins
      name = self.this.name.nil? ? self.this.email_address : self.this.name
      @page_title = I18n.translate('user.dashboard_for', :name => name,
                                   :default => 'Dashboard for ' + name)
      hobo_show
    rescue Hobo::PermissionDeniedError => e
      self.current_user = nil
      redirect_to "/login?force=true"
    end
  end

  def kanban
    @this = find_instance
    @lanes = Task::Lifecycle.states.keys
    @referenced_hoshins = {}
    [@this.backlog_tasks, @this.active_tasks, @this.completed_tasks, @this.discarded_tasks].each {|tasks|
      tasks.each {|t|
        @referenced_hoshins[t.area.hoshin_id] = t.area.hoshin unless @referenced_hoshins[t.area.hoshin_id]
      }
    }
    @referenced_hoshins = @referenced_hoshins.values
    if request.xhr?
      hobo_ajax_response
    end
  end

  def login
    unless params[:force] || request.post? && params[:login].nil?
      hobo_login do
        if performed?
          redirect_to home_page
        else
          true #continue normal hobo_login behavior
        end
      end
    end
  end

  def pending
    begin
      current_user.all_companies
      self.this = User.includes({:user_companies => {:company => :active_hoshins}}).preload([:pending_tasks, :pending_indicators])
                      .order('lower(companies.name) asc, lower(hoshins.name) asc').references(:company, :hoshin)
                      .user_find(current_user, params[:id])
      ActiveRecord::Associations::Preloader.new.preload(self.this, [:pending_tasks, :pending_indicators])
      @page_title = I18n.translate('user.pending_actions_for', :name => self.this.name,
                                   :default => 'Pending actions for ' + self.this.name)
    rescue Hobo::PermissionDeniedError => e
      self.current_user = nil
      redirect_to "/login?force=true"
    end
  end

  def unsubscribe
    @this = find_instance
  end

  def tutorial
    if params[:id].present?
      @this = User.unscoped.user_find(current_user, params[:id])
    else
      redirect_to current_user, action: :tutorial
    end
  end

  def logout_and_return
    logout_current_user
    redirect_to params["return_url"]
  end

  # Normally, users should be created via the user lifecycle, except
  #  for the initial user created via the form on the front screen on
  #  first run.  This method creates the initial user.
  def create
    hobo_create do
      if valid?
        self.current_user = this
        flash[:notice] = t("hobo.messages.you_are_site_admin", :default => "You are now the site administrator")
        redirect_to home_page
      end
    end
    people_set_with_event "Signup"
  end

  def update
    ajax = request.xhr? || !(request.headers['HTTP_X_REQUESTED_WITH'] !~ /XMLHttpRequest/i)

    self.this ||= find_instance

    if self.this.timezone.nil? && !cookies[:tz].nil?
      zone = cookies[:tz]
      zone = Hoshinplan::Timezone.get(zone)
      self.this.timezone = zone.name unless zone.nil?
    end
    if params[:user] && params[:user][:preferred_view]
      ajax = true
    end
    if params[:tutorial_step]
      step = params[:tutorial_step].to_i
      if step == 1
        self.this.tutorial_step << self.this.next_tutorial
      elsif step == -1
        self.this.tutorial_step.pop
      elsif step > 1
        self.this.tutorial_step = User.values_for_tutorial_step
      elsif step < -1
        self.this.tutorial_step = []
      end
      if !params[:user]
        params[:user] = {}
      end
      params[:user][:tutorial_step] = self.this.tutorial_step
      ajax = true
    end
    if params[:delete_image].present?
      self.this.image.clear
      self.this.save
      if ajax
        flash[:notice] = nil
        hobo_ajax_response
      else
        redirect_to current_user, :dgv => Time.now.to_i if valid? && current_user.signed_up?
        redirect_to home_page if current_user.nil?
      end
    else
      begin
        hobo_update do
          if ajax
            flash[:notice] = nil
            hobo_ajax_response
          else
            redirect_to current_user, :dgv => Time.now.to_i if valid? && current_user.signed_up?
            redirect_to home_page if current_user.nil?
          end
        end
      rescue Paperclip::Error => e
        if ajax
          render text: "Unrecognized image format", :status => 400
        else
          redirect_to current_user, :dgv => Time.now.to_i if valid?
        end
      end
    end
    people_set
  end

  def update_data
    auth = request.env["omniauth.auth"]
    provider = auth['provider']
    uid = auth['uid']
    email = auth['info']['email']
    firstName = auth['info']['firstName']
    lastName = auth['info']['lastName']
    firstName ||= auth['info']['first_name']
    lastName ||= auth['info']['last_name']
    current_user.delay.update_data_from_authorization(provider, uid, email, firstName, lastName, request.remote_ip, cookies[:tz], header_locale) if current_user.signed_up? && current_user.account_active?
  end

  def signup
    self.this = User.new
    self.this.language = header_locale
    if params[:slug]
      @partner = Partner.find_by_slug params[:slug]
      self.this.partner = @partner
    end
    hobo_signup
  end

  def do_signup
    existing = model.find_by_email_address(params[:user][:email_address]) if params[:user].present? && params[:user][:email_address].present?
    redirect_url = "/confirm-email"
    if params[:user][:partner_id].present?
      @partner = Partner.find_by_id(params[:user][:partner_id])
      redirect_url = "/" + @partner.slug + redirect_url
    end
    if existing.present? && (existing.state == 'invited' || existing.state == 'inactive')
      existing.lifecycle.resend_activation!(existing)
      flash[:notice] = ht(:"#{model.to_s.underscore}.messages.signup.success")
      redirect_to redirect_url
    else
      hobo_do_signup do
        if valid?
          if @partner
            self.this.partner = @partner
            self.this.trial_ends_at = Date.today + @partner.companies_trial_days
            self.this.save
          end
          people_set_with_event "Signup", self.this
          redirect_to redirect_url
        end
      end
    end
    session[:just_signed_up] = true
  end

  def sign_in(user)
    sign_user_in(user)
    log_event("Signin", {objid: self.this.id, email_address: self.this.email_address})
  end

  def sign_user_in(user, password = nil)
    params[:remember_me] = true
    if (password.nil?)
      super(user) {remember(user)}
    else
      super(user, password) {remember(user)}
    end
  end

  def remember(user)
    current_user.remember_me if user.account_active?
    create_auth_cookie if user.account_active?
    true
  end

  alias_method :original_omniauth_callback, :omniauth_callback

  def omniauth_callback
    email = request.env["omniauth.auth"]["info"]["email"]
    if (email.blank?)
      raise "Email was not present in SSO request"
    end
    existed = model.find_by_email_address(email).present?
    original_omniauth_callback
    if current_user.present? && !existed
      people_set_with_event "Signup"
    end
  end

  def omniauth
  end

  def destroy
    user_id = params[:id].to_i.to_s
    hobo_destroy do
      Mp.people_delete(user_id) if valid?
    end
  end
end


text:
'''
Created on 2016年5月14日

@author: Darren
'''
'''
Consider the number triangle shown below. Write a program that calculates the highest sum of numbers that can be passed on a route that starts at the top and ends somewhere on the base. Each step can go either diagonally down to the left or diagonally down to the right.

          7

        3   8

      8   1   0

    2   7   4   4

  4   5   2   6   5
In the sample above, the route from 7 to 3 to 8 to 7 to 5 produces the highest sum: 30.

PROGRAM NAME: numtri

INPUT FORMAT

The first line contains R (1 <= R <= 1000), the number of rows. Each subsequent line contains the integers for that particular row of the triangle. All the supplied integers are non-negative and no larger than 100.
SAMPLE INPUT (file numtri.in)

5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
OUTPUT FORMAT

A single line containing the largest sum using the traversal specified.
SAMPLE OUTPUT (file numtri.out)

30
'''

def load_data(file_name):
    file = open(file_name,"r",newline="\n")
    N=int(file.readline())
    data=[]
    for i in range(N):
        line=file.readline()
        line=line.strip().split(" ")
        line=list(map(int,line))
        data.append(line)
    return data

def numbri():
    data=load_data("numtri.in")
    for i in range(len(data)-2,-1,-1):
        for j in range(len(data[i])):
            data[i][j]+=max(data[i+1][j],data[i+1][j+1])
    return data[0][0]

print(numbri())


text:
<?php

namespace App\Containers\AppSection\Authentication\Tasks;

use App\Containers\AppSection\Authentication\Exceptions\LoginFailedException;
use App\Ship\Parents\Tasks\Task;
use GuzzleHttp\Utils;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;

class CallOAuthServerTask extends Task
{
    private const AUTH_ROUTE = '/v1/oauth/token';

    public function run(array $data, string $languageHeader = null): array
    {
        $authFullApiUrl = config('apiato.api.url') . self::AUTH_ROUTE;

        $headers = [
            'HTTP_ACCEPT' => 'application/json',
            'HTTP_ACCEPT_LANGUAGE' => $languageHeader ?? config('app.locale'),
        ];

        $request = Request::create($authFullApiUrl, 'POST', $data, [], [], $headers);

        $response = App::handle($request);

        $content = Utils::jsonDecode($response->getContent(), true);

        // If the internal request to the oauth token endpoint was not successful we throw an exception
        if (!$response->isSuccessful()) {
            throw new LoginFailedException($content['message'], $response->getStatusCode());
        }

        return $content;
    }
}


text:
require "spec_helper"
require "bond"

RSpec.describe Bond do
  include Bond

  describe "#bond" do
    let(:method_name) { :method_name }

    it "returns a Bond::Spy" do
      expect(bond(:arbitrary)).to be_a_kind_of(Bond::Spy)
    end

    it "responds to all method calls and records them" do
      my_spy = bond(:spy)
      my_spy.public_send(method_name)
      bond_did_you_receive?(my_spy, method_name)
    end

    it "fails the test when it didn't receive a method call" do
      expect {
        my_spy = bond(:spy)
        bond_did_you_receive?(my_spy, method_name)
      }.to raise_error("Expected to receive :#{method_name}")
    end
  end
end


text:
package br.eti.kinoshita.testlinkjavaapi.testcase;

import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import br.eti.kinoshita.testlinkjavaapi.BaseTest;
import br.eti.kinoshita.testlinkjavaapi.constants.ExecutionStatus;
import br.eti.kinoshita.testlinkjavaapi.model.ReportTCResultResponse;
import br.eti.kinoshita.testlinkjavaapi.util.TestLinkAPIException;

/**
 *

 *

 *
20101130 - BUGID: 3123764 - kinow - reportTCresult not returning
 * execution data

 *

 *

 *
 * @author Bruno P. Kinoshita - http://www.kinoshita.eti.br
 * @since
 */
public class TestReportTCResult extends BaseTest {

    @DataProvider(name = "buildData")
    public Object[][] createData() {
	return new Object[][] { { 4, 10, 1, "Sample build", "Build notes.", 2,
		"Post" } };
    }

    @Test(dataProvider = "buildData")
    public void testReportTCResult(Integer testCaseId, Integer testPlanId,
	    Integer buildId, String buildName, String notes,
	    Integer platformId, String platformName) {
	this.loadXMLRPCMockData("tl.reportTCResult.xml");

	ReportTCResultResponse response = null;
	try {
	    response = this.api.reportTCResult(testCaseId, null, testPlanId,
		    ExecutionStatus.FAILED, buildId, buildName, notes, true,
		    null, platformId, platformName, null, // TODO: Test custom
							  // fields!
		    true);
	} catch (TestLinkAPIException e) {
	    Assert.fail(e.getMessage(), e);
	}

	Assert.assertNotNull(response);

	Assert.assertTrue(response.getExecutionId() > 0);
    }

    @Test(dataProvider = "buildData")
    public void testSetTestCaseExecutionResult(Integer testCaseId,
	    Integer testPlanId, Integer buildId, String buildName,
	    String notes, Integer platformId, String platformName) {
	this.loadXMLRPCMockData("tl.reportTCResult.xml");

	ReportTCResultResponse response = null;
	try {
	    response = this.api.setTestCaseExecutionResult(testCaseId, null,
		    testPlanId, ExecutionStatus.PASSED, buildId, buildName,
		    notes, true, null, platformId, platformName, null, // TODO:
								       // Test
								       // custom
								       // fields!
		    true);
	} catch (TestLinkAPIException e) {
	    Assert.fail(e.getMessage(), e);
	}

	Assert.assertNotNull(response);

	Assert.assertTrue(response.getExecutionId() > 0);
    }

}


text:
extern "Java"
{
  namespace gnu
  {
    namespace java
    {
      namespace nio
      {
        namespace charset
        {
            class ByteCharset$2;
            class ByteCharset$Encoder;
        }
      }
    }
  }
}

class gnu::java::nio::charset::ByteCharset$2 : public ::gnu::java::nio::charset::ByteEncodeLoopHelper
{

public: // actually package-private
  ByteCharset$2(::gnu::java::nio::charset::ByteCharset$Encoder *);
public: // actually protected
  virtual jboolean isMappable(jchar);
  virtual jbyte mapToByte(jchar);
public: // actually package-private
  ::gnu::java::nio::charset::ByteCharset$Encoder * __attribute__((aligned(__alignof__( ::gnu::java::nio::charset::ByteEncodeLoopHelper)))) this$1;
public:
  static ::java::lang::Class class$;
};

#endif // __gnu_java_nio_charset_ByteCharset$2__


text:
/**
 * Support and FAQ: visit Atmel Support
 */
#ifndef CONF_SLEEPMGR_H
#define CONF_SLEEPMGR_H

#define CONFIG_SLEEPMGR_ENABLE

#endif /* CONF_SLEEPMGR_H */


text:
namespace ash {

// BubbleContentsView ---------------------------------------------------------

// A class which creates the content of the bubble: The buttons, and the label.
class BubbleContentsView : public views::View {
 public:
  BubbleContentsView(MaximizeBubbleControllerBubble* bubble,
                     SnapType initial_snap_type);
  virtual ~BubbleContentsView();

  // Set the label content to reflect the currently selected |snap_type|.
  // This function can be executed through the frame maximize button as well as
  // through hover operations.
  void SetSnapType(SnapType snap_type);

  // Added for unit test: Retrieve the button for an action.
  // |state| can be either SNAP_LEFT, SNAP_RIGHT or SNAP_MINIMIZE.
  views::CustomButton* GetButtonForUnitTest(SnapType state);

 private:
  // The owning class.
  MaximizeBubbleControllerBubble* bubble_;

  // The object which owns all the buttons.
  BubbleContentsButtonRow* buttons_view_;

  // The label object which shows the user the selected action.
  views::Label* label_view_;

  DISALLOW_COPY_AND_ASSIGN(BubbleContentsView);
};

BubbleContentsView::BubbleContentsView(
    MaximizeBubbleControllerBubble* bubble,
    SnapType initial_snap_type)
    : bubble_(bubble),
      buttons_view_(NULL),
      label_view_(NULL) {
  SetLayoutManager(new views::BoxLayout(
      views::BoxLayout::kVertical, 0, 0,
      MaximizeBubbleControllerBubble::kLayoutSpacing));
  set_background(views::Background::CreateSolidBackground(
      MaximizeBubbleControllerBubble::kBubbleBackgroundColor));

  buttons_view_ = new BubbleContentsButtonRow(bubble);
  AddChildView(buttons_view_);

  label_view_ = new views::Label();
  SetSnapType(initial_snap_type);
  label_view_->SetBackgroundColor(
      MaximizeBubbleControllerBubble::kBubbleBackgroundColor);
  const SkColor kBubbleTextColor = SK_ColorWHITE;
  label_view_->SetEnabledColor(kBubbleTextColor);
  const int kLabelSpacing = 4;
  label_view_->set_border(views::Border::CreateEmptyBorder(
      kLabelSpacing, 0, kLabelSpacing, 0));
  AddChildView(label_view_);
}

BubbleContentsView::~BubbleContentsView() {
}

// Set the label content to reflect the currently selected |snap_type|.
// This function can be executed through the frame maximize button as well as
// through hover operations.
void BubbleContentsView::SetSnapType(SnapType snap_type) {
  if (!bubble_->controller())
    return;

  ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
  int id = 0;
  switch (snap_type) {
    case SNAP_LEFT:
      id = IDS_ASH_SNAP_WINDOW_LEFT;
      break;
    case SNAP_RIGHT:
      id = IDS_ASH_SNAP_WINDOW_RIGHT;
      break;
    case SNAP_MAXIMIZE:
      DCHECK_NE(FRAME_STATE_FULL, bubble_->controller()->maximize_type());
      id = IDS_ASH_MAXIMIZE_WINDOW;
      break;
    case SNAP_MINIMIZE:
      id = IDS_ASH_MINIMIZE_WINDOW;
      break;
    case SNAP_RESTORE:
      DCHECK_NE(FRAME_STATE_NONE, bubble_->controller()->maximize_type());
      id = IDS_ASH_RESTORE_WINDOW;
      break;
    default:
      // If nothing is selected, we automatically select the click operation.
      id = bubble_->controller()->maximize_type() == FRAME_STATE_FULL ?
               IDS_ASH_RESTORE_WINDOW : IDS_ASH_MAXIMIZE_WINDOW;
      break;
  }
  label_view_->SetText(rb.GetLocalizedString(id));
}

views::CustomButton* BubbleContentsView::GetButtonForUnitTest(SnapType state) {
  return buttons_view_->GetButtonForUnitTest(state);
}

// MaximizeBubbleBorder -------------------------------------------------------

namespace {

const int kLineWidth = 1;
const int kArrowHeight = 10;
const int kArrowWidth = 20;

}  // namespace

class MaximizeBubbleBorder : public views::BubbleBorder {
 public:
  MaximizeBubbleBorder(views::View* content_view, views::View* anchor);

  virtual ~MaximizeBubbleBorder() {}

  // Get the mouse active area of the window.
  void GetMask(gfx::Path* mask);

  // views::BubbleBorder:
  virtual gfx::Rect GetBounds(const gfx::Rect& position_relative_to,
                              const gfx::Size& contents_size) const OVERRIDE;
  virtual void Paint(const views::View& view, gfx::Canvas* canvas) OVERRIDE;
  virtual gfx::Size GetMinimumSize() const OVERRIDE;

 private:
  // Note: Animations can continue after then main window frame was destroyed.
  // To avoid this problem, the owning screen metrics get extracted upon
  // creation.
  gfx::Size anchor_size_;
  gfx::Point anchor_screen_origin_;
  views::View* content_view_;

  DISALLOW_COPY_AND_ASSIGN(MaximizeBubbleBorder);
};

MaximizeBubbleBorder::MaximizeBubbleBorder(views::View* content_view,
                                           views::View* anchor)
    : views::BubbleBorder(
          views::BubbleBorder::TOP_RIGHT, views::BubbleBorder::NO_SHADOW,
          MaximizeBubbleControllerBubble::kBubbleBackgroundColor),
      anchor_size_(anchor->size()),
      anchor_screen_origin_(0, 0),
      content_view_(content_view) {
  views::View::ConvertPointToScreen(anchor, &anchor_screen_origin_);
  set_alignment(views::BubbleBorder::ALIGN_EDGE_TO_ANCHOR_EDGE);
}

void MaximizeBubbleBorder::GetMask(gfx::Path* mask) {
  gfx::Insets inset = GetInsets();
  // Note: Even though the tip could be added as activatable, it is left out
  // since it would not change the action behavior in any way plus it makes
  // more sense to keep the focus on the underlying button for clicks.
  int left = inset.left() - kLineWidth;
  int right = inset.left() + content_view_->width() + kLineWidth;
  int top = inset.top() - kLineWidth;
  int bottom = inset.top() + content_view_->height() + kLineWidth;
  mask->moveTo(left, top);
  mask->lineTo(right, top);
  mask->lineTo(right, bottom);
  mask->lineTo(left, bottom);
  mask->lineTo(left, top);
  mask->close();
}

gfx::Rect MaximizeBubbleBorder::GetBounds(
    const gfx::Rect& position_relative_to,
    const gfx::Size& contents_size) const {
  gfx::Size border_size(contents_size);
  gfx::Insets insets = GetInsets();
  border_size.Enlarge(insets.width(), insets.height());

  // Position the bubble to center the box on the anchor.
  int x = (anchor_size_.width() - border_size.width()) / 2;
  // Position the bubble under the anchor, overlapping the arrow with it.
  int y = anchor_size_.height() - insets.top();

  gfx::Point view_origin(x + anchor_screen_origin_.x(),
                         y + anchor_screen_origin_.y());

  return gfx::Rect(view_origin, border_size);
}

void MaximizeBubbleBorder::Paint(const views::View& view, gfx::Canvas* canvas) {
  gfx::Insets inset = GetInsets();

  // Draw the border line around everything.
  int y = inset.top();
  // Top
  canvas->FillRect(gfx::Rect(inset.left(),
                             y - kLineWidth,
                             content_view_->width(),
                             kLineWidth),
                   MaximizeBubbleControllerBubble::kBubbleBackgroundColor);
  // Bottom
  canvas->FillRect(gfx::Rect(inset.left(),
                             y + content_view_->height(),
                             content_view_->width(),
                             kLineWidth),
                   MaximizeBubbleControllerBubble::kBubbleBackgroundColor);
  // Left
  canvas->FillRect(gfx::Rect(inset.left() - kLineWidth,
                             y - kLineWidth,
                             kLineWidth,
                             content_view_->height() + 2 * kLineWidth),
                   MaximizeBubbleControllerBubble::kBubbleBackgroundColor);
  // Right
  canvas->FillRect(gfx::Rect(inset.left() + content_view_->width(),
                             y - kLineWidth,
                             kLineWidth,
                             content_view_->height() + 2 * kLineWidth),
                   MaximizeBubbleControllerBubble::kBubbleBackgroundColor);

  // Draw the arrow afterwards covering the border.
  SkPath path;
  path.incReserve(4);
  // The center of the tip should be in the middle of the button.
  int tip_x = inset.left() + content_view_->width() / 2;
  int left_base_x = tip_x - kArrowWidth / 2;
  int left_base_y = y;
  int tip_y = left_base_y - kArrowHeight;
  path.moveTo(SkIntToScalar(left_base_x), SkIntToScalar(left_base_y));
  path.lineTo(SkIntToScalar(tip_x), SkIntToScalar(tip_y));
  path.lineTo(SkIntToScalar(left_base_x + kArrowWidth),
              SkIntToScalar(left_base_y));

  SkPaint paint;
  paint.setStyle(SkPaint::kFill_Style);
  paint.setColor(MaximizeBubbleControllerBubble::kBubbleBackgroundColor);
  canvas->DrawPath(path, paint);
}

gfx::Size MaximizeBubbleBorder::GetMinimumSize() const {
  return gfx::Size(kLineWidth * 2 + kArrowWidth,
                   std::max(kLineWidth, kArrowHeight) + kLineWidth);
}

// BubbleMouseWatcherHost -----------------------------------------------------

// The mouse watcher host which makes sure that the bubble does not get closed
// while the mouse cursor is over the maximize button or the balloon content.
// Note: This object gets destroyed when the MouseWatcher gets destroyed.
class BubbleMouseWatcherHost: public views::MouseWatcherHost {
 public:
  explicit BubbleMouseWatcherHost(MaximizeBubbleControllerBubble* bubble);
  virtual ~BubbleMouseWatcherHost();

  // views::MouseWatcherHost:
  virtual bool Contains(const gfx::Point& screen_point,
                        views::MouseWatcherHost::MouseEventType type) OVERRIDE;
 private:
  MaximizeBubbleControllerBubble* bubble_;

  DISALLOW_COPY_AND_ASSIGN(BubbleMouseWatcherHost);
};

BubbleMouseWatcherHost::BubbleMouseWatcherHost(
    MaximizeBubbleControllerBubble* bubble)
    : bubble_(bubble) {
}

BubbleMouseWatcherHost::~BubbleMouseWatcherHost() {
}

bool BubbleMouseWatcherHost::Contains(
    const gfx::Point& screen_point,
    views::MouseWatcherHost::MouseEventType type) {
  return bubble_->Contains(screen_point, type);
}

// MaximizeBubbleControllerBubble ---------------------------------------------

// static
const SkColor MaximizeBubbleControllerBubble::kBubbleBackgroundColor =
    0xFF141414;
const int MaximizeBubbleControllerBubble::kLayoutSpacing = -1;

MaximizeBubbleControllerBubble::MaximizeBubbleControllerBubble(
    MaximizeBubbleController* owner,
    int appearance_delay_ms,
    SnapType initial_snap_type)
    : views::BubbleDelegateView(owner->frame_maximize_button(),
                                views::BubbleBorder::TOP_RIGHT),
      shutting_down_(false),
      owner_(owner),
      bubble_widget_(NULL),
      contents_view_(NULL),
      bubble_border_(NULL),
      appearance_delay_ms_(appearance_delay_ms) {
  set_margins(gfx::Insets());

  // The window needs to be owned by the root so that the SnapSizer does not
  // cover it upon animation.
  aura::Window* parent = Shell::GetContainer(
      Shell::GetTargetRootWindow(),
      internal::kShellWindowId_ShelfContainer);
  set_parent_window(parent);

  set_notify_enter_exit_on_child(true);
  set_adjust_if_offscreen(false);
  SetPaintToLayer(true);
  set_color(kBubbleBackgroundColor);
  set_close_on_deactivate(false);
  set_background(
      views::Background::CreateSolidBackground(kBubbleBackgroundColor));

  SetLayoutManager(new views::BoxLayout(
      views::BoxLayout::kVertical, 0, 0, kLayoutSpacing));

  contents_view_ = new BubbleContentsView(this, initial_snap_type);
  AddChildView(contents_view_);

  // Note that the returned widget has an observer which points to our
  // functions.
  bubble_widget_ = views::BubbleDelegateView::CreateBubble(this);
  bubble_widget_->set_focus_on_creation(false);

  SetAlignment(views::BubbleBorder::ALIGN_EDGE_TO_ANCHOR_EDGE);
  bubble_widget_->non_client_view()->frame_view()->set_background(NULL);

  bubble_border_ = new MaximizeBubbleBorder(this, GetAnchorView());
  GetBubbleFrameView()->SetBubbleBorder(bubble_border_);
  GetBubbleFrameView()->set_background(NULL);

  // Recalculate size with new border.
  SizeToContents();

  if (!appearance_delay_ms_)
    GetWidget()->Show();
  else
    StartFade(true);

  ash::Shell::GetInstance()->metrics()->RecordUserMetricsAction(
      ash::UMA_WINDOW_MAXIMIZE_BUTTON_SHOW_BUBBLE);

  mouse_watcher_.reset(new views::MouseWatcher(
      new BubbleMouseWatcherHost(this),
      this));
  mouse_watcher_->Start();
}

MaximizeBubbleControllerBubble::~MaximizeBubbleControllerBubble() {
}

aura::Window* MaximizeBubbleControllerBubble::GetBubbleWindow() {
  return bubble_widget_ ? bubble_widget_->GetNativeWindow() : NULL;
}

gfx::Rect MaximizeBubbleControllerBubble::GetAnchorRect() {
  if (!owner_)
    return gfx::Rect();

  gfx::Rect anchor_rect =
      owner_->frame_maximize_button()->GetBoundsInScreen();
  return anchor_rect;
}

void MaximizeBubbleControllerBubble::AnimationProgressed(
    const gfx::Animation* animation) {
  // First do everything needed for the fade by calling the base function.
  BubbleDelegateView::AnimationProgressed(animation);
  // When fading in we are done.
  if (!shutting_down_)
    return;
  // Upon fade out an additional shift is required.
  const int kBubbleAnimationOffsetY = 5;
  int shift = animation->CurrentValueBetween(kBubbleAnimationOffsetY, 0);
  gfx::Rect rect = initial_position_;

  rect.set_y(rect.y() + shift);
  bubble_widget_->GetNativeWindow()->SetBounds(rect);
}

bool MaximizeBubbleControllerBubble::CanActivate() const {
  return false;
}

bool MaximizeBubbleControllerBubble::WidgetHasHitTestMask() const {
  return bubble_border_ != NULL;
}

void MaximizeBubbleControllerBubble::GetWidgetHitTestMask(
    gfx::Path* mask) const {
  DCHECK(mask);
  DCHECK(bubble_border_);
  bubble_border_->GetMask(mask);
}

void MaximizeBubbleControllerBubble::MouseMovedOutOfHost() {
  if (!owner_ || shutting_down_)
    return;
  // When we leave the bubble, we might be still be in gesture mode or over
  // the maximize button. So only close if none of the other cases apply.
  if (!owner_->frame_maximize_button()->is_snap_enabled()) {
    gfx::Point screen_location = Shell::GetScreen()->GetCursorScreenPoint();
    if (!owner_->frame_maximize_button()->GetBoundsInScreen().Contains(
        screen_location)) {
      owner_->RequestDestructionThroughOwner();
    }
  }
}

bool MaximizeBubbleControllerBubble::Contains(
    const gfx::Point& screen_point,
    views::MouseWatcherHost::MouseEventType type) {
  if (!owner_ || shutting_down_)
    return false;
  bool inside_button =
      owner_->frame_maximize_button()->GetBoundsInScreen().Contains(
          screen_point);
  if (!owner_->frame_maximize_button()->is_snap_enabled() && inside_button) {
    SetSnapType(controller()->maximize_type() == FRAME_STATE_FULL ?
        SNAP_RESTORE : SNAP_MAXIMIZE);
    return true;
  }
  // Check if either a gesture is taking place (=> bubble stays no matter what
  // the mouse does) or the mouse is over the maximize button or the bubble
  // content.
  return (owner_->frame_maximize_button()->is_snap_enabled() ||
          inside_button ||
          contents_view_->GetBoundsInScreen().Contains(screen_point));
}

gfx::Size MaximizeBubbleControllerBubble::GetPreferredSize() {
  return contents_view_->GetPreferredSize();
}

void MaximizeBubbleControllerBubble::OnWidgetDestroying(views::Widget* widget) {
  if (bubble_widget_ == widget) {
    mouse_watcher_->Stop();

    if (owner_) {
      // If the bubble destruction was triggered by some other external
      // influence then ourselves, the owner needs to be informed that the menu
      // is gone.
      shutting_down_ = true;
      owner_->RequestDestructionThroughOwner();
      owner_ = NULL;
    }
  }
  BubbleDelegateView::OnWidgetDestroying(widget);
}

void MaximizeBubbleControllerBubble::ControllerRequestsCloseAndDelete() {
  // This only gets called from the owning base class once it is deleted.
  if (shutting_down_)
    return;
  shutting_down_ = true;
  owner_ = NULL;

  // Close the widget asynchronously after the hide animation is finished.
  initial_position_ = bubble_widget_->GetNativeWindow()->bounds();
  if (!appearance_delay_ms_)
    bubble_widget_->CloseNow();
  else
    StartFade(false);
}

void MaximizeBubbleControllerBubble::SetSnapType(SnapType snap_type) {
  if (contents_view_)
    contents_view_->SetSnapType(snap_type);
}

views::CustomButton* MaximizeBubbleControllerBubble::GetButtonForUnitTest(
    SnapType state) {
  return contents_view_->GetButtonForUnitTest(state);
}

}  // namespace ash


text:
/*
 * ClientUser -- default implementation of user interface for p4 client
 *
 * This file implements the p4 client command line interface by defining
 * the methods of the ClientUser class.  This interface reads from stdin,
 * writes to stdout and stderr, and invokes the user's editor.
 */

# define NEED_FILE
# define NEED_STAT

# ifdef OS_NT
# include <process.h>
# define NEED_FCNTL
# ifdef __BORLANDC__
# define ARGVCAST(x)	((char * const *)(x))
# else
# define ARGVCAST(x)	(x)
# endif
# endif

# include <clientapi.h>
# include <clientprog.h>

# include <diff.h>
# include <enviro.h>
# include <echoctl.h>
# include <signaler.h>
# include <strops.h>
# include <runcmd.h>
# include <i18napi.h>
# include <charcvt.h>

# include <msgclient.h>
# include <msgserver.h>

# ifdef OS_MACOSX
# include <CoreFoundation/CoreFoundation.h>
# endif

int commandChaining = 0; // can be set by clientmain to support '-x run'

/*
 * ClientUser::~ClientUser() - virtual destructor holder
 */

ClientUser::~ClientUser()
{
}

/*
 * ClientUser::Prompt() - prompt the user, and wait for a response.
 */

void
ClientUser::Prompt( const StrPtr &msg, StrBuf &buf, int noEcho, Error *e )
{
	Prompt( msg, buf, noEcho, 0, e );
}

void
ClientUser::Prompt( const StrPtr &msg, StrBuf &buf, int noEcho, int noOutput, Error *e )
{
	if ( !noOutput )
	    printf( "%s", msg.Text() );

	fflush( stdout );
	int flushStdin = 1;
# ifdef OS_NT
	struct _stat statBuf;
	_fstat( _fileno( stdin ), &statBuf );
	if( statBuf.st_mode != _S_IFCHR )
	    flushStdin = 0;
# endif
	if( flushStdin )
	    fflush( stdin );

	// Turn off echoing

	NoEcho *setEcho = noEcho ? new NoEcho : 0;

	// Prompt'em

	buf.Clear();
	char *b = buf.Alloc( 2048 );

	if( !fgets( b, 2048, stdin ) )
	{
	    e->Set( MsgClient::Eof );
	    buf.SetEnd( b );
	}
	else
	{
	    // Set end and truncate any newline

	    buf.SetEnd( b += strlen( b ) );

# ifdef USE_CR
	    /*
 	     * Codewarrior (7.0?) oddity:
 	     *	fprintf to file translates \n (10) -> \r.
 	     *	fgets from file translates \n (10) <- \r.
 	     *	fprintf to console translates \n (10) -> newline on screen.
 	     *	fgets from stdin DOES NOT translate "enter".
 	     */

	    if( buf.Length() && buf.End()[ -1 ] == '\r' )
	    	buf.End()[ -1 ] = '\n';
# endif

	    if( buf.Length() && buf.End()[ -1 ] == '\n' )
	    {
		buf.SetEnd( buf.End() - 1 );
		buf.Terminate();
	    }

# ifdef OS_NT
	    if( buf.Length() && buf.End()[ -1 ] == '\r' )
	    {
	        buf.SetEnd( buf.End() - 1 );
	        buf.Terminate();
	    }
# endif
	}

	delete setEcho;
}

void
ClientUser::Help( const char *const *help )
{
	for( ; *help; help++ )
	    printf( "%s\n", *help );
}

void
ClientUser::HandleError( Error *err )
{
	// Dumb implementation is just to format
	// the error and call (old) OutputError.

	// API callers against 99.1+ servers can do better by
	// having HandleError probe 'err' directly for detail.

	StrBuf buf;
	err->Fmt( buf, EF_NEWLINE );
	OutputError( buf.Text() );
}

void
ClientUser::OutputError( const char *errBuf )
{
	fflush( stdout );
# ifdef OS_VMS
	// Note - VMS likes the args this way,  Mac the other,
	// UNIX doesn't care.
	//
	fwrite( errBuf, strlen( errBuf ), 1, stderr );
# else
	fwrite( errBuf, 1, strlen( errBuf ), stderr );
# endif
}

void
ClientUser::OutputInfo( char level, const char *data )
{
	if( quiet )
	    return;

	switch( level )
	{
	default:
	case '0': break;
	case '1': printf( "... " ); break;
	case '2': printf( "... ... " ); break;
	}

# ifdef OS_VMS
	// Note - VMS likes the args this way,  Mac the other,
	// UNIX doesn't care.
	//
	fwrite( data, strlen( data ), 1, stdout );
# else
	fwrite( data, 1, strlen( data ), stdout );
# endif
	fputc( '\n', stdout );
}

void
ClientUser::OutputText( const char *data, int length )
{

# ifdef OS_VMS
	// Note - VMS likes the args this way,  Mac the other,
	// UNIX doesn't care.
	//
	fwrite( data, length, 1, stdout );
# else
	fwrite( data, 1, length, stdout );
# endif
}

void
ClientUser::OutputBinary( const char *data, int length )
{
# ifdef OS_NT
	// we rely on a trailing zero length buffer to
	// tell us to turn off binary output.

	if( binaryStdout == !length )
	{
	    // toggle
	    binaryStdout = !!length;
	    fflush( stdout );
	    setmode( fileno( stdout ), binaryStdout ? O_BINARY : O_TEXT );
	}
# endif

	fwrite( data, 1, length, stdout );
}

void
ClientUser::InputData( StrBuf *buf, Error * )
{
	if( commandChaining )
	{
	    for( ;; )
	    {
	        StrBuf lb;
	        char *b = lb.Alloc( 2048 );

	        if( !fgets( b, 2048, stdin ) )
	            break;
		int l = strlen( b );
		if( l > 0 && l <= 3 &&
	            b[0] == '.' && ( b[1] == '\r' || b[1] == '\n' ) )
	            break;
		buf->Append( b );
	    }
	    buf->Terminate();
	    return;
	}

	int n;
	int size = FileSys::BufferSize();

	buf->Clear();

	do {
	    char *b = buf->Alloc( size );
	    n = read( 0, b, size );
	    buf->SetEnd( b + ( n >= 0 ? n : 0 ) );
	} while( n > 0 );

	buf->Terminate();
}

void
ClientUser::OutputStat( StrDict *varList )
{
	int i;
	StrBuf msg;
	StrRef var, val;

	// Dump out the variables, using the GetVar( x ) interface.
	// Don't display the function (duh), which is only relevant to rpc.
	// Don't display "specFormatted" which is only relevant to us.

	for( i = 0; varList->GetVar( i, var, val ); i++ )
	{
	    if( var == "func" || var == P4Tag::v_specFormatted ) continue;

	    // otherAction and otherOpen go at level 2, as per 99.1 + earlier

	    msg.Clear();
	    msg << var << " " << val;
	    char level = strncmp( var.Text(), "other", 5 ) ? '1' : '2';
	    OutputInfo( level, msg.Text() );
	}

	// blank line

	OutputInfo( '0', "" );
}

void
ClientUser::ErrorPause( char *errBuf, Error *e )
{
	StrBuf buf;
	OutputError( errBuf );
	Prompt( StrRef( "Hit return to continue..." ), buf, 0, e );

	if( editFile.Length() > 0 )
	{
	    FileSys *f = File( FST_UNICODE );
	    f->Set( editFile );
	    f->Unlink( e );
	    delete f;
	    editFile.Clear();
	}
}

void
ClientUser::Edit( FileSys *f1, Error *e )
{
	Edit( f1, enviro, e );

	editFile.Set( f1->Name() );
	f1->ClearDeleteOnClose();
}

void
ClientUser::Edit( FileSys *f1, Enviro * env, Error *e )
{
	// The presence of $SHELL on NT implies MKS, which has vi.
	// On VMS, we look for POSIX$SHELL - if set, we'll use vi.
	// Otherwise, EDIT.

	if( !f1->IsTextual() )
	{
	    e->Set( MsgClient::CantEdit ) << f1->Name();
	    return;
	}

	const char *editor = env->Get( "P4EDITOR" );

	if( !editor )
	    editor = env->Get( "EDITOR" );

# ifdef OS_NT
	if( !editor && !env->Get( "SHELL" ) )
	    editor = "notepad";
# endif

# ifdef OS_VMS
	if( !editor && !env->Get( "POSIX$SHELL" ) )
	    editor = "edit";
# endif

# ifdef OS_AS400
  if( !editor )
      editor = "edtf";
# endif

# ifdef OS_MACOSX

	// open flags:  -W wait
	//              -n create a new instance even if one is running
	//              -t use the default text editor
	//              -a use the specified editor

	if( !editor )
	  editor = "open -Wnt";

	// It's possible P4EDITOR is set to an actual gui application bundle.
	// Passing bundles to RunCmd won't execute them.
	// Instead, we can prefix it with "open" so the system
	// will open it and bring it forward

	FileSys * editorFile = FileSys::Create( FST_BINARY );
	editorFile->Set( editor );

	StrBuf openCommand("open -Wna ");

	// 1 - the file must exist

	if ( editorFile->Stat() & FSF_EXISTS )
	{

	    // 2 - in order to use 'open', the file must also point to a
	    //     bundled application. We check to see if there is a bundle
	    //     with an executable

	    CFURLRef bundleURL = CFURLCreateFromFileSystemRepresentation(NULL,
	                            (const UInt8 *)editor, strlen(editor), true);
	    CFBundleRef bundle = NULL;

	    if ( bundleURL && (bundle = CFBundleCreate(NULL, bundleURL)) )
	    {
	        CFURLRef executableURL = CFBundleCopyExecutableURL( bundle );
	        if ( executableURL )
	        {
	            CFRelease( executableURL );
	            openCommand.Append( "\"" );
	            openCommand.Append( editor );
	            openCommand.Append( "\"" );

	            editor = openCommand.Text();
	        }
	    }
	    if ( bundle )    CFRelease( bundle );
	    if ( bundleURL ) CFRelease( bundleURL );
	}

# endif

	// Bill Joy rules, Emacs maggots!

	if( !editor )
	    editor = "vi";

	RunCmd( editor, f1->Name(), 0, 0, 0, 0, 0, e );
}

void
ClientUser::Diff( FileSys *f1, FileSys *f2, int doPage, char *df, Error *e )
{
	Diff(f1, f2, NULL, doPage, df, e);
}

void
ClientUser::Diff( FileSys *f1, FileSys *f2, FileSys *fout, int doPage, char *df, Error *e )
{
	if( !f1->IsTextual() || !f2->IsTextual() )
	{
	    if( f1->Compare( f2, e ) )
	    {
		StrRef s( "(... files differ ...)\n" );
		if( fout )
		{
		    fout->Open( FOM_WRITE, e );
		    if( !e->Test() )
		    {
			fout->Write( s, e );
			fout->Close( e );
		    }
		}
		else
		{
		    printf( "%s", s.Text() );
		}
	    }
	    return;
	}

	// Call diff to do text compare

	const char *diffunicode = NULL;
	const char *diff = enviro->Get( "P4DIFF" );
	const char *pager = enviro->Get( "P4PAGER" );
	int charset = 0;
	int output  = outputCharset;

	if( !diff )
	    diff = enviro->Get( "DIFF" );

	if( f1->IsUnicode() )
	{
	    diffunicode = enviro->Get( "P4DIFFUNICODE" );
	    charset = f1->GetContentCharSetPriv();
	    if( !output && charset == f2->GetContentCharSetPriv() )
		output = charset;
	}

	if( !doPage )
	    pager = 0;
	else if( !pager )
	    pager = enviro->Get( "PAGER" );

	// Do our own diff
	// VMS ReadFile is busted.

# ifdef OS_VMS

	if( !diff )
	    diff = "diff";

# else /* not VMS */

	if( !diffunicode && !diff )
	{
	    // diff expects to read files in raw mode, we must
	    // create new FileSys to allow this.

	    FileSys *f1_bin = File( FST_BINARY );
	    FileSys *f2_bin = File( FST_BINARY );
	    int content_charset = f1->GetContentCharSetPriv();
	    int output_translate = 0;

	    if( f1->IsUnicode() &&
		content_charset != output &&
		content_charset != (int)CharSetApi::UTF_8 )
	    {
		// convert files to utf-8

		f1_bin->SetDeleteOnClose();
		f1_bin->MakeGlobalTemp();
		f2_bin->SetDeleteOnClose();
		f2_bin->MakeGlobalTemp();
		CharSetCvt *cvt;
		cvt = CharSetCvt::FindCvt(
		    (CharSetApi::CharSet)content_charset,
		    CharSetApi::UTF_8 );
		// error out if converter not found? - should not happen
		f1->Translator( cvt );
		f1->Copy( f1_bin, FPM_RW, e );

		if( !e->Test() )
		{
		    if( cvt ) cvt->ResetErr();
		    f2->Translator( cvt );
		    f2->Copy( f2_bin, FPM_RW, e );
		}
		delete cvt;

		if( output && output != (int)CharSetApi::UTF_8 )
		    output_translate = 1;
	    }
	    else
	    {
		if( f1->IsUnicode() &&
		    output != content_charset )
		    output_translate = 1;
		f1_bin->Set( f1->Name() );
		f2_bin->Set( f2->Name() );
	    }

	    if( !e->Test() )
	    {
		DiffFlags flags( df );
# ifndef OS_NEXT
		::
# endif
		Diff d;
		FileSys *t = NULL;

		d.SetInput( f1_bin, f2_bin, flags, e );
		int fileError = e->Test();

		if( !fileError || flags.type == DiffFlags::Unified )
		{
		    if( fout )
		    {
			t = fout;
			d.SetOutput( t->Name(), e );
		    }
		    else if( pager || output_translate )
		    {
			// this does the work of FileSys::CreateGlobalTemp but
			// uses the client user object's FileSys create method
			t = File( FileSysType( ( f1->GetType() & FST_L_MASK )
					 | FST_UNICODE ) );
			t->SetDeleteOnClose();
			t->MakeGlobalTemp();
			d.SetOutput( t->Name(), e );
		    }
		    else
		    {
			d.SetOutput( stdout );
		    }
		}

		if( fileError && flags.type == DiffFlags::Unified )
	        {

		    d.DiffUnifiedDeleteFile( f1_bin, e );
		    d.CloseOutput( e );

		}
		else if( fileError )
		{
		    d.CloseOutput( e );

		}
		else if( !fileError )
		{

		    if( !e->Test() ) d.DiffWithFlags( flags );
		    d.CloseOutput( e );

		    if( output_translate )
		    {
			// set translator
			CharSetCvt *cvt;
			cvt = CharSetCvt::FindCvt(
			    CharSetApi::UTF_8,
			    (CharSetApi::CharSet)output );
			// error out if converter not found?
			t->Translator( cvt );

			if( pager )
			{
			    FileSys *tr = File( f1->GetType() );
			    tr->SetDeleteOnClose();
			    tr->MakeGlobalTemp();
			    t->Copy( tr, FPM_RW, e );
			    if( !fout )
				delete t;
			    t = tr;
			}
			else if( !fout )
			{
			    // read the file to stdout...

			    t->Open( FOM_READ, e );
			    if( !e->Test() )
			    {
				char buf[2048];
				int i;

				while( (i = t->Read( buf, sizeof(buf), e )) > 0
					&& !e->Test() )
				    fwrite( buf, i, 1, stdout );

   				t->Close( e );
			    }
			}

			delete cvt;
		    }

		    if( pager && !e->Test() )
			RunCmd( pager, t->Name(), 0, 0, 0, 0, 0, e );

		    if( !fout || pager )
			delete t;
		}
	    }

	    delete f1_bin;
	    delete f2_bin;
	    return;
	}

# endif /* VMS */

	// Build up flags args
	// Yuk.

	if( !df || !*df )
	{
	    if( diffunicode )
		RunCmd( diffunicode,
			CharSetApi::Name( (CharSetApi::CharSet)charset ),
			f1->Name(), f2->Name(), 0, 0, pager, e );
	    else
		RunCmd( diff, f1->Name(), f2->Name(), 0, 0, 0, pager, e );
	}
	else
	{
	    StrBuf flags;
	    flags.Set( "-", 1 );
	    flags << df;
	    if( diffunicode )
		RunCmd( diffunicode, flags.Text(),
			CharSetApi::Name( (CharSetApi::CharSet)charset ),
			f1->Name(), f2->Name(), 0, pager, e );
	    else
	        RunCmd( diff, flags.Text(), f1->Name(), f2->Name(),
			0, 0, pager, e );
	}
}

void
ClientUser::Merge(
	FileSys *base,
	FileSys *leg1,
	FileSys *leg2,
	FileSys *result,
	Error *e )
{
	char *merger;

	if( result->IsUnicode() )
	{
	    int cs = result->GetContentCharSetPriv();

	    if( cs != 0 && ( merger = enviro->Get( "P4MERGEUNICODE" ) ) )
	    {
		RunCmd( merger, CharSetApi::Name( (CharSetApi::CharSet)cs ),
			base->Name(), leg1->Name(), leg2->Name(),
			result->Name(), 0, e );
		return;
	    }
	}

	merger = enviro->Get( "P4MERGE" );

	if( !merger )
	    merger = enviro->Get( "MERGE" );

	if( !merger )
	{
	    e->Set( MsgClient::NoMerger );
	    return;
	}

	RunCmd( merger, base->Name(), leg1->Name(),
		leg2->Name(), result->Name(), 0, 0, e );
}

void
ClientUser::RunCmd(
	const char *command,
	const char *arg1,
	const char *arg2,
	const char *arg3,
	const char *arg4,
	const char *arg5,
	const char *pager,
	Error *e )
{
	// XXX RunCommand is dynamically allocated
	// to work around linux 2.5 24x86 compiler bug.
	// see job019081.

	RunCommand *rc = new RunCommand;

	fflush( stdout );

	signaler.Block();	// reset SIGINT to SIGDFL

	// Use AddCmd() to handle command which may be a mix of
	// cmd name (with spaces on NT) and flags (following spaces).

	RunArgs cmd;

	cmd.AddCmd( command );
	if( arg1 ) cmd.AddArg( arg1 );
	if( arg2 ) cmd.AddArg( arg2 );
	if( arg3 ) cmd.AddArg( arg3 );
	if( arg4 ) cmd.AddArg( arg4 );
	if( arg5 ) cmd.AddArg( arg5 );
	if( pager )
	{
	    cmd.AddArg( "|" );
	    cmd.AddArg( pager );
	}

	rc->Run( cmd, e );
	delete rc;

	signaler.Catch();	// catch SIGINT again
}

FileSys *
ClientUser::File( FileSysType type )
{
	return FileSys::Create( type );
}

int
ClientUser::ProgressIndicator()
{
	return 0;
}

ClientProgress *
ClientUser::CreateProgress( int )
{
	return NULL;
}

int
ClientUserProgress::ProgressIndicator()
{
	return 1;
}

ClientProgress *
ClientUserProgress::CreateProgress( int t )
{
	return new ClientProgressText( t );
}

int
ClientUser::Resolve( ClientMerge *m, Error *e )
{
	// pun from ClientMergeStatus
	return (int)m->Resolve( e );
}

int
ClientUser::Resolve( ClientResolveA *r, int preview, Error *e )
{
	// pun from ClientMergeStatus
	return (int)r->Resolve( preview, e );
}

void
ClientUser::Message( Error *err )
{
	int keepfile = 0;

	if( err->IsInfo() )
	{
	    // Info
	    StrBuf buf;
	    err->Fmt( buf, EF_PLAIN );
	    OutputInfo( (char)err->GetGeneric() + '0', buf.Text() );

	    if( err->CheckId( MsgServer::SpecNotCorrect ) )
		keepfile = 1;
	}
	else
	{
	    // warn, failed, fatal
	    HandleError( err );

	    // report file name left
	    if( !err->CheckId( MsgServer::ErrorInSpec ) )
		keepfile = 1;
	}

	if( editFile.Length() > 0 )
	{
	    if( keepfile )
	    {
		Error other;
		other.Set( MsgClient::FileKept ) << editFile.Text();
		HandleError( &other );
	    }
	    else
	    {
		FileSys *f = File( FST_UNICODE );
		f->Set( editFile );
		f->Unlink( err );
		delete f;
	    }
	    editFile.Clear();
	}
}

void
ClientUser::SetOutputCharset( int charset )
{
	outputCharset = charset;
}

void
ClientUser::DisableTmpCleanup()
{
	signaler.Disable();
}

void
ClientUser::SetQuiet()
{
	quiet = 1;
}


text:
/*
 *
 *
 *
 *
 *
 * Copyright (c) 2013, Stephen Colebourne & Michael Nascimento Santos
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  * Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 *  * Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 *  * Neither the name of JSR-310 nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package java.time.temporal;

import java.time.DateTimeException;

/**
 * UnsupportedTemporalTypeException indicates that a ChronoField or ChronoUnit is
 * not supported for a Temporal class.
 *
 * @implSpec
 * This class is intended for use in a single thread.
 *
 * @since 1.8
 */
public class UnsupportedTemporalTypeException extends DateTimeException {

    /**
     * Serialization version.
     */
    private static final long serialVersionUID = -6158898438688206006L;

    /**
     * Constructs a new UnsupportedTemporalTypeException with the specified message.
     *
     * @param message  the message to use for this exception, may be null
     */
    public UnsupportedTemporalTypeException(String message) {
        super(message);
    }

    /**
     * Constructs a new UnsupportedTemporalTypeException with the specified message and cause.
     *
     * @param message  the message to use for this exception, may be null
     * @param cause  the cause of the exception, may be null
     */
    public UnsupportedTemporalTypeException(String message, Throwable cause) {
        super(message, cause);
    }

}


text:
namespace qtools.Core.CLI
{
    public interface ICommand
    {
        bool Execute(string subject, IQueueTools tools, IOutput log);
    }
}


text:
<?php

    // JSON serialize a record
    $record = array();

    foreach($recorddisplay as $key => $element) {
        if (isset($solr[$element])) {
            $key = array();
            foreach ($solr[$element] as $metadatavalue) {
                $key[] = "" . $metadatavalue;
            }
            $record[$element] = $key;
        }
    }

    //TODO Put in digital objects

    header('Content-type: application/json');
    echo json_encode(array('record' => $record));
?>


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

"""This script is used to synthesize generated parts of this library."""

import synthtool as s
import synthtool.gcp as gcp
import logging
import re

logging.basicConfig(level=logging.DEBUG)

gapic = gcp.GAPICGenerator()

v2_library = gapic.ruby_library(
    'bigtable', 'v2', config_path='/google/bigtable/artman_bigtable.yaml',
    artman_output_name='google-cloud-ruby/google-cloud-bigtable'
)
s.copy(v2_library / 'lib/google/cloud/bigtable/v2')
s.copy(v2_library / 'lib/google/cloud/bigtable/v2.rb')
s.copy(v2_library / 'lib/google/bigtable/v2')
s.copy(v2_library / 'test/google/cloud/bigtable/v2')

v2_admin_library = gapic.ruby_library(
    'bigtableadmin', 'v2',
    config_path='/google/bigtable/admin/artman_bigtableadmin.yaml',
    artman_output_name='google-cloud-ruby/google-cloud-bigtable_admin'
)
s.copy(v2_admin_library / 'lib/google/cloud/bigtable/admin/v2')
s.copy(v2_admin_library / 'lib/google/cloud/bigtable/admin/v2.rb')
s.copy(v2_admin_library / 'lib/google/cloud/bigtable/admin.rb')
s.copy(v2_admin_library / 'lib/google/bigtable/admin/v2')
s.copy(v2_admin_library / 'test/google/cloud/bigtable/admin/v2')

# PERMANENT: We're combining bigtable and bigtable-admin into one gem.
s.replace(
    [
      'lib/google/cloud/bigtable/admin/v2/bigtable_instance_admin_client.rb',
      'lib/google/cloud/bigtable/admin/v2/bigtable_table_admin_client.rb'
    ],
    "Gem.loaded_specs\\['google-cloud-bigtable-admin'\\]",
    "Gem.loaded_specs['google-cloud-bigtable']")
s.replace(
    [
      'lib/google/cloud/bigtable/admin.rb',
      'lib/google/cloud/bigtable/admin/v2.rb'
    ],
    '# \\$ gem install google-cloud-bigtable-admin',
    '# $ gem install google-cloud-bigtable')

# PERMANENT: Handwritten layer owns Bigtable.new so low-level clients need to
# use Bigtable::V2.new instead of Bigtable.new(version: :v2). Update the
# examples and tests.
s.replace(
    [
      'lib/google/cloud/bigtable/v2/bigtable_client.rb',
      'test/google/cloud/bigtable/v2/bigtable_client_test.rb'
    ],
    'require "google/cloud/bigtable"',
    'require "google/cloud/bigtable/v2"')
s.replace(
    [
      'lib/google/cloud/bigtable/v2/bigtable_client.rb',
      'test/google/cloud/bigtable/v2/bigtable_client_test.rb'
    ],
    'Google::Cloud::Bigtable\\.new\\(version: :v2\\)',
    'Google::Cloud::Bigtable::V2.new')

# PERMANENT: API name for bigtableadmin
s.replace(
    [
      'lib/google/cloud/bigtable/admin.rb',
      'lib/google/cloud/bigtable/admin/v2.rb',
    ],
    '/bigtable-admin\\.googleapis\\.com', '/bigtableadmin.googleapis.com')

# https://github.com/googleapis/gapic-generator/issues/2232
s.replace(
    [
      'lib/google/cloud/bigtable/admin/v2/bigtable_instance_admin_client.rb',
      'lib/google/cloud/bigtable/admin/v2/bigtable_table_admin_client.rb'
    ],
    '\n\n(\\s+)class OperationsClient < Google::Longrunning::OperationsClient',
    '\n\n\\1# @private\n\\1class OperationsClient < Google::Longrunning::OperationsClient')

# https://github.com/googleapis/gapic-generator/issues/2242
def escape_braces(match):
    expr = re.compile('^([^`]*(`[^`]*`[^`]*)*)([^`#\\$\\\\])\\{([\\w,]+)\\}')
    content = match.group(0)
    while True:
        content, count = expr.subn('\\1\\3\\\\\\\\{\\4}', content)
        if count == 0:
            return content
s.replace(
    'lib/google/cloud/bigtable/admin/v2/**/*.rb',
    '\n(\\s+)#[^\n]*[^\n#\\$\\\\]\\{[\\w,]+\\}',
    escape_braces)

# https://github.com/googleapis/gapic-generator/issues/2243
s.replace(
    [
      'lib/google/cloud/bigtable/v2/*_client.rb',
      'lib/google/cloud/bigtable/admin/v2/*_client.rb'
    ],
    '(\n\\s+class \\w+Client\n)(\\s+)(attr_reader :\\w+_stub)',
    '\\1\\2# @private\n\\2\\3')

# https://github.com/googleapis/gapic-generator/issues/2279
s.replace(
    'lib/**/*.rb',
    '\\A(((#[^\n]*)?\n)*# (Copyright \\d+|Generated by the protocol buffer compiler)[^\n]+\n(#[^\n]*\n)*\n)([^\n])',
    '\\1\n\\6')

# https://github.com/googleapis/gapic-generator/issues/2323
s.replace(
    'lib/**/*.rb',
    'https://github\\.com/GoogleCloudPlatform/google-cloud-ruby',
    'https://github.com/googleapis/google-cloud-ruby'
)
s.replace(
    'lib/**/*.rb',
    'https://googlecloudplatform\\.github\\.io/google-cloud-ruby',
    'https://googleapis.github.io/google-cloud-ruby'
)


text:
using System;
using System.IO;
using System.Linq;

namespace Moonfish.Graphics
{
    public interface IBuffer
    {
        IDisposable Bind( );

        IDisposable Create( );
    }

    struct DrawIndirectCmd
    {
        public DrawIndirectCmd( int count, int instanceCount, int firstIndex, int baseVertex, int baseInstance )
        {
            Count = count;
            InstanceCount = instanceCount;
            BaseInstance = baseInstance;
            FirstIndex = firstIndex;
            BaseVertex = baseVertex;
        }

        public int Count { get; }
        public int InstanceCount { get; }
        public int FirstIndex { get; }
        public int BaseVertex { get; }
        public int BaseInstance { get; }

        public void Write( BinaryWriter binaryWriter )
        {
            binaryWriter.Write(Count);
            binaryWriter.Write(InstanceCount);
            binaryWriter.Write(FirstIndex);
            binaryWriter.Write(BaseVertex);
            binaryWriter.Write(BaseInstance);
        }

        public const int CmdSize = sizeof ( int ) * 5;
    }
}


text:
const asyncRetry = require('async/retry');
const {getPortPromise: getPort} = require('portfinder');
const {setupChannel} = require('ln-docker-daemons');
const {spawnLightningDocker} = require('ln-docker-daemons');
const {test} = require('@alexbosworth/tap');

const {addPeer} = require('./../../');
const {authenticatedLndGrpc} = require('./../../');
const {createChainAddress} = require('./../../');
const {getBackups} = require('./../../');
const {getIdentity} = require('./../../');
const {getPendingChannels} = require('./../../');
const {getUtxos} = require('./../../');
const {recoverFundsFromChannels} = require('./../../');

const confirmationCount = 20;
const generateAddress = '2N8hwP1WmJrFF5QWABn38y63uYLhnJYJYTF';
const giftTokens = 1e5;
const interval = 10;
const makeAddress = ({lnd}) => createChainAddress({lnd});
const maturity = 100;
const seed = 'about rabbit ozone hope jaguar quit scare twenty punch crisp consider clutch ring frost universe okay execute shrug drink notice abandon wine denial retreat';
const times = 3000;

// Using a channels backup should recover funds
test(`Recover funds from channels`, async ({end, equal}) => {
  const control = await asyncRetry({interval, times}, async () => {
    return await spawnLightningDocker({
      seed,
      chain_p2p_port: await getPort({port: 8000, stopPort: 9000}),
      chain_rpc_port: await getPort({port: 9001, stopPort: 10000}),
      chain_zmq_block_port: await getPort({port: 10001, stopPort: 11000}),
      chain_zmq_tx_port: await getPort({port: 11001, stopPort: 12000}),
      generate_address: generateAddress,
      lightning_p2p_port: await getPort({port: 12001, stopPort: 13000}),
      lightning_rpc_port: await getPort({port: 13001, stopPort: 14000}),
    });
  });

  const target = await asyncRetry({interval, times}, async () => {
    return await spawnLightningDocker({
      chain_p2p_port: await getPort({port: 8000, stopPort: 9000}),
      chain_rpc_port: await getPort({port: 9001, stopPort: 10000}),
      chain_zmq_block_port: await getPort({port: 10001, stopPort: 11000}),
      chain_zmq_tx_port: await getPort({port: 11001, stopPort: 12000}),
      generate_address: generateAddress,
      lightning_p2p_port: await getPort({port: 12001, stopPort: 13000}),
      lightning_rpc_port: await getPort({port: 13001, stopPort: 14000}),
    });
  });

  await control.add_chain_peer({socket: target.chain_socket});
  await target.add_chain_peer({socket: control.chain_socket});

  const controlLnd = authenticatedLndGrpc({
    cert: control.cert,
    macaroon: control.macaroon,
    socket: control.socket,
  });

  const id = (await getIdentity({lnd: controlLnd.lnd})).public_key;

  const targetLnd = authenticatedLndGrpc({
    cert: target.cert,
    macaroon: target.macaroon,
    socket: target.socket,
  });

  const targetId = (await getIdentity({lnd: targetLnd.lnd})).public_key;

  const channelOpen = await setupChannel({
    generate: ({address, count}) => {
      return new Promise(async (resolve, reject) => {
        const {lnd} = targetLnd;

        await target.generate({
          count,
          address: (await makeAddress({lnd})).address,
        });

        if (!count || count < maturity) {
          return resolve();
        }

        await asyncRetry({interval, times}, async () => {
          const [utxo] = (await getUtxos({lnd})).utxos;

          if (!utxo) {
            throw new Error('ExpectedUtxoInUtxos');
          }
        });

        return resolve();
      });
    },
    give_tokens: giftTokens,
    lnd: targetLnd.lnd,
    to: {id, socket: control.ln_socket},
  });

  const {backup} = await getBackups({lnd: controlLnd.lnd});

  await control.kill({});

  const clone = await asyncRetry({interval, times}, async () => {
    return await spawnLightningDocker({
      seed,
      chain_p2p_port: await getPort({port: 8000, stopPort: 9000}),
      chain_rpc_port: await getPort({port: 9001, stopPort: 10000}),
      chain_zmq_block_port: await getPort({port: 10001, stopPort: 11000}),
      chain_zmq_tx_port: await getPort({port: 11001, stopPort: 12000}),
      generate_address: generateAddress,
      lightning_p2p_port: await getPort({port: 12001, stopPort: 13000}),
      lightning_rpc_port: await getPort({port: 13001, stopPort: 14000}),
    });
  });

  await clone.add_chain_peer({socket: target.chain_socket});

  await target.add_chain_peer({socket: clone.chain_socket});

  const cloneLnd = authenticatedLndGrpc({
    cert: clone.cert,
    macaroon: clone.macaroon,
    socket: clone.socket,
  });

  await addPeer({
    lnd: cloneLnd.lnd,
    public_key: targetId,
    socket: target.ln_socket,
  });

  await asyncRetry({interval, times}, async () => {
    await recoverFundsFromChannels({backup, lnd: cloneLnd.lnd});
  });

  await clone.generate({
    address: generateAddress,
    count: confirmationCount,
  });

  await target.generate({
    address: generateAddress,
    count: confirmationCount,
  });

  // Target should force close the channel
  {
    const {lnd} = targetLnd;

    await asyncRetry({interval, times}, async () => {
      await addPeer({
        lnd: cloneLnd.lnd,
        public_key: targetId,
        socket: target.ln_socket,
      });

      const [chan] = (await getPendingChannels({lnd})).pending_channels;

      if (!chan) {
        throw new Error('ExpectedChannelClosing');
      }
    });
  }

  // Make sure that the clone is getting the recovered funds
  {
    const {lnd} = cloneLnd;

    await asyncRetry({interval, times}, async () => {
      const [chan] = (await getPendingChannels({lnd})).pending_channels;

      await target.generate({address: generateAddress});

      if (!chan.local_balance) {
        throw new Error('ExpectedChannelClosingBalance');
      }
    });

    const [chan] = (await getPendingChannels({lnd})).pending_channels;

    equal(!!chan.close_transaction_id, true, 'Close transaction id found');
    equal(chan.is_active, false, 'Chan no longer active');
    equal(chan.is_closing, true, 'Channel is closing');
    equal(chan.is_opening, false, 'Channel closing');
    equal(chan.local_balance, giftTokens, 'Funds are being restored');
    equal(chan.partner_public_key, targetId, 'Peer key');
    equal(chan.transaction_id, channelOpen.transaction_id, 'Chan tx id');
    equal(chan.transaction_vout, channelOpen.transaction_vout, 'Chan tx vout');
  }

  await clone.kill({});

  await target.kill({});

  return end();
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cereal64.Microcodes.F3DEX.DataElements;
using Cereal64.Common.DataElements;
using System.Xml.Linq;
using Cereal64.Common.Utils;

namespace Pitstop64.Data.Karts
{
    public class KartPaletteBlock : N64DataElement
    {
        public List<Palette> Palettes;

        private const int PALETTE_BYTE_LENGTH = 0x40 * 2; //64 colors, 2 bytes per color

        public KartPaletteBlock(int fileOffset, List<Palette> palettes)
            : base(fileOffset, null)
        {
            Palettes.AddRange(palettes);
        }

        public KartPaletteBlock(int fileOffset, byte[] rawData)
            : base(fileOffset, rawData)
        {
        }

        public KartPaletteBlock(XElement xml, byte[] rawData)
            : base(xml, rawData)
        {
            //This should never be saved as an xml
            throw new Exception();
        }

        public override byte[] RawData
        {
            get
            {
                return ByteHelper.CombineIntoBytes(Palettes);
            }
            set
            {
                if(Palettes == null)
                    Palettes = new List<Palette>();

                if (value != null)
                {
                    int paletteCount = (value.Length / PALETTE_BYTE_LENGTH);

                    byte[] paletteBytes = new byte[PALETTE_BYTE_LENGTH];

                    bool overwriteExistingPalettes = Palettes.Count == paletteCount;

                    for (int i = 0; i < paletteCount; i++)
                    {
                        Array.Copy(value, i * PALETTE_BYTE_LENGTH, paletteBytes, 0, PALETTE_BYTE_LENGTH);

                        //Either overwrite existing palettes or create new ones
                        if (overwriteExistingPalettes)
                        {
                            Palettes[i].RawData = paletteBytes;
                        }
                        else
                        {
                            Palettes.Add(new Palette(FileOffset + i * PALETTE_BYTE_LENGTH, paletteBytes));
                        }
                    }
                }
            }
        }

        public override int RawDataSize
        {
            get { return Palettes.Count * PALETTE_BYTE_LENGTH; }
        }
    }
}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;

using Microsoft.Build.Framework;
using Microsoft.Build.Shared;
using Xunit;

namespace Microsoft.Build.UnitTests
{
    public class ResourceUtilitiesTests
    {
        [Fact]
        public void ExtractMSBuildCode()
        {
            // most common message pattern
            string code;
            string messageOnly = ResourceUtilities.ExtractMessageCode(true /* msbuild code only */, "MSB7007: This is a message.", out code);
            Assert.Equal("MSB7007", code);
            Assert.Equal("This is a message.", messageOnly);

            // no whitespace between colon and message is ok
            code = null;
            messageOnly = ResourceUtilities.ExtractMessageCode(true /* msbuild code only */, "MSB7007:This is a message.", out code);
            Assert.Equal("MSB7007", code);
            Assert.Equal("This is a message.", messageOnly);

            // whitespace before code and after colon is ok
            code = null;
            messageOnly = ResourceUtilities.ExtractMessageCode(true /* msbuild code only */, "  MSB7007:   This is a message.", out code);
            Assert.Equal("MSB7007", code);
            Assert.Equal("This is a message.", messageOnly);

            // whitespace between code and colon is not ok
            code = null;
            messageOnly = ResourceUtilities.ExtractMessageCode(true /* msbuild code only */, "MSB7007 : This is a message.", out code);
            Assert.Null(code);
            Assert.Equal("MSB7007 : This is a message.", messageOnly);

            // whitespace in code is not ok
            code = null;
            messageOnly = ResourceUtilities.ExtractMessageCode(true /* msbuild code only */, "MSB 7007: This is a message.", out code);
            Assert.Null(code);
            Assert.Equal("MSB 7007: This is a message.", messageOnly);

            // code with less than 4 digits is not ok
            code = null;
            messageOnly = ResourceUtilities.ExtractMessageCode(true /* msbuild code only */, "MSB007: This is a message.", out code);
            Assert.Null(code);
            Assert.Equal("MSB007: This is a message.", messageOnly);

            // code without digits is not ok
            code = null;
            messageOnly = ResourceUtilities.ExtractMessageCode(true /* msbuild code only */, "MSB: This is a message.", out code);
            Assert.Null(code);
            Assert.Equal("MSB: This is a message.", messageOnly);

            // code without MSB prefix is not ok
            code = null;
            messageOnly = ResourceUtilities.ExtractMessageCode(true /* msbuild code only */, "1001: This is a message.", out code);
            Assert.Null(code);
            Assert.Equal("1001: This is a message.", messageOnly);

            // digits before MSB prefix is not ok
            code = null;
            messageOnly = ResourceUtilities.ExtractMessageCode(true /* msbuild code only */, "7001MSB: This is a message.", out code);
            Assert.Null(code);
            Assert.Equal("7001MSB: This is a message.", messageOnly);

            // mixing letters and digits is not ok
            code = null;
            messageOnly = ResourceUtilities.ExtractMessageCode(true /* msbuild code only */, "MSB564B: This is a message.", out code);
            Assert.Null(code);
            Assert.Equal("MSB564B: This is a message.", messageOnly);

            // lowercase code is not ok
            code = null;
            messageOnly = ResourceUtilities.ExtractMessageCode(true /* msbuild code only */, "msb1001: This is a message.", out code);
            Assert.Null(code);
            Assert.Equal("msb1001: This is a message.", messageOnly);
        }
    }
}