text:
// This is *not* original work by Kirill Shlenskiy.
// It is taken in its entirety or derived from
// CoreFX (https://github.com/dotnet/corefx).
// Original license below:

// The MIT License (MIT)

// Copyright (c) .NET Foundation and Contributors

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

#if NET_40

using System.Runtime.CompilerServices;

namespace System.Threading
{
    /// <summary>
    /// Slow Volatile reimplementation for
    /// consumers targeting .NET 4.0 and below.
    /// Equivalent to Thread.VolatileRead().
    /// </summary>
    internal static class Volatile
    {
        [MethodImplAttribute(MethodImplOptions.NoInlining)] // disable optimizations.
        public static T Read<T>(ref T location) where T : class
        {
            T value = location;
            Thread.MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.
            return value;
        }
    }
}

#endif


text:
extern "C" {
#include "postgres.h"
#include "utils/memutils.h"
}

#include "gpos/memory/CMemoryPool.h"
#include "gpopt/gpdbwrappers.h"

#include "gpopt/utils/CMemoryPoolPalloc.h"

using namespace gpos;

// ctor
CMemoryPoolPalloc::CMemoryPoolPalloc()
	: m_cxt(NULL)
{
	m_cxt = gpdb::GPDBAllocSetContextCreate();
}

void *
CMemoryPoolPalloc::NewImpl
	(
	const ULONG bytes,
	const CHAR *,
	const ULONG,
	CMemoryPool::EAllocationType eat
	)
{
	// if it's a singleton allocation, allocate requested memory
	if (CMemoryPool::EatSingleton == eat)
	{
		return gpdb::GPDBMemoryContextAlloc(m_cxt, bytes);
	}
	// if it's an array allocation, allocate header + requested memory
	else
	{
		ULONG alloc_size = GPOS_MEM_ALIGNED_STRUCT_SIZE(SArrayAllocHeader) + GPOS_MEM_ALIGNED_SIZE(bytes);

		void *ptr = gpdb::GPDBMemoryContextAlloc(m_cxt, alloc_size);

		if (NULL == ptr)
		{
			return NULL;
		}

		SArrayAllocHeader *header = static_cast<SArrayAllocHeader*>(ptr);

		header->m_user_size = bytes;
		return static_cast<BYTE*>(ptr) + GPOS_MEM_ALIGNED_STRUCT_SIZE(SArrayAllocHeader);
	}
}

void
CMemoryPoolPalloc::DeleteImpl(void *ptr, CMemoryPool::EAllocationType eat)
{
	if (CMemoryPool::EatSingleton == eat)
	{
		gpdb::GPDBFree(ptr);
	}
	else
	{
		void* header = static_cast<BYTE*>(ptr) - GPOS_MEM_ALIGNED_STRUCT_SIZE(SArrayAllocHeader);
		gpdb::GPDBFree(header);
	}
}

// Prepare the memory pool to be deleted
void
CMemoryPoolPalloc::TearDown()
{
	gpdb::GPDBMemoryContextDelete(m_cxt);
}

// Total allocated size including management overheads
ULLONG
CMemoryPoolPalloc::TotalAllocatedSize() const
{
	return MemoryContextGetCurrentSpace(m_cxt);
}

// get user requested size of array allocation. Note: this is ONLY called for arrays
ULONG
CMemoryPoolPalloc::UserSizeOfAlloc(const void *ptr)
{
	GPOS_ASSERT(ptr != NULL);
	void* void_header = static_cast<BYTE*>(const_cast<void*>(ptr)) - GPOS_MEM_ALIGNED_STRUCT_SIZE(SArrayAllocHeader);
	const SArrayAllocHeader *header = static_cast<SArrayAllocHeader*>(void_header);
	return header->m_user_size;
}

// EOF

redpajama_set_name: RedPajamaGithub


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * 控制器
 * @package     CI
 * @subpackage  Controllers
 * @category    Controllers
 * @author      ming.king
 */
class Home extends P_Controller{
    /**
     * 构造函数
     *
     * @access  public
     * @return  void
     */
    public function __construct(){
        parent::__construct();
        $this->this_view_data['menu'] = 'home';
    }
    /**
     * 后台默认首页
     *
     * @access  public
     * @return  void
     */
    public function index(){
        $this->load->view('home',$this->this_view_data);
    }
}


text:
import {IComponent} from "./IComponent";
import {IDestroyable} from "./IDestroyable";
import {IEntity} from "./IEntity";

export class AbstractComponent implements IComponent, IDestroyable {

    protected owner:IEntity;
    protected destroyed:boolean;

    constructor() {
    }

    public setOwner(owner:IEntity):void {
        this.owner = owner;
        this.setup();
    }

    public isDestroyed():boolean {
        return this.destroyed;
    }

    public getDependencies():Array<string> {
        return null;
    }

    public getType():string {
        throw Error("AbstractComponent.getType not overrided. Please implement this method");
    }

    public setup():void {
        throw Error("You must override this method, here the owner is available to start your component");
    }

    public destroy():void {
        this.owner = null;
        this.destroyed = true;
    }

}


text:
/*

  This demo renders markdown documents to an image.

  - Reads markdown from stdin
  - Renders it to the document.body with GFM
  - Shows the browser window and captures the screen
  - Writes PNG to process.stdout

    npm run example:markdown
 */

var marked = require('marked');
var remote = require('electron').remote;

var css = require.resolve('github-markdown-css/github-markdown.css');
var cssFile = require('fs').readFileSync(css, 'utf8');
require('insert-css')(cssFile);

require('get-stdin')()
  .then(function (src) {
    capture(src.toString());
  }, function (err) {
    console.error(err);
    process.exit(1);
  });

function capture (md) {
  document.body.className = 'markdown-body';
  document.body.innerHTML = marked(md);

  var browserWindow = remote.getCurrentWindow();
  browserWindow.show();
  browserWindow.setContentSize(720, 640);
  setTimeout(function () { // wait for images to render
    browserWindow.capturePage(function (data) {
      process.stdout.write(data.toPng(), function () {
        window.close();
      });
    });
  }, 500);
}


text:
@interface FRBSwatchist : NSObject

+ (void)loadSwatch:(NSURL *)url forName:(NSString *)string;
+ (FRBSwatch *)swatchForName:(NSString *)string;

// Swatch Access
// Use <swatchName>.<key>
+ (id)objectForKey:(NSString *)key;
+ (NSString *)stringForKey:(NSString *)key;
+ (NSInteger)intForKey:(NSString *)key;
+ (CGFloat)floatForKey:(NSString *)key;
+ (BOOL)boolForKey:(NSString *)key;

+ (CGPoint)pointForKey:(NSString *)key;
+ (CGSize)sizeForKey:(NSString *)key;
+ (CGRect)rectForKey:(NSString *)key;

+ (GLKVector2)vector2ForKey:(NSString *)key;
+ (GLKVector3)vector3ForKey:(NSString *)key;
+ (GLKVector4)vector4ForKey:(NSString *)key;

+ (GLKVector3)vector3ColorForKey:(NSString *)key;
+ (GLKVector4)vector4ColorForKey:(NSString *)key;

+ (UIFont *)fontForKey:(NSString *)key;
+ (UIColor *)colorForKey:(NSString *)key;

@end


text:
package com.yammer.metrics.logback.tests;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Appender;
import com.yammer.metrics.core.Meter;
import com.yammer.metrics.core.MetricsRegistry;
import com.yammer.metrics.logback.InstrumentedAppender;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.concurrent.TimeUnit;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class InstrumentedAppenderTest {
    private Meter all, trace, debug, info, warn, error;
    private ILoggingEvent event;
    private InstrumentedAppender instrumented;

    @Before
    public void setUp() throws Exception {
        this.all = mock(Meter.class);
        this.trace = mock(Meter.class);
        this.debug = mock(Meter.class);
        this.info = mock(Meter.class);
        this.warn = mock(Meter.class);
        this.error = mock(Meter.class);

        this.event = mock(ILoggingEvent.class);
        when(event.getLevel()).thenReturn(Level.INFO);

        final MetricsRegistry registry = mock(MetricsRegistry.class);
        when(registry.newMeter(Appender.class, "all", "statements", TimeUnit.SECONDS)).thenReturn(all);
        when(registry.newMeter(Appender.class, "trace", "statements", TimeUnit.SECONDS)).thenReturn(trace);
        when(registry.newMeter(Appender.class, "debug", "statements", TimeUnit.SECONDS)).thenReturn(debug);
        when(registry.newMeter(Appender.class, "info", "statements", TimeUnit.SECONDS)).thenReturn(info);
        when(registry.newMeter(Appender.class, "warn", "statements", TimeUnit.SECONDS)).thenReturn(warn);
        when(registry.newMeter(Appender.class, "error", "statements", TimeUnit.SECONDS)).thenReturn(error);

        this.instrumented = new InstrumentedAppender(registry);
        instrumented.start();
    }

    @After
    public void tearDown() throws Exception {
        instrumented.stop();
    }

    @Test
    public void metersTraceEvents() throws Exception {
        when(event.getLevel()).thenReturn(Level.TRACE);
        instrumented.doAppend(event);

        verify(trace).mark();
        verify(all).mark();
    }

    @Test
    public void metersDebugEvents() throws Exception {
        when(event.getLevel()).thenReturn(Level.DEBUG);
        instrumented.doAppend(event);

        verify(debug).mark();
        verify(all).mark();
    }

    @Test
    public void metersInfoEvents() throws Exception {
        when(event.getLevel()).thenReturn(Level.INFO);
        instrumented.doAppend(event);

        verify(info).mark();
        verify(all).mark();
    }

    @Test
    public void metersWarnEvents() throws Exception {
        when(event.getLevel()).thenReturn(Level.WARN);
        instrumented.doAppend(event);

        verify(warn).mark();
        verify(all).mark();
    }

    @Test
    public void metersErrorEvents() throws Exception {
        when(event.getLevel()).thenReturn(Level.ERROR);
        instrumented.doAppend(event);

        verify(error).mark();
        verify(all).mark();
    }
}


text:
// +build legacy

package cpolicy

import (
	"testing"

	"github.com/intelsdi-x/snap/core/ctypes"
	. "github.com/smartystreets/goconvey/convey"
)

// Helpful method to switch to slice of strings for goconvey contains checking
func errorsMsg(errors []error) []string {
	s := []string{}
	for _, e := range errors {
		s = append(s, e.Error())
	}
	return s
}

func TestConfigPolicyNode(t *testing.T) {

	Convey("returns error for missing required data", t, func() {
		n := NewPolicyNode()
		So(n, ShouldNotBeNil)

		m := map[string]ctypes.ConfigValue{}
		m["username"] = ctypes.ConfigValueStr{Value: "root"}

		r1, _ := NewStringRule("username", true)
		r2, _ := NewStringRule("password", true)
		r3, _ := NewBoolRule("nova", false)

		n.Add(r1, r2, r3)

		_, pe := n.Process(m)

		So(pe.HasErrors(), ShouldBeTrue)
		So(len(pe.Errors()), ShouldEqual, 1)
		So(errorsMsg(pe.Errors()), ShouldContain, "required key missing (password)")
	})

	Convey("returns errors for missing required data (mutliple)", t, func() {
		n := NewPolicyNode()
		So(n, ShouldNotBeNil)

		m := map[string]ctypes.ConfigValue{}
		m["username"] = ctypes.ConfigValueStr{Value: "root"}

		r1, _ := NewStringRule("username", true)
		r2, _ := NewStringRule("password", true)
		r3, _ := NewIntegerRule("port", true)
		r4, _ := NewIntegerRule("port", true)

		n.Add(r1, r2, r3, r4)

		_, pe := n.Process(m)

		So(pe.HasErrors(), ShouldBeTrue)
		So(len(pe.Errors()), ShouldEqual, 2)
		So(errorsMsg(pe.Errors()), ShouldContain, "required key missing (port)")
		So(errorsMsg(pe.Errors()), ShouldContain, "required key missing (password)")
	})

	Convey("returns error for mismatched type", t, func() {
		n := NewPolicyNode()
		So(n, ShouldNotBeNil)

		m := map[string]ctypes.ConfigValue{}
		m["username"] = ctypes.ConfigValueStr{Value: "root"}
		m["password"] = ctypes.ConfigValueStr{Value: "password"}
		m["port"] = ctypes.ConfigValueStr{Value: "8080"}
		m["nova"] = ctypes.ConfigValueStr{Value: "true"}

		r1, _ := NewStringRule("username", true)
		r2, _ := NewStringRule("password", true)
		r3, _ := NewIntegerRule("port", true)
		r4, _ := NewBoolRule("nova", true)

		n.Add(r1, r2, r3, r4)

		_, pe := n.Process(m)

		So(len(pe.Errors()), ShouldEqual, 2)
		So(errorsMsg(pe.Errors()), ShouldContain, "type mismatch (port wanted type 'integer' but provided type 'string')")
		So(errorsMsg(pe.Errors()), ShouldContain, "type mismatch (nova wanted type 'bool' but provided type 'string')")
	})

	Convey("adds defaults to only missing values that should have them", t, func() {
		n := NewPolicyNode()
		So(n, ShouldNotBeNil)

		m := map[string]ctypes.ConfigValue{}
		m["password"] = ctypes.ConfigValueStr{Value: "password"}

		r1, _ := NewStringRule("username", false, "root")
		r2, _ := NewStringRule("password", true)
		r3, _ := NewIntegerRule("port", false, 8080)
		r4, _ := NewBoolRule("nova", false, true)

		n.Add(r1, r2, r3, r4)

		m2, pe := n.Process(m)

		So(len(pe.Errors()), ShouldEqual, 0)
		So((*m2)["username"].(*ctypes.ConfigValueStr).Value, ShouldEqual, "root")
		So((*m2)["port"].(*ctypes.ConfigValueInt).Value, ShouldEqual, 8080)
		So((*m2)["nova"].(*ctypes.ConfigValueBool).Value, ShouldEqual, true)
	})

	Convey("defaults don't fix missing values on required", t, func() {
		n := NewPolicyNode()
		So(n, ShouldNotBeNil)

		m := map[string]ctypes.ConfigValue{}
		m["password"] = ctypes.ConfigValueStr{Value: "password"}

		r1, _ := NewStringRule("username", true, "root")
		r2, _ := NewStringRule("password", true)

		n.Add(r1, r2)

		m2, pe := n.Process(m)

		So(len(pe.Errors()), ShouldEqual, 1)
		So(m2, ShouldBeNil)
	})

	Convey("Test integer value between minimum and maximum for rule succeeds", t, func() {
		n := NewPolicyNode()

		m := map[string]ctypes.ConfigValue{}
		m["port"] = ctypes.ConfigValueInt{Value: 5}

		r1, _ := NewIntegerRule("port", false)
		r1.SetMinimum(0)
		r1.SetMaximum(10)

		n.Add(r1)

		m2, pe := n.Process(m)

		So(len(pe.Errors()), ShouldEqual, 0)
		So((*m2)["port"].(ctypes.ConfigValueInt).Value, ShouldEqual, 5)
	})
	Convey("Test integer value outside of maximum for rule fails", t, func() {
		n := NewPolicyNode()

		m := map[string]ctypes.ConfigValue{}
		m["port"] = ctypes.ConfigValueInt{Value: 5}

		r1, _ := NewIntegerRule("port", false)
		r1.SetMinimum(0)
		r1.SetMaximum(4)

		n.Add(r1)

		_, pe := n.Process(m)

		So(len(pe.Errors()), ShouldEqual, 1)
	})
	Convey("Test integer value outside of minimum for rule fails", t, func() {
		n := NewPolicyNode()

		m := map[string]ctypes.ConfigValue{}
		m["port"] = ctypes.ConfigValueInt{Value: 5}

		r1, _ := NewIntegerRule("port", false)
		r1.SetMinimum(7)
		r1.SetMaximum(100)

		n.Add(r1)

		_, pe := n.Process(m)

		So(len(pe.Errors()), ShouldEqual, 1)
	})
	Convey("Test float value between minimum and maximum for rule succeeds", t, func() {
		n := NewPolicyNode()

		m := map[string]ctypes.ConfigValue{}
		m["num"] = ctypes.ConfigValueFloat{Value: 5.06}

		r1, _ := NewFloatRule("num", false)
		r1.SetMinimum(3.14)
		r1.SetMaximum(10.17)

		n.Add(r1)

		m2, pe := n.Process(m)

		So(len(pe.Errors()), ShouldEqual, 0)
		So((*m2)["num"].(ctypes.ConfigValueFloat).Value, ShouldEqual, 5.06)
	})
	Convey("Test float value outside of maximum for rule fails", t, func() {
		n := NewPolicyNode()

		m := map[string]ctypes.ConfigValue{}
		m["num"] = ctypes.ConfigValueFloat{Value: 5.97}

		r1, _ := NewFloatRule("num", false)
		r1.SetMinimum(0)
		r1.SetMaximum(3.14)

		n.Add(r1)

		_, pe := n.Process(m)

		So(len(pe.Errors()), ShouldEqual, 1)
	})
	Convey("Test float value outside of minimum for rule fails", t, func() {
		n := NewPolicyNode()

		m := map[string]ctypes.ConfigValue{}
		m["num"] = ctypes.ConfigValueFloat{Value: 2.26}

		r1, _ := NewFloatRule("num", false)
		r1.SetMinimum(3.14)
		r1.SetMaximum(42)

		n.Add(r1)

		_, pe := n.Process(m)

		So(len(pe.Errors()), ShouldEqual, 1)
	})

}


text:
using osu.Framework.Graphics.UserInterface;

namespace osu.Game.Graphics.UserInterfaceV2
{
    public class OsuColourPicker : ColourPicker
    {
        public OsuColourPicker()
        {
            CornerRadius = 10;
            Masking = true;
        }

        protected override HSVColourPicker CreateHSVColourPicker() => new OsuHSVColourPicker();
        protected override HexColourPicker CreateHexColourPicker() => new OsuHexColourPicker();
    }
}


text:
package io.github.imsmobile.fahrplan.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;

import io.github.imsmobile.fahrplan.MainActivity;
import io.github.imsmobile.fahrplan.R;
import io.github.imsmobile.fahrplan.model.FavoriteModel;
import io.github.imsmobile.fahrplan.model.FavoriteModelItem;

public class FavoriteAdapter extends BaseAdapter {

    private final Context context;
    private final FavoriteModel favorite;

    public FavoriteAdapter(Context context, FavoriteModel favorite) {
        this.context = context;
        this.favorite = favorite;
    }
    @Override
    public int getCount() {
        return favorite.size();
    }

    @Override
    public Object getItem(int position) {
        return favorite.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.favorite_item, parent, false);
        }

        FavoriteModelItem fav = (FavoriteModelItem) getItem(position);

        TextView text = (TextView) convertView.findViewById(R.id.favorite_item_text);
        text.setText(fav.toString());
        text.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                MainActivity c = (MainActivity) context;
                c.activateFavorite(position);
            }
        });

        Button delete = (Button) convertView.findViewById(R.id.favorite_item_delete);
        delete.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                MainActivity c = (MainActivity) context;
                c.removeFavorite(position);
                notifyDataSetChanged();
            }
        });

        return convertView;
    }

}


text:
import unittest
import mock

import app

class Resp:

    def __init__(self, json_data, status_code):
        self.json_data = json_data
        self.status_code = status_code

    def json(self):
        return self.json_data

class AppTestCase(unittest.TestCase):

    def setUp(self):
        app.app.config['TESTING'] = True
        self.app = app.app.test_client()

    @mock.patch('requests.post')
    def test_checkouts_usd_ok(self, mock_post):
        payment = {
            "Payment": {
                "ID": 123,
                "Status": {"ID": 11, "Info": "Captured", "Reasons": []},
                "CreditCardToken": {"Value": "zxc"}
            }
        }
        mock_post.return_value = Resp(payment, 200)
        data = {
            "currency": "USD",
            "price_USD": "11",
            "price_EUR": "7",
            "amount": "2",
            "card_holder": "CH",
            "card_number": "333",
            "card_exp_month": "11",
            "card_exp_year": "22",
            "card_cvv": "123",
        }
        res = self.app.post('/checkouts', data=data)
        self.assertEqual(res.status_code, 302)
        self.assertIn("/checkouts/123", res.location)
        mock_post.assert_called_with(
            'https://securetest.smart2pay.com/v1/payments',
            auth=mock.ANY,
            json={'Payment': {
                'MerchantTransactionID': mock.ANY,
                'Amount': 2200,
                'Currency': 'USD',
                'ReturnURL': 'https://smart2pay-demo-db2.herokuapp.com/redirect',
                'Customer': {'Email': 'youremail@email.com'},
                'Card': {'HolderName': 'CH', 'Number': '333', 'ExpirationMonth': '11',
                         'ExpirationYear': '22', 'SecurityCode': '123'},
                'Capture': True,
                'GenerateCreditCardToken': True}})

    @mock.patch('requests.post')
    def test_checkouts_eur_ok(self, mock_post):
        payment = {
            "Payment": {
                "ID": 123,
                "Status": {"ID": 11, "Info": "Captured", "Reasons": []},
                "CreditCardToken": {"Value": "zxc"}
            }
        }
        mock_post.return_value = Resp(payment, 200)
        data = {
            "currency": "EUR",
            "price_USD": "11",
            "price_EUR": "7",
            "amount": "2",
            "card_holder": "CH",
            "card_number": "333",
            "card_exp_month": "11",
            "card_exp_year": "22",
            "card_cvv": "123",
        }
        res = self.app.post('/checkouts', data=data)
        self.assertEqual(res.status_code, 302)
        self.assertIn("/checkouts/123", res.location)
        mock_post.assert_called_with(
            'https://securetest.smart2pay.com/v1/payments',
            auth=mock.ANY,
            json={'Payment': {
                'MerchantTransactionID': mock.ANY,
                'Amount': 1400,
                'Currency': 'EUR',
                'ReturnURL': 'https://smart2pay-demo-db2.herokuapp.com/redirect',
                'Customer': {'Email': 'youremail@email.com'},
                'Card': {'HolderName': 'CH', 'Number': '333', 'ExpirationMonth': '11',
                         'ExpirationYear': '22', 'SecurityCode': '123'},
                'Capture': True,
                'GenerateCreditCardToken': True}})

    @mock.patch('requests.get')
    def test_show(self, mock_get):
        payment = {
            "Payment": {
                "ID": 123321,
                "Status": {"ID": 11, "Info": "Captured", "Reasons": []},
                "CreditCardToken": {"Value": "zxc"}
            }
        }
        with app.app.test_client() as c:
            with c.session_transaction() as sess:
                sess["payment"] = payment["Payment"]
            res = c.get('/checkouts/123')
        self.assertEqual(res.status_code, 200)
        self.assertIn(b"zxc", res.data)
        self.assertIn(b"123321", res.data)

    @mock.patch('requests.post')
    def test_checkout_more(self, mock_post):
        payment = {
            "Payment": {
                "ID": 12344,
                "Status": {"ID": 11, "Info": "Captured", "Reasons": []},
                "CreditCardToken": {"Value": "zxc"}
            }
        }
        mock_post.return_value = Resp(payment, 200)
        with app.app.test_client() as c:
            with c.session_transaction() as sess:
                sess["payment_method_token"] = {"Value": "xyz222"}
            res = c.post('/checkouts/one_more', data={"price": "123"})
        self.assertEqual(res.status_code, 302)
        self.assertIn("/checkouts/12344", res.location)
        mock_post.assert_called_with(
            'https://securetest.smart2pay.com/v1/payments',
            auth=mock.ANY,
            json={
                'Payment': {
                    'MerchantTransactionID': mock.ANY,
                    'Amount': 12300,
                    'Currency': 'USD',
                    'ReturnURL': 'https://smart2pay-demo-db2.herokuapp.com/redirect',
                    'Customer': {
                        'Email': 'youremail@email.com'},
                    'CreditCardToken': {
                        'Value': 'xyz222'},
                    'Capture': True,
                    'Retry': True,
                    'GenerateCreditCardToken': True}})

    @mock.patch('requests.post')
    @mock.patch('requests.get')
    def test_refund(self, mock_get, mock_post):
        payment = {
            "Payment": {
                "ID": 321,
                "Amount": "1200"
            }
        }
        mock_get.return_value = Resp(payment, 200)
        mock_post.return_value = Resp({"OK": "OK"}, 200)
        res = self.app.post('/refund', data={'payment_id': 321, "tx_id": "abc"})
        self.assertEqual(res.status_code, 200)
        self.assertIn(b"OK", res.data)
        mock_post.assert_called_with(
            'https://securetest.smart2pay.com/v1/payments/321/refunds',
            auth=mock.ANY,
            json={'Refund': {'MerchantTransactionID': 'abc', 'Amount': '1200'}})

    @mock.patch('requests.post')
    def test_refund_partial(self, mock_post):
        mock_post.return_value = Resp({"OK": "OK"}, 200)
        res = self.app.post('/refund/partial',
                            data={'payment_id': 321, "tx_id": "abc", "amount": 45})
        self.assertEqual(res.status_code, 200)
        self.assertIn(b"OK", res.data)
        mock_post.assert_called_with(
            'https://securetest.smart2pay.com/v1/payments/321/refunds',
            auth=mock.ANY,
            json={'Refund': {'MerchantTransactionID': 'abc', 'Amount': 4500}})

if __name__ == '__main__':
    unittest.main()


text:
class CreateItemHierarchies < ActiveRecord::Migration
  def change
    create_table :item_hierarchies ,  :id => false do |t|
      t.references :ancestor
      t.references :descendant
      t.integer :generation
      t.string :hierarchy_scope
      t.decimal :position
    end
    add_index :item_hierarchies,[:descendant_id,:hierarchy_scope]
    add_index :item_hierarchies,[:ancestor_id,:descendant_id,:hierarchy_scope],unique:true,name: 'idx_unq_item_hierachy_ancestor_descendant_scope'
    add_index :item_hierarchies,[:ancestor_id,:hierarchy_scope,:position],name: 'idx_ancestor_scope_position'
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE locale SYSTEM "../../../../../lib/pkp/dtd/locale.dtd">

<!--
  * plugins/auth/ldap/locale/el_GR/locale.xml
  *
  * Copyright (c) 2003-2013 John Willinsky
  * Distributed under the GNU GPL v2. For full terms see the file docs/COPYING.
  *
  * LDAP authentication plugin localization strings for the Greek locale.
  *
  * Translation by University of Patras, Library & Information Service
  * Vassilis Barkayannis (barkayannis@upatras.gr),
  * Panos Georgiou (panos@lis.upatras.gr),
  * Giannis Tsakonas (john@lis.upatras.gr),
  * Kiriazis Vasilis (vaskir@lis.upatras.gr),
  * Papaxristopoulos Leonidas (leonidasp@lis.upatras.gr)
  *
  -->

<locale name="el_GR" full_name="Greek">
	<message key="plugins.auth.ldap.displayName">LDAP</message>
	<message key="plugins.auth.ldap.description">Το plugin αυτό υποστηρίζει την πιστοποίηση και τον συγχρονισμό των λογαριασμών χρηστών βάση μιας εξωτερικής LDAP πηγής.</message>

	<message key="plugins.auth.ldap.settings">Ρυθμίσεις LDAP </message>
	<message key="plugins.auth.ldap.settings.hostname">Server hostname</message>
	<message key="plugins.auth.ldap.settings.hostname.description">Π.χ., "ldap.example.com", ή "ldaps://ldap.example.com" (για χρήση SSL)</message>
	<message key="plugins.auth.ldap.settings.port">Server port</message>
	<message key="plugins.auth.ldap.settings.port.description">Προαιρετικό. Αυτόματα στο 389 (LDAP) ή 636 (LDAP over SSL)</message>
	<message key="plugins.auth.ldap.settings.basedn">Base DN</message>
	<message key="plugins.auth.ldap.settings.basedn.description">Π.χ., "ou=people,dc=example,dc=com"</message>
	<message key="plugins.auth.ldap.settings.managerdn">Διαχειριστής DN</message>
	<message key="plugins.auth.ldap.settings.managerdn.description">Π.χ., "cn=Manager,dc=example,dc=com"</message>
	<message key="plugins.auth.ldap.settings.managerpwd">Κωδικός Πρόσβασης (password) Διαχειριστή</message>
	<message key="plugins.auth.ldap.settings.managerpwd.description">Ο Διαχειριστής DN και ο κωδικός πρόσβασης απαιτούνται μόνο αν είναι ενεργοποιημένες οι επιλογές συγχρονισμός προφίλ/κωδικός πρόρσβασης χρήστη ή δημιουργία χρήστη. Αν το LDAP θα χρησιμοποιηθεί αποκλειστικά για πιστοποίηση τότε αυτές οι επιλογές μπορούν να παραβλεφθούν.</message>
	<message key="plugins.auth.ldap.settings.pwhash">Password encryption</message>
	<message key="plugins.auth.ldap.settings.saslopt">SASL Ρυθμίσεις (προαιρετικό)</message>
	<message key="plugins.auth.ldap.settings.saslmech">SASL Μηχανισμός</message>
	<message key="plugins.auth.ldap.settings.saslmech.description">Π.χ., "DIGEST-MD5"</message>
	<message key="plugins.auth.ldap.settings.saslrealm">Realm</message>
	<message key="plugins.auth.ldap.settings.saslauthzid">Αίτηση ID πιστοποίησης</message>
	<message key="plugins.auth.ldap.settings.saslprop">Ιδιότητες ασφαλείας SASL </message>
	<message key="plugins.auth.ldap.settings.uid">Χαρακτηριστικό Λογαριασμού</message>
	<message key="plugins.auth.ldap.settings.uid.description">Χαρακτηριστική ιδιότητα, η τιμή της οποίας χαρακτηρίζει μοναδικά ένα αντικείμενο χρήστη, όπως uid ή cn ή sAMAccountName.</message>
</locale>


text:
/*
 * File Layout for: PR.PR_TAX_PROFILE_D on 21-May-01
 *
 * Payroll Tax Profile - County
 */

#pragma member_alignment save
#pragma nomember_alignment

struct pr_tax_profile_d_cdd
{
/* Element =
   Description = 'D' county authority */
	char auth[1];
/* Element =
   Description = Code */
	char code[2];
/* Element =
   Description = Report number */
	char repno[20];
/* Element = ACCOUNT
   Description = General Ledger Account Number */
	char wh_acct[18];
/* Element = ACCOUNT
   Description = General Ledger Account Number */
	char cou_lia_acct[18];
};
#pragma member_alignment restore


text:
use crate::process_error::ProcessError;
use crate::read2;

use anyhow::{bail, Context, Result};
use jobserver::Client;
use shell_escape::escape;
use tempfile::NamedTempFile;

use std::collections::BTreeMap;
use std::env;
use std::ffi::{OsStr, OsString};
use std::fmt;
use std::io::{self, Write};
use std::iter::once;
use std::path::Path;
use std::process::{Command, ExitStatus, Output, Stdio};

/// A builder object for an external process, similar to [`std::process::Command`].
#[derive(Clone, Debug)]
pub struct ProcessBuilder {
    /// The program to execute.
    program: OsString,
    /// A list of arguments to pass to the program.
    args: Vec<OsString>,
    /// Any environment variables that should be set for the program.
    env: BTreeMap<String, Option<OsString>>,
    /// The directory to run the program from.
    cwd: Option<OsString>,
    /// A list of wrappers that wrap the original program when calling
    /// [`ProcessBuilder::wrapped`]. The last one is the outermost one.
    wrappers: Vec<OsString>,
    /// The `make` jobserver. See the [jobserver crate] for
    /// more information.
    ///
    /// [jobserver crate]: https://docs.rs/jobserver/
    jobserver: Option<Client>,
    /// `true` to include environment variable in display.
    display_env_vars: bool,
    /// `true` to retry with an argfile if hitting "command line too big" error.
    /// See [`ProcessBuilder::retry_with_argfile`] for more information.
    retry_with_argfile: bool,
    /// Data to write to stdin.
    stdin: Vec<u8>,
}

impl fmt::Display for ProcessBuilder {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "`")?;

        if self.display_env_vars {
            for (key, val) in self.env.iter() {
                if let Some(val) = val {
                    let val = escape(val.to_string_lossy());
                    if cfg!(windows) {
                        write!(f, "set {}={}&& ", key, val)?;
                    } else {
                        write!(f, "{}={} ", key, val)?;
                    }
                }
            }
        }

        write!(f, "{}", self.get_program().to_string_lossy())?;

        for arg in self.get_args() {
            write!(f, " {}", escape(arg.to_string_lossy()))?;
        }

        write!(f, "`")
    }
}

impl ProcessBuilder {
    /// Creates a new [`ProcessBuilder`] with the given executable path.
    pub fn new<T: AsRef<OsStr>>(cmd: T) -> ProcessBuilder {
        ProcessBuilder {
            program: cmd.as_ref().to_os_string(),
            args: Vec::new(),
            cwd: None,
            env: BTreeMap::new(),
            wrappers: Vec::new(),
            jobserver: None,
            display_env_vars: false,
            retry_with_argfile: false,
            stdin: Vec::new(),
        }
    }

    /// (chainable) Sets the executable for the process.
    pub fn program<T: AsRef<OsStr>>(&mut self, program: T) -> &mut ProcessBuilder {
        self.program = program.as_ref().to_os_string();
        self
    }

    /// (chainable) Adds `arg` to the args list.
    pub fn arg<T: AsRef<OsStr>>(&mut self, arg: T) -> &mut ProcessBuilder {
        self.args.push(arg.as_ref().to_os_string());
        self
    }

    /// (chainable) Adds multiple `args` to the args list.
    pub fn args<T: AsRef<OsStr>>(&mut self, args: &[T]) -> &mut ProcessBuilder {
        self.args
            .extend(args.iter().map(|t| t.as_ref().to_os_string()));
        self
    }

    /// (chainable) Replaces the args list with the given `args`.
    pub fn args_replace<T: AsRef<OsStr>>(&mut self, args: &[T]) -> &mut ProcessBuilder {
        if let Some(program) = self.wrappers.pop() {
            // User intend to replace all args, so we
            // - use the outermost wrapper as the main program, and
            // - cleanup other inner wrappers.
            self.program = program;
            self.wrappers = Vec::new();
        }
        self.args = args.iter().map(|t| t.as_ref().to_os_string()).collect();
        self
    }

    /// (chainable) Sets the current working directory of the process.
    pub fn cwd<T: AsRef<OsStr>>(&mut self, path: T) -> &mut ProcessBuilder {
        self.cwd = Some(path.as_ref().to_os_string());
        self
    }

    /// (chainable) Sets an environment variable for the process.
    pub fn env<T: AsRef<OsStr>>(&mut self, key: &str, val: T) -> &mut ProcessBuilder {
        self.env
            .insert(key.to_string(), Some(val.as_ref().to_os_string()));
        self
    }

    /// (chainable) Unsets an environment variable for the process.
    pub fn env_remove(&mut self, key: &str) -> &mut ProcessBuilder {
        self.env.insert(key.to_string(), None);
        self
    }

    /// Gets the executable name.
    pub fn get_program(&self) -> &OsString {
        self.wrappers.last().unwrap_or(&self.program)
    }

    /// Gets the program arguments.
    pub fn get_args(&self) -> impl Iterator<Item = &OsString> {
        self.wrappers
            .iter()
            .rev()
            .chain(once(&self.program))
            .chain(self.args.iter())
            .skip(1) // Skip the main `program
    }

    /// Gets the current working directory for the process.
    pub fn get_cwd(&self) -> Option<&Path> {
        self.cwd.as_ref().map(Path::new)
    }

    /// Gets an environment variable as the process will see it (will inherit from environment
    /// unless explicitally unset).
    pub fn get_env(&self, var: &str) -> Option<OsString> {
        self.env
            .get(var)
            .cloned()
            .or_else(|| Some(env::var_os(var)))
            .and_then(|s| s)
    }

    /// Gets all environment variables explicitly set or unset for the process (not inherited
    /// vars).
    pub fn get_envs(&self) -> &BTreeMap<String, Option<OsString>> {
        &self.env
    }

    /// Sets the `make` jobserver. See the [jobserver crate][jobserver_docs] for
    /// more information.
    ///
    /// [jobserver_docs]: https://docs.rs/jobserver/0.1.6/jobserver/
    pub fn inherit_jobserver(&mut self, jobserver: &Client) -> &mut Self {
        self.jobserver = Some(jobserver.clone());
        self
    }

    /// Enables environment variable display.
    pub fn display_env_vars(&mut self) -> &mut Self {
        self.display_env_vars = true;
        self
    }

    /// Enables retrying with an argfile if hitting "command line too big" error
    ///
    /// This is primarily for the `@path` arg of rustc and rustdoc, which treat
    /// each line as an command-line argument, so `LF` and `CRLF` bytes are not
    /// valid as an argument for argfile at this moment.
    /// For example, `RUSTDOCFLAGS="--crate-version foo\nbar" cargo doc` is
    /// valid when invoking from command-line but not from argfile.
    ///
    /// To sum up, the limitations of the argfile are:
    ///
    /// - Must be valid UTF-8 encoded.
    /// - Must not contain any newlines in each argument.
    ///
    /// Ref:
    ///
    /// - https://doc.rust-lang.org/rustdoc/command-line-arguments.html#path-load-command-line-flags-from-a-path
    /// - https://doc.rust-lang.org/rustc/command-line-arguments.html#path-load-command-line-flags-from-a-path>
    pub fn retry_with_argfile(&mut self, enabled: bool) -> &mut Self {
        self.retry_with_argfile = enabled;
        self
    }

    /// Sets a value that will be written to stdin of the process on launch.
    pub fn stdin<T: Into<Vec<u8>>>(&mut self, stdin: T) -> &mut Self {
        self.stdin = stdin.into();
        self
    }

    fn should_retry_with_argfile(&self, err: &io::Error) -> bool {
        self.retry_with_argfile && imp::command_line_too_big(err)
    }

    /// Like [`Command::status`] but with a better error message.
    pub fn status(&self) -> Result<ExitStatus> {
        self._status()
            .with_context(|| ProcessError::could_not_execute(self))
    }

    fn _status(&self) -> io::Result<ExitStatus> {
        if !debug_force_argfile(self.retry_with_argfile) {
            let mut cmd = self.build_command();
            match cmd.spawn() {
                Err(ref e) if self.should_retry_with_argfile(e) => {}
                Err(e) => return Err(e),
                Ok(mut child) => return child.wait(),
            }
        }
        let (mut cmd, argfile) = self.build_command_with_argfile()?;
        let status = cmd.spawn()?.wait();
        close_tempfile_and_log_error(argfile);
        status
    }

    /// Runs the process, waiting for completion, and mapping non-success exit codes to an error.
    pub fn exec(&self) -> Result<()> {
        let exit = self.status()?;
        if exit.success() {
            Ok(())
        } else {
            Err(ProcessError::new(
                &format!("process didn't exit successfully: {}", self),
                Some(exit),
                None,
            )
            .into())
        }
    }

    /// Replaces the current process with the target process.
    ///
    /// On Unix, this executes the process using the Unix syscall `execvp`, which will block
    /// this process, and will only return if there is an error.
    ///
    /// On Windows this isn't technically possible. Instead we emulate it to the best of our
    /// ability. One aspect we fix here is that we specify a handler for the Ctrl-C handler.
    /// In doing so (and by effectively ignoring it) we should emulate proxying Ctrl-C
    /// handling to the application at hand, which will either terminate or handle it itself.
    /// According to Microsoft's documentation at
    /// <https://docs.microsoft.com/en-us/windows/console/ctrl-c-and-ctrl-break-signals>.
    /// the Ctrl-C signal is sent to all processes attached to a terminal, which should
    /// include our child process. If the child terminates then we'll reap them in Cargo
    /// pretty quickly, and if the child handles the signal then we won't terminate
    /// (and we shouldn't!) until the process itself later exits.
    pub fn exec_replace(&self) -> Result<()> {
        imp::exec_replace(self)
    }

    /// Like [`Command::output`] but with a better error message.
    pub fn output(&self) -> Result<Output> {
        self._output()
            .with_context(|| ProcessError::could_not_execute(self))
    }

    fn _output(&self) -> io::Result<Output> {
        if !debug_force_argfile(self.retry_with_argfile) {
            let mut cmd = self.build_command();
            match piped(&mut cmd).spawn() {
                Err(ref e) if self.should_retry_with_argfile(e) => {}
                Err(e) => return Err(e),
                Ok(mut child) => {
                    child.stdin.take().unwrap().write_all(&self.stdin)?;
                    return child.wait_with_output();
                }
            }
        }
        let (mut cmd, argfile) = self.build_command_with_argfile()?;
        let mut child = piped(&mut cmd).spawn()?;
        child.stdin.take().unwrap().write_all(&self.stdin)?;
        let output = child.wait_with_output();
        close_tempfile_and_log_error(argfile);
        output
    }

    /// Executes the process, returning the stdio output, or an error if non-zero exit status.
    pub fn exec_with_output(&self) -> Result<Output> {
        let output = self.output()?;
        if output.status.success() {
            Ok(output)
        } else {
            Err(ProcessError::new(
                &format!("process didn't exit successfully: {}", self),
                Some(output.status),
                Some(&output),
            )
            .into())
        }
    }

    /// Executes a command, passing each line of stdout and stderr to the supplied callbacks, which
    /// can mutate the string data.
    ///
    /// If any invocations of these function return an error, it will be propagated.
    ///
    /// If `capture_output` is true, then all the output will also be buffered
    /// and stored in the returned `Output` object. If it is false, no caching
    /// is done, and the callbacks are solely responsible for handling the
    /// output.
    pub fn exec_with_streaming(
        &self,
        on_stdout_line: &mut dyn FnMut(&str) -> Result<()>,
        on_stderr_line: &mut dyn FnMut(&str) -> Result<()>,
        capture_output: bool,
    ) -> Result<Output> {
        let mut stdout = Vec::new();
        let mut stderr = Vec::new();

        let mut callback_error = None;
        let mut stdout_pos = 0;
        let mut stderr_pos = 0;

        let spawn = |mut cmd| {
            if !debug_force_argfile(self.retry_with_argfile) {
                match piped(&mut cmd).spawn() {
                    Err(ref e) if self.should_retry_with_argfile(e) => {}
                    Err(e) => return Err(e),
                    Ok(child) => return Ok((child, None)),
                }
            }
            let (mut cmd, argfile) = self.build_command_with_argfile()?;
            Ok((piped(&mut cmd).spawn()?, Some(argfile)))
        };

        let status = (|| {
            let cmd = self.build_command();
            let (mut child, argfile) = spawn(cmd)?;
            let out = child.stdout.take().unwrap();
            let err = child.stderr.take().unwrap();
            read2(out, err, &mut |is_out, data, eof| {
                let pos = if is_out {
                    &mut stdout_pos
                } else {
                    &mut stderr_pos
                };
                let idx = if eof {
                    data.len()
                } else {
                    match data[*pos..].iter().rposition(|b| *b == b'\n') {
                        Some(i) => *pos + i + 1,
                        None => {
                            *pos = data.len();
                            return;
                        }
                    }
                };

                let new_lines = &data[..idx];

                for line in String::from_utf8_lossy(new_lines).lines() {
                    if callback_error.is_some() {
                        break;
                    }
                    let callback_result = if is_out {
                        on_stdout_line(line)
                    } else {
                        on_stderr_line(line)
                    };
                    if let Err(e) = callback_result {
                        callback_error = Some(e);
                        break;
                    }
                }

                if capture_output {
                    let dst = if is_out { &mut stdout } else { &mut stderr };
                    dst.extend(new_lines);
                }

                data.drain(..idx);
                *pos = 0;
            })?;
            let status = child.wait();
            if let Some(argfile) = argfile {
                close_tempfile_and_log_error(argfile);
            }
            status
        })()
        .with_context(|| ProcessError::could_not_execute(self))?;
        let output = Output {
            status,
            stdout,
            stderr,
        };

        {
            let to_print = if capture_output { Some(&output) } else { None };
            if let Some(e) = callback_error {
                let cx = ProcessError::new(
                    &format!("failed to parse process output: {}", self),
                    Some(output.status),
                    to_print,
                );
                bail!(anyhow::Error::new(cx).context(e));
            } else if !output.status.success() {
                bail!(ProcessError::new(
                    &format!("process didn't exit successfully: {}", self),
                    Some(output.status),
                    to_print,
                ));
            }
        }

        Ok(output)
    }

    /// Builds the command with an `@<path>` argfile that contains all the
    /// arguments. This is primarily served for rustc/rustdoc command family.
    fn build_command_with_argfile(&self) -> io::Result<(Command, NamedTempFile)> {
        use std::io::Write as _;

        let mut tmp = tempfile::Builder::new()
            .prefix("cargo-argfile.")
            .tempfile()?;

        let mut arg = OsString::from("@");
        arg.push(tmp.path());
        let mut cmd = self.build_command_without_args();
        cmd.arg(arg);
        log::debug!("created argfile at {} for {self}", tmp.path().display());

        let cap = self.get_args().map(|arg| arg.len() + 1).sum::<usize>();
        let mut buf = Vec::with_capacity(cap);
        for arg in &self.args {
            let arg = arg.to_str().ok_or_else(|| {
                io::Error::new(
                    io::ErrorKind::Other,
                    format!(
                        "argument for argfile contains invalid UTF-8 characters: `{}`",
                        arg.to_string_lossy()
                    ),
                )
            })?;
            if arg.contains('\n') {
                return Err(io::Error::new(
                    io::ErrorKind::Other,
                    format!("argument for argfile contains newlines: `{arg}`"),
                ));
            }
            writeln!(buf, "{arg}")?;
        }
        tmp.write_all(&mut buf)?;
        Ok((cmd, tmp))
    }

    /// Builds a command from `ProcessBuilder` for everything but not `args`.
    fn build_command_without_args(&self) -> Command {
        let mut command = {
            let mut iter = self.wrappers.iter().rev().chain(once(&self.program));
            let mut cmd = Command::new(iter.next().expect("at least one `program` exists"));
            cmd.args(iter);
            cmd
        };
        if let Some(cwd) = self.get_cwd() {
            command.current_dir(cwd);
        }
        for (k, v) in &self.env {
            match *v {
                Some(ref v) => {
                    command.env(k, v);
                }
                None => {
                    command.env_remove(k);
                }
            }
        }
        if let Some(ref c) = self.jobserver {
            c.configure(&mut command);
        }
        command
    }

    /// Converts `ProcessBuilder` into a `std::process::Command`, and handles
    /// the jobserver, if present.
    ///
    /// Note that this method doesn't take argfile fallback into account. The
    /// caller should handle it by themselves.
    pub fn build_command(&self) -> Command {
        let mut command = self.build_command_without_args();
        for arg in &self.args {
            command.arg(arg);
        }
        command
    }

    /// Wraps an existing command with the provided wrapper, if it is present and valid.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use cargo_util::ProcessBuilder;
    /// // Running this would execute `rustc`
    /// let cmd = ProcessBuilder::new("rustc");
    ///
    /// // Running this will execute `sccache rustc`
    /// let cmd = cmd.wrapped(Some("sccache"));
    /// ```
    pub fn wrapped(mut self, wrapper: Option<impl AsRef<OsStr>>) -> Self {
        if let Some(wrapper) = wrapper.as_ref() {
            let wrapper = wrapper.as_ref();
            if !wrapper.is_empty() {
                self.wrappers.push(wrapper.to_os_string());
            }
        }
        self
    }
}

/// Forces the command to use `@path` argfile.
///
/// You should set `__CARGO_TEST_FORCE_ARGFILE` to enable this.
fn debug_force_argfile(retry_enabled: bool) -> bool {
    cfg!(debug_assertions) && env::var("__CARGO_TEST_FORCE_ARGFILE").is_ok() && retry_enabled
}

/// Creates new pipes for stderr, stdout and stdin.
fn piped(cmd: &mut Command) -> &mut Command {
    cmd.stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .stdin(Stdio::piped())
}

fn close_tempfile_and_log_error(file: NamedTempFile) {
    file.close().unwrap_or_else(|e| {
        log::warn!("failed to close temporary file: {e}");
    });
}

#[cfg(unix)]
mod imp {
    use super::{close_tempfile_and_log_error, debug_force_argfile, ProcessBuilder, ProcessError};
    use anyhow::Result;
    use std::io;
    use std::os::unix::process::CommandExt;

    pub fn exec_replace(process_builder: &ProcessBuilder) -> Result<()> {
        let mut error;
        let mut file = None;
        if debug_force_argfile(process_builder.retry_with_argfile) {
            let (mut command, argfile) = process_builder.build_command_with_argfile()?;
            file = Some(argfile);
            error = command.exec()
        } else {
            let mut command = process_builder.build_command();
            error = command.exec();
            if process_builder.should_retry_with_argfile(&error) {
                let (mut command, argfile) = process_builder.build_command_with_argfile()?;
                file = Some(argfile);
                error = command.exec()
            }
        }
        if let Some(file) = file {
            close_tempfile_and_log_error(file);
        }

        Err(anyhow::Error::from(error).context(ProcessError::new(
            &format!("could not execute process {}", process_builder),
            None,
            None,
        )))
    }

    pub fn command_line_too_big(err: &io::Error) -> bool {
        err.raw_os_error() == Some(libc::E2BIG)
    }
}

#[cfg(windows)]
mod imp {
    use super::{ProcessBuilder, ProcessError};
    use anyhow::Result;
    use std::io;
    use winapi::shared::minwindef::{BOOL, DWORD, FALSE, TRUE};
    use winapi::um::consoleapi::SetConsoleCtrlHandler;

    unsafe extern "system" fn ctrlc_handler(_: DWORD) -> BOOL {
        // Do nothing; let the child process handle it.
        TRUE
    }

    pub fn exec_replace(process_builder: &ProcessBuilder) -> Result<()> {
        unsafe {
            if SetConsoleCtrlHandler(Some(ctrlc_handler), TRUE) == FALSE {
                return Err(ProcessError::new("Could not set Ctrl-C handler.", None, None).into());
            }
        }

        // Just execute the process as normal.
        process_builder.exec()
    }

    pub fn command_line_too_big(err: &io::Error) -> bool {
        use winapi::shared::winerror::ERROR_FILENAME_EXCED_RANGE;
        err.raw_os_error() == Some(ERROR_FILENAME_EXCED_RANGE as i32)
    }
}

#[cfg(test)]
mod tests {
    use super::ProcessBuilder;
    use std::fs;

    #[test]
    fn argfile_build_succeeds() {
        let mut cmd = ProcessBuilder::new("echo");
        cmd.args(["foo", "bar"].as_slice());
        let (cmd, argfile) = cmd.build_command_with_argfile().unwrap();

        assert_eq!(cmd.get_program(), "echo");
        let cmd_args: Vec<_> = cmd.get_args().map(|s| s.to_str().unwrap()).collect();
        assert_eq!(cmd_args.len(), 1);
        assert!(cmd_args[0].starts_with("@"));
        assert!(cmd_args[0].contains("cargo-argfile."));

        let buf = fs::read_to_string(argfile.path()).unwrap();
        assert_eq!(buf, "foo\nbar\n");
    }

    #[test]
    fn argfile_build_fails_if_arg_contains_newline() {
        let mut cmd = ProcessBuilder::new("echo");
        cmd.arg("foo\n");
        let err = cmd.build_command_with_argfile().unwrap_err();
        assert_eq!(
            err.to_string(),
            "argument for argfile contains newlines: `foo\n`"
        );
    }

    #[test]
    fn argfile_build_fails_if_arg_contains_invalid_utf8() {
        let mut cmd = ProcessBuilder::new("echo");

        #[cfg(windows)]
        let invalid_arg = {
            use std::os::windows::prelude::*;
            std::ffi::OsString::from_wide(&[0x0066, 0x006f, 0xD800, 0x006f])
        };

        #[cfg(unix)]
        let invalid_arg = {
            use std::os::unix::ffi::OsStrExt;
            std::ffi::OsStr::from_bytes(&[0x66, 0x6f, 0x80, 0x6f]).to_os_string()
        };

        cmd.arg(invalid_arg);
        let err = cmd.build_command_with_argfile().unwrap_err();
        assert_eq!(
            err.to_string(),
            "argument for argfile contains invalid UTF-8 characters: `fo�o`"
        );
    }
}