text:
using Facility.Core.Assertions;
using FluentAssertions;
using NUnit.Framework;

namespace Facility.Core.UnitTests;

[TestFixtureSource(nameof(JsonServiceSerializers))]
public class ServiceResultJsonTests : JsonServiceSerializerTestsBase
{
	public ServiceResultJsonTests(JsonServiceSerializer jsonSerializer)
		: base(jsonSerializer)
	{
	}

	[Test]
	public void NoValueSuccessJson()
	{
		var before = ServiceResult.Success();
		var json = JsonSerializer.ToJson(before);
		json.Should().Be("{}");
		var after = JsonSerializer.FromJson<ServiceResult>(json);
		after.Should().BeResult(before);
	}

	[Test]
	public void NoValueEmptyFailureJson()
	{
		var before = ServiceResult.Failure(new ServiceErrorDto());
		var json = JsonSerializer.ToJson(before);
		json.Should().Be("{\"error\":{}}");
		var after = JsonSerializer.FromJson<ServiceResult>(json);
		after.Should().BeResult(before);
	}

	[Test]
	public void NoValueFailureJson()
	{
		var before = ServiceResult.Failure(new ServiceErrorDto("Xyzzy", "Xyzzy unexpected."));
		var json = JsonSerializer.ToJson(before);
		json.Should().Be("{\"error\":{\"code\":\"Xyzzy\",\"message\":\"Xyzzy unexpected.\"}}");
		var after = JsonSerializer.FromJson<ServiceResult>(json);
		after.Should().BeResult(before);
	}

	[Test]
	public void IntegerSuccessJson()
	{
		var before = ServiceResult.Success(1337);
		var json = JsonSerializer.ToJson(before);
		json.Should().Be("{\"value\":1337}");
		var after = JsonSerializer.FromJson<ServiceResult<int>>(json);
		after.Should().BeResult(before);
	}

	[Test]
	public void IntegerEmptyFailureJson()
	{
		var before = ServiceResult.Failure(new ServiceErrorDto());
		var json = JsonSerializer.ToJson(before);
		json.Should().Be("{\"error\":{}}");
		var after = JsonSerializer.FromJson<ServiceResult<int?>>(json);
		after.Should().BeResult(before);
	}

	[Test]
	public void IntegerFailureJson()
	{
		var before = ServiceResult.Failure(new ServiceErrorDto("Xyzzy", "Xyzzy unexpected."));
		var json = JsonSerializer.ToJson(before);
		json.Should().Be("{\"error\":{\"code\":\"Xyzzy\",\"message\":\"Xyzzy unexpected.\"}}");
		var after = JsonSerializer.FromJson<ServiceResult<int>>(json);
		after.Should().BeResult(before);
	}

	[Test]
	public void NullIntegerSuccessJson()
	{
		var before = ServiceResult.Success(default(int?));
		var json = JsonSerializer.ToJson(before);
		json.Should().Be("{\"value\":null}");
		var after = JsonSerializer.FromJson<ServiceResult<int?>>(json);
		after.Should().BeResult(before);
	}

	[Test]
	public void MissingValueIntegerSuccessJson()
	{
		var before = ServiceResult.Success(default(int?));
		const string json = "{}";
		var after = JsonSerializer.FromJson<ServiceResult<int?>>(json);
		after.Should().BeResult(before);
	}

	[Test]
	public void ValueAndErrorThrows()
	{
		const string json = "{\"value\":1337,\"error\":{}}";
		Assert.Throws<ServiceSerializationException>(() => JsonSerializer.FromJson<ServiceResult<int?>>(json));
	}

	[Test]
	public void ExtraFieldSuccessJson()
	{
		var before = ServiceResult.Success(1337);
		var json = "{\"values\":1337,\"value\":1337,\"valuex\":1337}";
		var after = JsonSerializer.FromJson<ServiceResult<int>>(json);
		after.Should().BeResult(before);
	}

	[Test]
	public void ExtraFieldFailureJson()
	{
		var before = ServiceResult.Failure(new ServiceErrorDto());
		var json = "{\"values\":1337,\"error\":{},\"valuex\":1337}";
		var after = JsonSerializer.FromJson<ServiceResult<int>>(json);
		after.Should().BeResult(before);
	}
}

redpajama_set_name: RedPajamaGithub


text:
jams
====

This project migrated to [marldev/jams](https://github.com/marl/jams/).


text:
<?php
/**
 *
 *
 * @author joshuag
 * @created: 04/08/2015 09:03
 * @project libphonenumber-for-php
 */

namespace libphonenumber;

class MultiFileMetadataSourceImpl implements MetadataSourceInterface
{
    protected static $metaDataFilePrefix = PhoneNumberUtil::META_DATA_FILE_PREFIX;

    /**
     * A mapping from a region code to the PhoneMetadata for that region.
     * @var PhoneMetadata[]
     */
    protected $regionToMetadataMap = array();

    /**
     * A mapping from a country calling code for a non-geographical entity to the PhoneMetadata for
     * that country calling code. Examples of the country calling codes include 800 (International
     * Toll Free Service) and 808 (International Shared Cost Service).
     * @var PhoneMetadata[]
     */
    protected $countryCodeToNonGeographicalMetadataMap = array();

    /**
     * The prefix of the metadata files from which region data is loaded.
     * @var String
     */
    protected $currentFilePrefix;

    /**
     * The metadata loader used to inject alternative metadata sources.
     * @var MetadataLoaderInterface
     */
    protected $metadataLoader;

    /**
     * @param MetadataLoaderInterface $metadataLoader
     * @param string|null $currentFilePrefix
     */
    public function __construct(MetadataLoaderInterface $metadataLoader, $currentFilePrefix = null)
    {
        if ($currentFilePrefix === null) {
            $currentFilePrefix = static::$metaDataFilePrefix;
        }

        $this->currentFilePrefix = $currentFilePrefix;
        $this->metadataLoader = $metadataLoader;
    }

    /**
     * @inheritdoc
     */
    public function getMetadataForRegion($regionCode)
    {
        $regionCode = strtoupper($regionCode);

        if (!array_key_exists($regionCode, $this->regionToMetadataMap)) {
            // The regionCode here will be valid and won't be '001', so we don't need to worry about
            // what to pass in for the country calling code.
            $this->loadMetadataFromFile($this->currentFilePrefix, $regionCode, 0, $this->metadataLoader);
        }

        return $this->regionToMetadataMap[$regionCode];
    }

    /**
     * @inheritdoc
     */
    public function getMetadataForNonGeographicalRegion($countryCallingCode)
    {
        if (!array_key_exists($countryCallingCode, $this->countryCodeToNonGeographicalMetadataMap)) {
            $this->loadMetadataFromFile($this->currentFilePrefix, PhoneNumberUtil::REGION_CODE_FOR_NON_GEO_ENTITY, $countryCallingCode, $this->metadataLoader);
        }

        return $this->countryCodeToNonGeographicalMetadataMap[$countryCallingCode];
    }

    /**
     * @param string $filePrefix
     * @param string $regionCode
     * @param int $countryCallingCode
     * @param MetadataLoaderInterface $metadataLoader
     * @throws \RuntimeException
     */
    public function loadMetadataFromFile($filePrefix, $regionCode, $countryCallingCode, MetadataLoaderInterface $metadataLoader)
    {
        $regionCode = strtoupper($regionCode);

        $isNonGeoRegion = PhoneNumberUtil::REGION_CODE_FOR_NON_GEO_ENTITY === $regionCode;
        $fileName = $filePrefix . '_' . ($isNonGeoRegion ? $countryCallingCode : $regionCode) . '.php';
        if (!is_readable($fileName)) {
            throw new \RuntimeException('missing metadata: ' . $fileName);
        }

        $data = $metadataLoader->loadMetadata($fileName);
        $metadata = new PhoneMetadata();
        $metadata->fromArray($data);
        if ($isNonGeoRegion) {
            $this->countryCodeToNonGeographicalMetadataMap[$countryCallingCode] = $metadata;
        } else {
            $this->regionToMetadataMap[$regionCode] = $metadata;
        }
    }
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Opuntia reflexispina Wiggins & Rollins

### Remarks
null


text:
<?php namespace App\Events;

use App\Events\Event;
use Sanghaplanner\Users\User;
use Sanghaplanner\Sanghas\Sangha;
use Illuminate\Queue\SerializesModels;

class MemberAlreadyExists extends Event
{

    use SerializesModels;

    /**
     * @var User $user
     */
    public $user;

    /**
     * @var Sangha $sangha
     */
    public $sangha;

    /**
     * @param User $user
     * @param Sangha $sangha
     */
    public function __construct($user, $sangha)
    {
        $this->user = $user;
        $this->sangha = $sangha;
    }
}


text:
<DescribeImagesResponse xmlns="http://ec2.amazonaws.com/doc/2009-11-30/">
  <imagesSet>
    <item>
      <imageId>ami-0</imageId>
      <imageLocation>ec2-public-images/fedora-8-i386-base-v1.04.manifest.xml
      </imageLocation>
      <imageState>available</imageState>
      <imageOwnerId>206029621532</imageOwnerId>
      <isPublic>false</isPublic>
      <productCodes>
        <item>
          <productCode>9961934F</productCode>
        </item>
      </productCodes>
      <architecture>i386</architecture>
      <imageType>machine</imageType>
      <kernelId>aki-4438dd2d</kernelId>
      <ramdiskId>ari-4538dd2c</ramdiskId>
      <rootDeviceType>instance-store</rootDeviceType>
      <blockDeviceMapping />
      <virtualizationType>paravirtual</virtualizationType>
    </item>
  </imagesSet>
</DescribeImagesResponse>


text:
import org.apache.solr.common.*;
import org.apache.solr.core.CoreContainer;
import org.apache.solr.client.solrj.*;
import org.apache.solr.client.solrj.beans.Field;
import org.apache.solr.client.solrj.embedded.EmbeddedSolrServer;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import java.io.FileNotFoundException;

import java.io.File;

public class ClientSolrj {

    public static void main(String[] args) {
        if (args.length == 0){
            runRemoteExample(); //connect to localhost
        } else{
            runEmbeddedExample(args[0]);
        }
    }

    private static void runRemoteExample() {
        SolrServer solr = new HttpSolrServer("http://localhost:8983/solr/solrj");
        listCollectionContent(solr, "Running in remote mode");

        SolrInputDocument doc = new SolrInputDocument();
        doc.addField("id", "email3");
        doc.addField("addr_from", "maija@acme.example.com");
        doc.addField("addr_to","kari@acme.example.com");
        doc.addField("addr_to","vania@home.example.com");
        doc.addField("subject","Re: Updating vacancy description");
        try {
            solr.add(doc);
            solr.commit();
        } catch (Exception e) {
            //Catch and ignore over-generic exception. Do NOT do this in production
            e.printStackTrace();
        }
        listCollectionContent(solr, "Added record in remote mode");
        solr.shutdown();
    }

    public static class Email{
        @Field String id, addr_from, subject;
        @Field String[] addr_to;
    }
    private static void runEmbeddedExample(String solrHomePath) {
        File coreConfig = new File(solrHomePath, "solr-solrj.xml" );
        CoreContainer container = null;
        try {
            container = new CoreContainer( solrHomePath, coreConfig);
        } catch (FileNotFoundException ex) {throw new RuntimeException(ex);}
        EmbeddedSolrServer solr = new EmbeddedSolrServer( container, "solrj" );
        listCollectionContent(solr, "Running in embedded mode");
        Email doc = new Email();
        doc.id = "email4";
        doc.addr_from = "kari@acme.example.com";
        doc.addr_to = new String[]{"maija@acme.example.com", "vania@home.example.com"};
        doc.subject = "Thanks (Was Re: Updating vacancy description)";
        try {
            solr.addBean(doc);
            solr.commit();
        } catch (Exception e) {
            //Catch and ignore over-generic exception. Do NOT do this in production
            e.printStackTrace();
        }
        listCollectionContent(solr, "Added record in embedded mode");

        solr.shutdown();
    }

    private static void listCollectionContent(SolrServer solr, String message) {
        System.out.println("\n------------------\n");
        System.out.println(message);
        SolrQuery parameters = new SolrQuery();
        parameters.set("q", "*:*");
        QueryResponse response = null;
        try {
            response = solr.query(parameters);
        } catch (SolrServerException e) {
            e.printStackTrace();
        }
        SolrDocumentList list = response.getResults();
        for (SolrDocument doc: list)
        {
            System.out.println(doc);
        }
        System.out.println("\n------------------\n");
    }
}


text:
	this->callMap[SysCall##name::GetCallNum()] = new SysCall##name()
SINGLETON_CPP(SystemCallEntry)
{
	ADD_SYSTEM_CALL(CreateThread);
	ADD_SYSTEM_CALL(Log);
	ADD_SYSTEM_CALL(SendMessageTo);
	ADD_SYSTEM_CALL(ReceiveAll);
	ADD_SYSTEM_CALL(ReceiveFrom);
	ADD_SYSTEM_CALL(ReadDataFromThread);
	ADD_SYSTEM_CALL(WriteToPhisicalAddr);
	Interrupt::Instance()->RegisterIRQ(Call,SYSCALL_IRQ_NUM);
	Interrupt::Instance()->SetDPLOfIRQ(SYSCALL_IRQ_NUM,1);
}
int SystemCallEntry::Call(InterruptParams& params)
{
	Interrupt::Instance()->Cli();
	auto ins = SystemCallEntry::Instance();
	auto ite = ins->callMap.Find(params.eax);
	if(ite==ins->callMap.End())
	{
		params.eax = -1;
		return -1;
	}
	else
	{
		int res = ite->second->Call(params.ebx
				,params.ecx
				,params.edx
				,params.esi,params);
		params.eax = res;
		return 1;
	}
	Interrupt::Instance()->Sti();
}


text:
namespace content {

// Test implementation of ImageTransportFactory and ContextFactory. This class
// tries to do very little, mostly setting up HostFrameSinkManager and returning
// fake implementations where possible.
class TestImageTransportFactory : public ui::ContextFactory,
                                  public ImageTransportFactory {
 public:
  TestImageTransportFactory();

  TestImageTransportFactory(const TestImageTransportFactory&) = delete;
  TestImageTransportFactory& operator=(const TestImageTransportFactory&) =
      delete;

  ~TestImageTransportFactory() override;

  // ui::ContextFactory implementation.
  void CreateLayerTreeFrameSink(
      base::WeakPtr<ui::Compositor> compositor) override;
  scoped_refptr<viz::ContextProvider> SharedMainThreadContextProvider()
      override;
  scoped_refptr<viz::RasterContextProvider>
  SharedMainThreadRasterContextProvider() override;
  void RemoveCompositor(ui::Compositor* compositor) override {}
  gpu::GpuMemoryBufferManager* GetGpuMemoryBufferManager() override;
  cc::TaskGraphRunner* GetTaskGraphRunner() override;
  viz::FrameSinkId AllocateFrameSinkId() override;
  viz::SubtreeCaptureId AllocateSubtreeCaptureId() override;
  viz::HostFrameSinkManager* GetHostFrameSinkManager() override;

  // ImageTransportFactory implementation.
  void DisableGpuCompositing() override;
  ui::ContextFactory* GetContextFactory() override;

 private:
  cc::TestTaskGraphRunner task_graph_runner_;
  viz::TestImageFactory image_factory_;
  viz::TestGpuMemoryBufferManager gpu_memory_buffer_manager_;
  viz::RendererSettings renderer_settings_;
  viz::FrameSinkIdAllocator frame_sink_id_allocator_;
  viz::SubtreeCaptureIdAllocator subtree_capture_id_allocator_;
  scoped_refptr<viz::ContextProvider> shared_main_context_provider_;
  viz::HostFrameSinkManager host_frame_sink_manager_;
  viz::TestFrameSinkManagerImpl test_frame_sink_manager_impl_;
};

}  // namespace content

#endif  // CONTENT_BROWSER_COMPOSITOR_TEST_TEST_IMAGE_TRANSPORT_FACTORY_H_


text:
extern crate remove_dir_all;

use std::char::from_u32;
use std::env;
use std::error;
use std::ffi::{OsStr, OsString};
use std::fmt;
use std::fs;
use std::io::Write;
use std::io;
use std::path::Path;
use std::process::{Command, ExitStatus};
use std::str;

use rand::random;

pub fn ensure_dir_exists<P: AsRef<Path>, F: FnOnce(&Path)>(path: P,
                                                           callback: F)
                                                           -> io::Result<bool> {
    if !is_directory(path.as_ref()) {
        callback(path.as_ref());
        fs::create_dir_all(path.as_ref()).map(|()| true)
    } else {
        Ok(false)
    }
}

pub fn is_directory<P: AsRef<Path>>(path: P) -> bool {
    fs::metadata(path).ok().as_ref().map(fs::Metadata::is_dir) == Some(true)
}

pub fn is_file<P: AsRef<Path>>(path: P) -> bool {
    fs::metadata(path).ok().as_ref().map(fs::Metadata::is_file) == Some(true)
}

pub fn path_exists<P: AsRef<Path>>(path: P) -> bool {
    fs::metadata(path).is_ok()
}

pub fn random_string(length: usize) -> String {
    let chars = b"abcdefghijklmnopqrstuvwxyz0123456789_";
    (0..length).map(|_| from_u32(chars[random::<usize>() % chars.len()] as u32).unwrap()).collect()
}

pub fn if_not_empty<S: PartialEq<str>>(s: S) -> Option<S> {
    if s == *"" {
        None
    } else {
        Some(s)
    }
}

pub fn write_file(path: &Path, contents: &str) -> io::Result<()> {
    let mut file = try!(fs::OpenOptions::new()
                            .write(true)
                            .truncate(true)
                            .create(true)
                            .open(path));

    try!(io::Write::write_all(&mut file, contents.as_bytes()));

    try!(file.sync_data());

    Ok(())
}

pub fn read_file(path: &Path) -> io::Result<String> {
    let mut file = try!(fs::OpenOptions::new()
                            .read(true)
                            .open(path));

    let mut contents = String::new();

    try!(io::Read::read_to_string(&mut file, &mut contents));

    Ok(contents)
}

pub fn filter_file<F: FnMut(&str) -> bool>(src: &Path,
                                           dest: &Path,
                                           mut filter: F)
                                           -> io::Result<usize> {
    let src_file = try!(fs::File::open(src));
    let dest_file = try!(fs::File::create(dest));

    let mut reader = io::BufReader::new(src_file);
    let mut writer = io::BufWriter::new(dest_file);
    let mut removed = 0;

    for result in io::BufRead::lines(&mut reader) {
        let line = try!(result);
        if filter(&line) {
            try!(writeln!(&mut writer, "{}", &line));
        } else {
            removed += 1;
        }
    }

    try!(writer.flush());

    Ok(removed)
}

pub fn match_file<T, F: FnMut(&str) -> Option<T>>(src: &Path, mut f: F) -> io::Result<Option<T>> {
    let src_file = try!(fs::File::open(src));

    let mut reader = io::BufReader::new(src_file);

    for result in io::BufRead::lines(&mut reader) {
        let line = try!(result);
        if let Some(r) = f(&line) {
            return Ok(Some(r));
        }
    }

    Ok(None)
}

pub fn append_file(dest: &Path, line: &str) -> io::Result<()> {
    let mut dest_file = try!(fs::OpenOptions::new()
                                 .write(true)
                                 .append(true)
                                 .create(true)
                                 .open(dest));

    try!(writeln!(&mut dest_file, "{}", line));

    try!(dest_file.sync_data());

    Ok(())
}

pub fn tee_file<W: io::Write>(path: &Path, mut w: &mut W) -> io::Result<()> {
    let mut file = try!(fs::OpenOptions::new()
                            .read(true)
                            .open(path));

    let buffer_size = 0x10000;
    let mut buffer = vec![0u8; buffer_size];

    loop {
        let bytes_read = try!(io::Read::read(&mut file, &mut buffer));

        if bytes_read != 0 {
            try!(io::Write::write_all(w, &mut buffer[0..bytes_read]));
        } else {
            return Ok(());
        }
    }
}

pub fn symlink_dir(src: &Path, dest: &Path) -> io::Result<()> {
    #[cfg(windows)]
    fn symlink_dir_inner(src: &Path, dest: &Path) -> io::Result<()> {
        // std's symlink uses Windows's symlink function, which requires
        // admin. We can create directory junctions the hard way without
        // though.
        symlink_junction_inner(src, dest)
    }
    #[cfg(not(windows))]
    fn symlink_dir_inner(src: &Path, dest: &Path) -> io::Result<()> {
        ::std::os::unix::fs::symlink(src, dest)
    }

    let _ = remove_dir(dest);
    symlink_dir_inner(src, dest)
}

// Creating a directory junction on windows involves dealing with reparse
// points and the DeviceIoControl function, and this code is a skeleton of
// what can be found here:
//
// http://www.flexhex.com/docs/articles/hard-links.phtml
//
// Copied from std
#[cfg(windows)]
#[allow(non_snake_case)]
fn symlink_junction_inner(target: &Path, junction: &Path) -> io::Result<()> {
    use winapi::*;
    use kernel32::*;
    use std::ptr;
    use std::os::windows::ffi::OsStrExt;

    const MAXIMUM_REPARSE_DATA_BUFFER_SIZE: usize = 16 * 1024;

    #[repr(C)]
    pub struct REPARSE_MOUNTPOINT_DATA_BUFFER {
        pub ReparseTag: DWORD,
        pub ReparseDataLength: DWORD,
        pub Reserved: WORD,
        pub ReparseTargetLength: WORD,
        pub ReparseTargetMaximumLength: WORD,
        pub Reserved1: WORD,
        pub ReparseTarget: WCHAR,
    }

    // We're using low-level APIs to create the junction, and these are more picky about paths.
    // For example, forward slashes cannot be used as a path separator, so we should try to
    // canonicalize the path first.
    let target = try!(fs::canonicalize(target));

    try!(fs::create_dir(junction));

    let path = try!(windows::to_u16s(junction));

    unsafe {
        let h = CreateFileW(path.as_ptr(),
                            GENERIC_WRITE,
                            FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
                            0 as *mut _,
                            OPEN_EXISTING,
                            FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
                            ptr::null_mut());

        let mut data = [0u8; MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
        let mut db = data.as_mut_ptr()
                        as *mut REPARSE_MOUNTPOINT_DATA_BUFFER;
        let buf = &mut (*db).ReparseTarget as *mut _;
        let mut i = 0;
        // FIXME: this conversion is very hacky
        let v = br"\??\";
        let v = v.iter().map(|x| *x as u16);
        for c in v.chain(target.as_os_str().encode_wide().skip(4)) {
            *buf.offset(i) = c;
            i += 1;
        }
        *buf.offset(i) = 0;
        i += 1;
        (*db).ReparseTag = IO_REPARSE_TAG_MOUNT_POINT;
        (*db).ReparseTargetMaximumLength = (i * 2) as WORD;
        (*db).ReparseTargetLength = ((i - 1) * 2) as WORD;
        (*db).ReparseDataLength =
                (*db).ReparseTargetLength as DWORD + 12;

        let mut ret = 0;
        let res = DeviceIoControl(h as *mut _,
                                  FSCTL_SET_REPARSE_POINT,
                                  data.as_ptr() as *mut _,
                                  (*db).ReparseDataLength + 8,
                                  ptr::null_mut(), 0,
                                  &mut ret,
                                  ptr::null_mut());

        if res == 0 {
            Err(io::Error::last_os_error())
        } else {
            Ok(())
        }
    }
}

pub fn hardlink(src: &Path, dest: &Path) -> io::Result<()> {
    let _ = fs::remove_file(dest);
    fs::hard_link(src, dest)
}

#[derive(Debug)]
pub enum CommandError {
    Io(io::Error),
    Status(ExitStatus),
}

pub type CommandResult<T> = ::std::result::Result<T, CommandError>;

impl error::Error for CommandError {
    fn description(&self) -> &str {
        use self::CommandError::*;
        match *self {
            Io(_) => "could not execute command",
            Status(_) => "command exited with unsuccessful status",
        }
    }

    fn cause(&self) -> Option<&error::Error> {
        use self::CommandError::*;
        match *self {
            Io(ref e) => Some(e),
            Status(_) => None,
        }
    }
}

impl fmt::Display for CommandError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            CommandError::Io(ref e) => write!(f, "Io: {}", e),
            CommandError::Status(ref s) => write!(f, "Status: {}", s),
        }
    }
}

pub fn cmd_status(cmd: &mut Command) -> CommandResult<()> {
    cmd.status().map_err(CommandError::Io).and_then(|s| {
        if s.success() {
            Ok(())
        } else {
            Err(CommandError::Status(s))
        }
    })
}

pub fn remove_dir(path: &Path) -> io::Result<()> {
    if try!(fs::symlink_metadata(path)).file_type().is_symlink() {
        if cfg!(windows) {
            fs::remove_dir(path)
        } else {
            fs::remove_file(path)
        }
    } else {
        // Again because remove_dir all doesn't delete write-only files on windows,
        // this is a custom implementation, more-or-less copied from cargo.
        // cc rust-lang/rust#31944
        // cc https://github.com/rust-lang/cargo/blob/master/tests/support/paths.rs#L52
        remove_dir_all::remove_dir_all(path)
    }
}

pub fn copy_dir(src: &Path, dest: &Path) -> io::Result<()> {
    try!(fs::create_dir(dest));
    for entry in try!(src.read_dir()) {
        let entry = try!(entry);
        let kind = try!(entry.file_type());
        let src = entry.path();
        let dest = dest.join(entry.file_name());
        if kind.is_dir() {
            try!(copy_dir(&src, &dest));
        } else {
            try!(fs::copy(&src, &dest));
        }
    }
    Ok(())
}

pub fn prefix_arg<S: AsRef<OsStr>>(name: &str, s: S) -> OsString {
    let mut arg = OsString::from(name);
    arg.push(s);
    arg
}

pub fn has_cmd(cmd: &str) -> bool {
    let cmd = format!("{}{}", cmd, env::consts::EXE_SUFFIX);
    let path = env::var_os("PATH").unwrap_or(OsString::new());
    env::split_paths(&path).map(|p| {
        p.join(&cmd)
    }).any(|p| {
        p.exists()
    })
}

pub fn find_cmd<'a>(cmds: &[&'a str]) -> Option<&'a str> {
    cmds.into_iter().map(|&s| s).filter(|&s| has_cmd(s)).next()
}

pub fn open_browser(path: &Path) -> io::Result<bool> {
    #[cfg(not(windows))]
    fn inner(path: &Path) -> io::Result<bool> {
        use std::process::Stdio;

        let commands = ["xdg-open", "open", "firefox", "chromium", "sensible-browser"];
        if let Some(cmd) = find_cmd(&commands) {
            Command::new(cmd)
                .arg(path)
                .stdin(Stdio::null())
                .stdout(Stdio::null())
                .stderr(Stdio::null())
                .spawn()
                .map(|_| true)
        } else {
            Ok(false)
        }
    }
    #[cfg(windows)]
    fn inner(path: &Path) -> io::Result<bool> {
        use winapi;
        use std::ptr;

        // FIXME: When winapi has this function, use their version
        extern "system" {
            pub fn ShellExecuteW(hwnd: winapi::HWND,
                                 lpOperation: winapi::LPCWSTR,
                                 lpFile: winapi::LPCWSTR,
                                 lpParameters: winapi::LPCWSTR,
                                 lpDirectory: winapi::LPCWSTR,
                                 nShowCmd: winapi::c_int)
                                 -> winapi::HINSTANCE;
        }
        const SW_SHOW: winapi::c_int = 5;

        let path = windows::to_u16s(path)?;
        let operation = windows::to_u16s("open")?;
        let result = unsafe {
            ShellExecuteW(ptr::null_mut(),
                          operation.as_ptr(),
                          path.as_ptr(),
                          ptr::null(),
                          ptr::null(),
                          SW_SHOW)
        };
        Ok(result as usize > 32)
    }
    inner(path)
}

#[cfg(windows)]
pub mod windows {
    use winapi::*;
    use std::io;
    use std::path::PathBuf;
    use std::ptr;
    use std::slice;
    use std::ffi::{OsString, OsStr};
    use std::os::windows::ffi::{OsStringExt, OsStrExt};
    use shell32;
    use ole32;

    #[allow(non_upper_case_globals)]
    pub const FOLDERID_LocalAppData: GUID = GUID {
        Data1: 0xF1B32785,
        Data2: 0x6FBA,
        Data3: 0x4FCF,
        Data4: [0x9D, 0x55, 0x7B, 0x8E, 0x7F, 0x15, 0x70, 0x91],
    };
    #[allow(non_upper_case_globals)]
    pub const FOLDERID_Profile: GUID = GUID {
        Data1: 0x5E6C858F,
        Data2: 0x0E22,
        Data3: 0x4760,
        Data4: [0x9A, 0xFE, 0xEA, 0x33, 0x17, 0xB6, 0x71, 0x73],
    };

    pub fn get_special_folder(id: &shtypes::KNOWNFOLDERID) -> io::Result<PathBuf> {

        let mut path = ptr::null_mut();
        let result;

        unsafe {
            let code = shell32::SHGetKnownFolderPath(id, 0, ptr::null_mut(), &mut path);
            if code == 0 {
                let mut length = 0usize;
                while *path.offset(length as isize) != 0 {
                    length += 1;
                }
                let slice = slice::from_raw_parts(path, length);
                result = Ok(OsString::from_wide(slice).into());
            } else {
                result = Err(io::Error::from_raw_os_error(code));
            }
            ole32::CoTaskMemFree(path as *mut _);
        }
        result
    }

    pub fn to_u16s<S: AsRef<OsStr>>(s: S) -> io::Result<Vec<u16>> {
        fn inner(s: &OsStr) -> io::Result<Vec<u16>> {
            let mut maybe_result: Vec<u16> = s.encode_wide().collect();
            if maybe_result.iter().any(|&u| u == 0) {
                return Err(io::Error::new(io::ErrorKind::InvalidInput,
                                          "strings passed to WinAPI cannot contain NULs"));
            }
            maybe_result.push(0);
            Ok(maybe_result)
        }
        inner(s.as_ref())
    }
}


text:
package sqlancer.sqlite3.gen.ddl;

import java.sql.SQLException;

import sqlancer.Randomly;
import sqlancer.common.query.ExpectedErrors;
import sqlancer.common.query.SQLQueryAdapter;
import sqlancer.sqlite3.SQLite3GlobalState;
import sqlancer.sqlite3.gen.SQLite3ColumnBuilder;
import sqlancer.sqlite3.gen.SQLite3Common;
import sqlancer.sqlite3.schema.SQLite3Schema;
import sqlancer.sqlite3.schema.SQLite3Schema.SQLite3Column;
import sqlancer.sqlite3.schema.SQLite3Schema.SQLite3Table;

public class SQLite3AlterTable {

    private final StringBuilder sb = new StringBuilder();
    private final SQLite3GlobalState globalState;

    public static SQLQueryAdapter alterTable(SQLite3GlobalState globalState) throws SQLException {
        SQLite3AlterTable alterTable = new SQLite3AlterTable(globalState);
        return alterTable.getQuery(globalState.getSchema(), alterTable);
    }

    private enum Option {
        RENAME_TABLE, RENAME_COLUMN, ADD_COLUMN
    }

    public SQLite3AlterTable(SQLite3GlobalState globalState) {
        this.globalState = globalState;
    }

    private SQLQueryAdapter getQuery(SQLite3Schema s, SQLite3AlterTable alterTable) throws AssertionError {
        ExpectedErrors errors = new ExpectedErrors();
        errors.add("error in view");
        errors.add("no such column"); // trigger
        errors.add("error in trigger"); // trigger

        errors.add("operator prohibited in generated columns");
        errors.add("subqueries prohibited in generated columns");
        errors.add("duplicate column name");
        errors.add("non-deterministic functions prohibited in generated columns");
        errors.add("non-deterministic functions prohibited in CHECK constraints");
        errors.add("second argument to likelihood");
        errors.add("subqueries prohibited in CHECK constraints");
        errors.add("subqueries prohibited in index expressions");
        errors.add("parser stack overflow");
        Option option = Randomly.fromOptions(Option.values());
        SQLite3Table t = s.getRandomTableOrBailout(tab -> !tab.isView() && !tab.isVirtual() && !tab.isReadOnly());
        sb.append("ALTER TABLE ");
        sb.append(t.getName());
        switch (option) {
        case RENAME_TABLE:
            sb.append(" RENAME TO ");
            sb.append(SQLite3Common.getFreeTableName(s));
            break;
        case RENAME_COLUMN:
            SQLite3Column c = t.getRandomColumn();
            sb.append(" RENAME COLUMN ");
            sb.append(c.getName());
            sb.append(" TO ");
            sb.append(SQLite3Common.getFreeColumnName(t));
            break;
        case ADD_COLUMN:
            sb.append(" ADD COLUMN ");
            String name = SQLite3Common.getFreeColumnName(t);
            // The column may not have a PRIMARY KEY or UNIQUE constraint.
            // The column may not have a default value of CURRENT_TIME, CURRENT_DATE,
            // CURRENT_TIMESTAMP, or an expression in parentheses.
            // If a NOT NULL constraint is specified, then the column must have a default
            // value other than NULL.
            // If foreign key constraints are enabled and a column with a REFERENCES clause
            // is added, the column must have a default value of NULL.
            sb.append(new SQLite3ColumnBuilder().allowPrimaryKey(false).allowUnique(false).allowNotNull(false)
                    .allowDefaultValue(false).createColumn(name, globalState, t.getColumns()));
            errors.add("subqueries prohibited in CHECK constraints");
            errors.add("Cannot add a NOT NULL column with default value NULL");
            errors.add("unsupported frame specification");
            break;
        default:
            throw new AssertionError();
        }
        return new SQLQueryAdapter(alterTable.sb.toString(), errors, true);
    }

}


text:
`Application` – An application that can authenticate to the TypePad API using OAuth
===================================================================================

.. autoclass:: typepad.api.Application
   :members:


text:
- **BREAKING** updated to Polymer 2, nothing else changed on the element
  - updated element to use the Polymer 2 syntax
  - updated demo to use iron-demo-helpers
  - updated index documentation to version 3 of iron-component-page

## 2.0.0
- **BREAKING** Change the name of the `title` property to be `pageTitle`. This is friendlier with Googlebot, we've found.

## 1.2.1
- Add missing `dom-module` wrapper.

## 1.2.0
- Updated Polymer dependency to allowe newer versions of Polymer.
  - This makes Bower dependency resolution easier. Not sure why it was pinned to begin with.
- **BREAKING** Removed the explicit spaces around the `separator`.
  - If you were using the default value for this you'll notice no difference.
  - If you were specifying this property, you'll now need to add your own spaces.


text:
require 'spec_helper'

describe 'Media queries' do
  describe 'standard column widths' do
    before :each do
      @css = render """
      @include longitude(2 4) {
        p { color: blue; }
      }
      """
    end

    it 'includes lower bound' do
      @css.should include('@media (max-width: 160px)')
    end

    it 'includes the middle step' do
      @css.should include('@media (min-width: 161px) and (max-width: 320px)')
    end

    it 'includes the higher bound' do
      @css.should include('@media (min-width: 321px)')
    end
  end

  describe 'custom column widths' do
    before :each do
      @css = render """
      $longitude-gutter-width: 5px;
      $longitude-column-width: 10px;

      @include longitude(2 4) {
        p { color: blue; }
      }
      """
    end

    it 'renders the middle stop according to the custom widths' do
      @css.should include('@media (min-width: 41px) and (max-width: 80px)')
    end
  end

  describe 'fluidity check' do
    before :each do
      @css = render """
      @include longitude(4) {
        p {
          @if not is-fluid() {
            color: blue;
          }
        }
      }
      """
    end

    it 'should only render "color: blue" for the higher bound media query' do
      @css.should match(/@media \(min-width: 321px\).*color: blue;/m)
    end
  end
end


text:
import { Descriptor, DescriptorFor, MultiTypeRegister } from 'vuvu/typo';
import { clearAllDescriptors } from 'vuvu/typo/descriptorHelpers';

describe('MultiTypeRegister', () => {

    beforeEach(() => {
        clearAllDescriptors();
    });

    it('resolves instances for type', () => {

        @DescriptorFor('foo')
        class FooDescriptor extends Descriptor<any> {

        }

        @DescriptorFor('bar')
        class BarDescriptor extends Descriptor<any> {

        }

        let foo = {
            a: 123
        };

        let bar = {
            b: 1234
        };

        let register = new MultiTypeRegister<object>({
            types: [
                {
                    from: FooDescriptor,
                    to: foo
                },
                {
                    from: FooDescriptor,
                    to: bar
                },
                {
                    from: 'bar',
                    to: bar
                }
            ]
        });

        let foos1 = register.get(FooDescriptor);
        let foos2 = register.get(new FooDescriptor());
        let foos3 = register.get('foo');
        let bars = register.get('bar');

        expect(foos1.length).toBe(2);
        expect(foos1[0]).toBe(foo);
        expect(foos1[1]).toBe(bar);
        expect(foos2.length).toBe(2);
        expect(foos2[0]).toBe(foo);
        expect(foos2[1]).toBe(bar);
        expect(foos3.length).toBe(2);
        expect(foos3[0]).toBe(foo);
        expect(foos3[1]).toBe(bar);

        expect(bars.length).toBe(1);
        expect(bars[0]).toBe(bar);
    });

    it('resolves insances for type with inheritance', () => {

        @DescriptorFor('foo')
        class FooDescriptor extends Descriptor<any> {

        }

        @DescriptorFor('bar')
        class BarDescriptor extends FooDescriptor {

        }

        @DescriptorFor('baz')
        class BazDescriptor extends BarDescriptor {

        }

        let foo = {
            a: 123
        };

        let bar = {
            b: 1234
        };

        let baz = {
            b: 1234
        };

        let register = new MultiTypeRegister<object>({
            types: [
                {
                    from: FooDescriptor,
                    to: foo
                },
                {
                    from: new BarDescriptor(),
                    to: bar
                },
                {
                    from: 'baz',
                    to: baz
                }
            ]
        });

        let foos1 = register.get(FooDescriptor);
        let foos2 = register.get(new FooDescriptor());
        let foos3 = register.get('foo');
        let bars1 = register.get('bar');
        let bars2 = register.get(BarDescriptor);
        let bars3 = register.get(new BarDescriptor());

        let bazs = register.get('baz');

        expect(foos1.length).toBe(1);
        expect(foos1[0]).toBe(foo);
        expect(foos2.length).toBe(1);
        expect(foos2[0]).toBe(foo);
        expect(foos3.length).toBe(1);
        expect(foos3[0]).toBe(foo);

        expect(bars1.length).toBe(2);
        expect(bars1[0]).toBe(foo);
        expect(bars1[1]).toBe(bar);
        expect(bars2.length).toBe(2);
        expect(bars2[0]).toBe(foo);
        expect(bars2[1]).toBe(bar);
        expect(bars3.length).toBe(2);
        expect(bars3[0]).toBe(foo);
        expect(bars3[1]).toBe(bar);

        expect(bazs.length).toBe(3);
        expect(bazs[0]).toBe(foo);
        expect(bazs[1]).toBe(bar);
        expect(bazs[2]).toBe(baz);
    });
});


text:
package com.sleepycat.je.utilint;

/**
 * A long stat which represents a rate whose value is Integral.
 */
public class IntegralRateStat extends LongStat {
    private static final long serialVersionUID = 1L;

    private final long factor;

    public IntegralRateStat(StatGroup group,
                            StatDefinition definition,
                            Stat<? extends Number> divisor,
                            Stat<? extends Number> dividend,
                            long factor) {
        super(group, definition);
        this.factor = factor;

        calculateRate(divisor, dividend);
    }

    /* Calculate the rate based on the two stats. */
    private void calculateRate(Stat<? extends Number> divisor,
                               Stat<? extends Number> dividend) {
        if (divisor == null || dividend == null) {
            counter = 0;
        } else {
            counter = (dividend.get().longValue() != 0) ?
                (divisor.get().longValue() * factor) /
                 dividend.get().longValue() :
                 0;
        }
    }
}


text:
package com.flipkart.foxtrot.core.datastore;

import com.flipkart.foxtrot.common.Document;
import com.flipkart.foxtrot.common.Table;

import java.util.List;

/**
 * User: Santanu Sinha (santanu.sinha@flipkart.com)
 * Date: 12/03/14
 * Time: 9:17 PM
 */
public interface DataStore {

    void initializeTable(final Table table, boolean forceTableCreate);

    Document save(final Table table, final Document document);

    List<Document> saveAll(final Table table, final List<Document> documents);

    Document get(final Table table, final String id);

    List<Document> getAll(final Table table, final List<String> ids);

    void updateTable(final Table table);
}


text:
@interface PodsDummy_Pods_GameCenterManager : NSObject
@end
@implementation PodsDummy_Pods_GameCenterManager
@end


text:
<?xml version="1.0"?>
<ruleset name="PHPMD" xmlns="http://pmd.sf.net/ruleset/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://pmd.sf.net/ruleset/1.0.0 http://pmd.sf.net/ruleset_xml_schema.xsd" xsi:noNamespaceSchemaLocation=" http://pmd.sf.net/ruleset_xml_schema.xsd">
  <description>Apnet PHPMD ruleset</description>

  <rule ref="rulesets/codesize.xml" />
  <rule ref="rulesets/design.xml" />
  <rule ref="rulesets/naming.xml" />
  <rule ref="rulesets/unusedcode.xml" />
</ruleset>


text:
package usr.doetsch.threed;

public class Vector {

}


text:
This folder contains all code (all .R files) used in this project. Under __scripts/__ are files that fit and test regression models. Under __functions/__ is a function that calculates the range of an object. The folder __tests/__ tests the function.

scripts/
 + regression-pcr.R

 Fits PCR regression to `Advertising` dataset.
 Outputs variables to data/fit-pcr.RData.

 + regression-lasso.R

 Fits LASSO regression to `Advertising` dataset.
 Outputs variables to data/fit-lasso.RData.

 + regression-pls.R

 Fits PLS regression to `Advertising` dataset.
 Outputs variables to data/fit-pls.RData.

 + regression-ridge.R

 Fits Ridge regression to `Advertising` dataset.
 Outputs variables to data/fit-ridge.RData.

 + regression-ols.R

 Fits Least Squares regression to `Advertising` dataset.
 Outputs variables to data/fit-ols.RData.

functions/
 + range-as-value.R

 Writes a function to calculate the range of a vector of numeric data (not the same as the built-in R function range())

tests/
 + test-range-as-value.R

 Tests whether the value produced by range_as_value() is the same as the
 the value obtained by manually calculating max() - min() for a given
 vector of numeric data

 + test-that.R

 Executes function test detailed in tests/test-range-as-value.R


text:
title: Border Blogger Movement - Mentoring 3 Maret 2013
date: 2013-03-03
categories:
- laporan
- mentoring
- Border Blogger Movement
---

Siska Doviana

Halo Mas Mering,

Terima kasih atas surelnya dan mohon maaf atas keterlambatan menjawab. Surel tertanggal 2 Februari 2013 & surel 2 Maret 2013 telah saya arsipkan pada halaman tim penasehat .

1. Penyerahan Hadiah kepada pemenang syaembara Blogger yang akan dilaksanakan pada tanggal 10 Pebruari 2013

> Saya sudah memeriksa laporan aktivitas Border Blogger Movement yang sayangnya berhenti pada 27 April 2012 setelah dana kedua mulai diminta, dan saat dana kedua turun, laporan stop sama sekali. Ini disayangkan, jadi saya buatkan lagi saja kotaknya untuk 10 Februari 2013 dan gambarnya mengambil dari facebook orang. Tolong diisi yah, saya tidak tahu acaranya dimulai jam berapa dan dihadiri oleh berapa banyak orang.

2. Di media pontianak post, Antara dan RRI, beberapa hari sebelum dan setelah kegiatan jga sudah dipunlish. Sekitar pukul 10 malam TVRI nasional akan menayangkan selama 30 menit berita ttg Inisiatif BBM ini di program liputan Tapal Batas.

> Betul, terima kasih atas pemberitahuannya, saya juga sudah taruh pranalanya di laporan aktivitas, namun saya tidak mendapatkan Pontianak Post. Mungkin bisa di scan dan dimuat di wiki cipta media?

3. Terkait laporan narasi dan keuangan fase II, kami akan selesaikan segera (dalam satu bulan ke depan) sebagai pertanggungjawaban lembaga terhadap project yang dilaksanakan. Minggu ini saya akan mulai membuat laporan kegiatan Akhir peogram BBM.

> Terlampir adalah format laporan naratif. Terakhir laporan pertama yang dikirim adalah untuk 20 Juli 2012, sehingga batas untuk laporan kedua, karena dari surelnya mengatakan satu bulan kedepan, saya pikir 20 Juli 2012 - 3 April 2013 bisa dilengkapi. Walaupun pertanyaannya sama (karena dari proposal) jawabannya diharapkan berbeda dari periode sebelumnya. Untuk yang sudah silahkan diinformasikan bahwa hal ini sudah dilaporkan pada periode berikutnya (misalnya), seperti biasa saya akan baca dan revisi seperti biasa ;-)

Catatan untuk laporan keuangan: Tolong diperbaharui, bisa diisi untuk Lomba dan Publishing

Kontributor BBM Bapak Andreas Basilius Gas terakhir melakukan kontribusi 19 Oktober 2012, dan laporan aktivitas terakhir adalah 27 April 2012, saya tidak tahu apakah diantara tanggal itu hingga 10 Februari 2013 ada kegiatan diantara, yang jelas bila ada kegiatan ini tidak dilaporkan. Saya mohon hal ini tetap diperhatikan dan diselesaikan.

Terima kasih dan sukses untuk upayanya!

Siska


text:
<?php

namespace Dalilak\VenueBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

/**
 * Branch Form Type
 *
 * @author Alaa Attya <alaa.attya91@gmail.com>
 * @package Dalilak.VenueBundle.Entity
 * @version 1.0
 * @license  http://www.opensource.org/licenses/mit-license.php The MIT License
 * @category FormType
 */
class BranchType extends AbstractType {

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder
                ->add('area')

                ->add('address_text', 'text', array('required' => false))
                ->add('address_longitude', 'text', array('required' => false))
                ->add('address_latitude', 'text', array('required' => false))
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver) {
        $resolver->setDefaults(array(
            'data_class' => 'Dalilak\VenueBundle\Entity\Branch'
        ));
    }

    /**
     * @return string
     */
    public function getName() {
        return 'dalilak_venuebundle_branch';
    }

}


text:
package org.wso2.carbon.apimgt.rest.api.core.impl;

import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.wso2.carbon.apimgt.core.impl.APIManagerFactory;
import org.wso2.carbon.apimgt.core.impl.APIMgtAdminServiceImpl;
import org.wso2.msf4j.Request;
import org.wso2.transport.http.netty.message.HTTPCarbonMessage;

import javax.ws.rs.core.Response;

@RunWith(PowerMockRunner.class)
@PrepareForTest(APIManagerFactory.class)
public class ExportApiServiceImplTestCase {

    @Test
    public void exportPoliciesThrottleGetTest() throws Exception {
        APIMgtAdminServiceImpl apiMgtAdminService = Mockito.mock(APIMgtAdminServiceImpl.class);
        APIManagerFactory instance = Mockito.mock(APIManagerFactory.class);
        PowerMockito.mockStatic(APIManagerFactory.class);
        PowerMockito.when(APIManagerFactory.getInstance()).thenReturn(instance);
        Mockito.when(instance.getAPIMgtAdminService()).thenReturn(apiMgtAdminService);

        ExportApiServiceImpl exportApiService = new ExportApiServiceImpl();

        LogManager.getRootLogger().setLevel(Level.DEBUG);

        Response response = exportApiService.exportPoliciesThrottleGet(null, getRequest());
        Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());

    }

    @Test
    public void exportPoliciesThrottleGetExceptionTest() throws Exception {
        LogManager.getRootLogger().setLevel(Level.INFO);
        ExportApiServiceImpl exportApiService = new ExportApiServiceImpl();
        Response response = exportApiService.exportPoliciesThrottleGet(null, getRequest());
        Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
    }

    private Request getRequest() throws Exception {
        HTTPCarbonMessage carbonMessage = Mockito.mock(HTTPCarbonMessage.class);
        Request request = new Request(carbonMessage);
        PowerMockito.whenNew(Request.class).withArguments(carbonMessage).thenReturn(request);
        return request;
    }

}


text:
package com.khartec.waltz.service.physical_specification_definition;

import com.khartec.waltz.data.physical_specification_definition.PhysicalSpecDefinitionDao;
import com.khartec.waltz.data.physical_specification_definition.PhysicalSpecDefinitionFieldDao;
import com.khartec.waltz.data.physical_specification_definition.PhysicalSpecDefinitionSampleFileDao;
import com.khartec.waltz.data.physical_specification_definition.PhysicalSpecDefnIdSelectorFactory;
import com.khartec.waltz.model.*;
import com.khartec.waltz.model.changelog.ImmutableChangeLog;
import com.khartec.waltz.model.physical_specification_definition.ImmutablePhysicalSpecDefinition;
import com.khartec.waltz.model.physical_specification_definition.PhysicalSpecDefinition;
import com.khartec.waltz.model.physical_specification_definition.PhysicalSpecDefinitionChangeCommand;
import com.khartec.waltz.service.changelog.ChangeLogService;
import org.jooq.Record1;
import org.jooq.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.khartec.waltz.common.Checks.checkNotNull;
import static com.khartec.waltz.common.ListUtilities.newArrayList;
import static com.khartec.waltz.model.EntityReference.mkRef;
import static com.khartec.waltz.model.ReleaseLifecycleStatus.*;

@Service
public class PhysicalSpecDefinitionService {

    private final ChangeLogService changeLogService;

    private final PhysicalSpecDefinitionDao physicalSpecDefinitionDao;
    private final PhysicalSpecDefinitionFieldDao physicalSpecDefinitionFieldDao;
    private final PhysicalSpecDefinitionSampleFileDao physicalSpecDefinitionSampleFileDao;
    private final Map<ReleaseLifecycleStatus, List<ReleaseLifecycleStatus>> stateTransitions;
    private final PhysicalSpecDefnIdSelectorFactory physicalSpecDefnIdSelectorFactory = new PhysicalSpecDefnIdSelectorFactory();

    @Autowired
    public PhysicalSpecDefinitionService(ChangeLogService changeLogService,
                                         PhysicalSpecDefinitionDao physicalSpecDefinitionDao,
                                         PhysicalSpecDefinitionFieldDao physicalSpecDefinitionFieldDao,
                                         PhysicalSpecDefinitionSampleFileDao physicalSpecDefinitionSampleFileDao) {
        checkNotNull(changeLogService, "changeLogService cannot be null");
        checkNotNull(physicalSpecDefinitionDao, "physicalSpecDefinitionDao cannot be null");
        checkNotNull(physicalSpecDefinitionFieldDao, "physicalSpecDefinitionFieldDao cannot be null");
        checkNotNull(physicalSpecDefinitionSampleFileDao, "physicalSpecDefinitionSampleFileDao cannot be null");

        this.changeLogService = changeLogService;
        this.physicalSpecDefinitionDao = physicalSpecDefinitionDao;
        this.physicalSpecDefinitionFieldDao = physicalSpecDefinitionFieldDao;
        this.physicalSpecDefinitionSampleFileDao = physicalSpecDefinitionSampleFileDao;

        // initialise valid state transitions
        // Hashmap as follows: <currenctState, List of valid transition states>
        stateTransitions = new HashMap<>();
        stateTransitions.put(DRAFT, newArrayList(ACTIVE));
        stateTransitions.put(ACTIVE, newArrayList(DEPRECATED));
        stateTransitions.put(DEPRECATED, newArrayList(ACTIVE, OBSOLETE));
        stateTransitions.put(OBSOLETE, newArrayList());
    }

    public long create(String userName,
                       long specificationId,
                       PhysicalSpecDefinitionChangeCommand command) {

        checkNotNull(userName, "userName cannot be null");
        checkNotNull(command, "command cannot be null");

        if (command.status() == ACTIVE) {
            physicalSpecDefinitionDao.markExistingActiveAsDeprecated(specificationId, userName);
        }

        long defId = physicalSpecDefinitionDao.create(
                ImmutablePhysicalSpecDefinition.builder()
                        .specificationId(specificationId)
                        .version(command.version())
                        .status(command.status())
                        .delimiter(command.delimiter())
                        .type(command.type())
                        .provenance("waltz")
                        .createdBy(userName)
                        .lastUpdatedBy(userName)
                        .build());

        changeLogService.write(
                ImmutableChangeLog.builder()
                        .operation(Operation.ADD)
                        .userId(userName)
                        .parentReference(mkRef(EntityKind.PHYSICAL_SPECIFICATION, specificationId))
                        .message("Spec Definition Version: " + command.version() + " added")
                        .build());

        return defId;

    }

    public int delete(String userName, long specDefinitionId) {

        checkNotNull(userName, "userName cannot be null");

        PhysicalSpecDefinition specDefinition = physicalSpecDefinitionDao.getById(specDefinitionId);

        checkNotNull(specDefinition, "specDefinition cannot be null");

        int defDelCount = physicalSpecDefinitionDao.delete(specDefinitionId);
        int fieldDelCount = physicalSpecDefinitionFieldDao.deleteForSpecDefinition(specDefinitionId);
        int fileDelCount = physicalSpecDefinitionSampleFileDao.deleteForSpecDefinition(specDefinitionId);

        changeLogService.write(
                ImmutableChangeLog.builder()
                        .operation(Operation.REMOVE)
                        .userId(userName)
                        .parentReference(mkRef(EntityKind.PHYSICAL_SPECIFICATION, specDefinition.specificationId()))
                        .message("Spec Definition Id: " + specDefinitionId + " removed")
                        .build());

        return defDelCount + fieldDelCount + fileDelCount;
    }

    public List<PhysicalSpecDefinition> findForSpecification(long specificationId) {
        return physicalSpecDefinitionDao.findForSpecification(specificationId);
    }

    public List<PhysicalSpecDefinition> findBySelector(IdSelectionOptions options) {
        Select<Record1<Long>> selector = physicalSpecDefnIdSelectorFactory.apply(options);
        return physicalSpecDefinitionDao.findBySelector(selector);
    }

    public boolean updateStatus(String userName, long specDefinitionId, ReleaseLifecycleStatusChangeCommand command) {
        checkNotNull(userName, "userName cannot be null");
        checkNotNull(command, "command cannot be null");

        PhysicalSpecDefinition specDefinition = physicalSpecDefinitionDao.getById(specDefinitionId);

        checkNotNull(specDefinition, "specDefinition cannot be null");

        ensureNewStatusIsValid(specDefinition, command.newStatus());

        if (command.newStatus() == ACTIVE) {
            physicalSpecDefinitionDao.markExistingActiveAsDeprecated(specDefinition.specificationId(), userName);
        }

        int result = physicalSpecDefinitionDao.updateStatus(specDefinitionId, command.newStatus(), userName);

        changeLogService.write(
                ImmutableChangeLog.builder()
                        .operation(Operation.UPDATE)
                        .userId(userName)
                        .parentReference(mkRef(EntityKind.PHYSICAL_SPECIFICATION, specDefinition.specificationId()))
                        .message("Spec Definition Id: " + specDefinitionId
                                + " status changed to " + command.newStatus())
                        .build());

        return result == 1;
    }

    private void ensureNewStatusIsValid(PhysicalSpecDefinition specDefinition,
                                        ReleaseLifecycleStatus newStatus) {
        ReleaseLifecycleStatus currentStatus = specDefinition.status();

        List<ReleaseLifecycleStatus> validTransitionStates = stateTransitions.get(currentStatus);
        if(validTransitionStates == null || !validTransitionStates.contains(newStatus)) {
            throw new IllegalStateException(String.format("Transition from %s to %s is not valid", currentStatus, newStatus));
        }
    }

}


text:
Rails.application.routes.draw do
  mount GotFixed::Engine => "/got_fixed"

  root :to => redirect("/got_fixed")
end


text:
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace KspTsTool2.ConfigurationData.NodeInfo
{
    /// <summary>
    /// TechTree解析
    /// </summary>
    class NodeAnalysisTechTree : NodeAnalysis
    {
        /// <summary>
        ///  TechTree用正規表現
        /// </summary>
        private Regex RegexTechTree = new Regex(@"^[@]*TechTree($|\s|:)", RegexOptions.IgnoreCase);

        /// <summary>
        ///  RDNode用正規表現
        /// </summary>
        private Regex RegexRDNode = new Regex(@"^RDNode($|\s|:)", RegexOptions.IgnoreCase);

        /// <summary>
        ///  RDNode用正規表現(Import/ModuleManage定義)
        /// </summary>
        private Regex RegexRDNodeImport = new Regex(@"^@RDNode\s*:\s*HAS\s*\[\s*#id\s*\[\s*(.+?)\s*\]\s*\]", RegexOptions.IgnoreCase);

        /// <summary>
        ///  id用正規表現
        /// </summary>
        private Regex RegexID = new Regex(@"^id\s*=\s*(.+)$", RegexOptions.IgnoreCase);

        /// <summary>
        ///  title用正規表現
        /// </summary>
        private Regex RegexTitle = new Regex(@"^[@]*title\s*=\s*(.+)$", RegexOptions.IgnoreCase);

        /// <summary>
        /// description用正規表現
        /// </summary>
        private Regex RegexDescription  = new Regex(@"^[@]*description\s*=\s*(.+)$", RegexOptions.IgnoreCase);

        /// <summary>
        /// description用正規表現
        /// </summary>
        private Regex RegexDescriptionImport  = new Regex(@"^@description\s*=\s*(.+)$", RegexOptions.IgnoreCase);

        /// <summary>
        /// TechTreeノードが見つかった
        /// </summary>
        /// <returns></returns>
        private bool FindNodeTechTree { get; set; } = false;

        /// <summary>
        /// TechTreeノードの中にはいった
        /// </summary>
        /// <returns></returns>
        private bool InsideNodeTechTree { get; set; } = false;

        /// <summary>
        /// RDNodeノードが見つかった
        /// </summary>
        /// <returns></returns>あ
        private bool FindNodeRDNode { get; set; } = false;

        /// <summary>
        /// RDNodeノードの中にはいった
        /// </summary>
        /// <returns></returns>
        private bool InsideNodeRDNode { get; set; } = false;

        /// <summary>
        /// ID
        /// </summary>
        private string TechTreeID { get; set; }

        /// <summary>
        /// タイトル
        /// </summary>
        private string TechTreeTitle { get; set; }

        /// <summary>
        /// 説明
        /// </summary>
        private string TechTreeDescription { get; set; }

        /// <summary>
        /// コンストラクタ
        /// </summary>
        public NodeAnalysisTechTree()
        {
            this.FindNodeTechTree = false;
            this.InsideNodeTechTree = false;
            this.FindNodeRDNode = false;
            this.InsideNodeRDNode = false;
        }

        /// <summary>
        /// 1ブロック解析
        /// </summary>
        /// <param name="blockText"></param>
        public override void AnalysisOneBlock( int nestLevel ,
                                               string blockText )
        {
            //正規表現用
            System.Text.RegularExpressions.MatchCollection mc;

            //TechTreeノードが見つかったか?
            if ( !this.InsideNodeTechTree && nestLevel == 0 && RegexTechTree.IsMatch( blockText ) )
            {
                //TechTreeノードが見つかった
                this.FindNodeTechTree = true;
                this.InsideNodeTechTree = false;
                this.FindNodeRDNode = false;
                this.InsideNodeRDNode = false;
                return;
            }

            //ノードの中に入ったか確認
            if ( this.FindNodeTechTree && !this.InsideNodeTechTree && nestLevel == 1 )
            {
                //TechTreeノードの中に入った
                this.InsideNodeTechTree = true;
            }

            if ( this.InsideNodeTechTree && nestLevel == 0 )
            {
                //TechTreeノードの外に出た
                this.FindNodeTechTree = false;
                this.InsideNodeTechTree = false;
                this.FindNodeRDNode = false;
                this.InsideNodeRDNode = false;

            }

            //RDNodeノードが見つかったか?
            if ( this.InsideNodeTechTree && !this.InsideNodeRDNode && nestLevel == 1 )
            {
                if ( blockText != "" )
                {
                    mc = this.RegexRDNodeImport.Matches( blockText );
                    if ( mc.Count >= 1 )
                    {
                        //RDNodeノードが見つかった
                        this.FindNodeRDNode = true;
                        this.InsideNodeRDNode = false;

                        this.TechTreeID = mc[0].Groups[1].Value;
                        this.TechTreeTitle = "";
                        this.TechTreeDescription = "";
                    }
                    else if ( this.RegexRDNode.IsMatch( blockText ) )
                    {
                        //RDNodeノードが見つかった
                        this.FindNodeRDNode = true;
                        this.InsideNodeRDNode = false;

                        this.TechTreeID = "";
                        this.TechTreeTitle = "";
                        this.TechTreeDescription = "";
                    }
                }
            }

            if ( this.FindNodeRDNode && !this.InsideNodeRDNode && nestLevel == 2 )
            {
                //RDNodeノードの中に入った
                this.InsideNodeRDNode = true;
            }

            if ( this.InsideNodeRDNode && nestLevel <= 1 )
            {
                //Resultノードの外に出た
                this.FindNodeRDNode = false;
                this.InsideNodeRDNode = false;

                //翻訳元テキストデータを記憶する
                if ( !this.TechTreeID.Equals( "" ) && !this.TechTreeDescription.Equals( "" ) )
                {
                    this.TextDataList.Add(
                            new Text.TextDataTechTree( this.TechTreeID ,
                                          this.TechTreeTitle ,
                                          this.TechTreeDescription )
                                          );
                }
            }

            if ( this.InsideNodeRDNode && nestLevel == 2 )
            {
                //ID
                mc = this.RegexID.Matches( blockText );
                if ( mc.Count >= 1 )
                {
                    this.TechTreeID = mc[0].Groups[1].Value;
                }

                //タイトル
                mc = this.RegexTitle.Matches( blockText );
                if ( mc.Count >= 1 )
                {
                    this.TechTreeTitle = mc[0].Groups[1].Value;
                }

                //説明
                mc = this.RegexDescription.Matches( blockText );
                if ( mc.Count >= 1 )
                {
                    this.TechTreeDescription = mc[0].Groups[1].Value;
                }
            }

        }

        /// <summary>
        /// 1ブロック解析(インポートモード時)
        /// </summary>
        /// <param name="blockText"></param>
        public override void AnalysisOneBlockImport( int nestLevel ,
                                                     string blockText )

        {
            //正規表現用
            System.Text.RegularExpressions.MatchCollection mc;

            //TechTreeノードが見つかったか?
            if ( !this.InsideNodeTechTree && nestLevel == 0 && RegexTechTree.IsMatch( blockText ) )
            {
                //TechTreeノードが見つかった
                this.FindNodeTechTree = true;
                this.InsideNodeTechTree = false;
                this.FindNodeRDNode = false;
                this.InsideNodeRDNode = false;
                return;
            }

            //ノードの中に入ったか確認
            if ( this.FindNodeTechTree && !this.InsideNodeTechTree && nestLevel == 1 )
            {
                //TechTreeノードの中に入った
                this.InsideNodeTechTree = true;
            }

            if ( this.InsideNodeTechTree && nestLevel == 0 )
            {
                //TechTreeノードの外に出た
                this.FindNodeTechTree = false;
                this.InsideNodeTechTree = false;
                this.FindNodeRDNode = false;
                this.InsideNodeRDNode = false;

            }

            //RDNodeノードが見つかったか?
            if ( this.InsideNodeTechTree && !this.InsideNodeRDNode && nestLevel == 1 )
            {

                mc = this.RegexRDNodeImport.Matches( blockText );
                if ( mc.Count >= 1 )
                {
                    //RDNodeノードが見つかった
                    this.FindNodeRDNode = true;
                    this.InsideNodeRDNode = false;

                    this.TechTreeID = mc[0].Groups[1].Value;
                    this.TechTreeTitle = "";
                    this.TechTreeDescription = "";
                }

            }

            if ( this.FindNodeRDNode && !this.InsideNodeRDNode && nestLevel == 2 )
            {
                //RDNodeノードの中に入った
                this.InsideNodeRDNode = true;
            }

            if ( this.InsideNodeRDNode && nestLevel <= 1 )
            {
                //Resultノードの外に出た
                this.FindNodeRDNode = false;
                this.InsideNodeRDNode = false;

                //翻訳元テキストデータを記憶する
                if ( !this.TechTreeID.Equals( "" ) && !this.TechTreeDescription.Equals( "" ) )
                {
                    this.TextDataList.Add(
                            new Text.TextDataTechTree( this.TechTreeID ,
                                          "" ,
                                          this.TechTreeDescription )
                                          );
                }
            }

            if ( this.InsideNodeRDNode && nestLevel == 2 )
            {
                //説明
                mc = this.RegexDescriptionImport.Matches( blockText );
                if ( mc.Count >= 1 )
                {
                    this.TechTreeDescription = mc[0].Groups[1].Value;
                }
            }

        }

    }
}


text:
package com.facebook.nifty.codec;

import com.facebook.nifty.core.ThriftMessage;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.handler.codec.frame.TooLongFrameException;

public class DefaultThriftFrameEncoder extends ThriftFrameEncoder
{
    private final long maxFrameSize;

    public DefaultThriftFrameEncoder(long maxFrameSize)
    {

        this.maxFrameSize = maxFrameSize;
    }

    @Override
    protected ChannelBuffer encode(ChannelHandlerContext ctx,
                                   Channel channel,
                                   ThriftMessage message) throws Exception
    {
        int frameSize = message.getBuffer().readableBytes();

        if (message.getBuffer().readableBytes() > maxFrameSize)
        {
            Channels.fireExceptionCaught(ctx, new TooLongFrameException(
                    String.format(
                            "Frame size exceeded on encode: frame was %d bytes, maximum allowed is %d bytes",
                            frameSize,
                            maxFrameSize)));
            return null;
        }

        switch (message.getTransportType()) {
            case UNFRAMED:
                return message.getBuffer();

            case FRAMED:
                ChannelBuffer frameSizeBuffer = ChannelBuffers.buffer(4);
                frameSizeBuffer.writeInt(message.getBuffer().readableBytes());
                return ChannelBuffers.wrappedBuffer(frameSizeBuffer, message.getBuffer());

            case HEADER:
                throw new UnsupportedOperationException("Header transport is not supported");

            case HTTP:
                throw new UnsupportedOperationException("HTTP transport is not supported");

            default:
                throw new UnsupportedOperationException("Unrecognized transport type");
        }
    }
}


text:
namespace Google.Cloud.OsLogin.V1.Snippets
{
    // [START oslogin_v1_generated_OsLoginService_DeleteSshPublicKey_async_flattened]
    using Google.Cloud.OsLogin.V1;
    using System.Threading.Tasks;

    public sealed partial class GeneratedOsLoginServiceClientSnippets
    {
        /// <summary>Snippet for DeleteSshPublicKeyAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated and should be regarded as a code template only.
        /// It will require modifications to work:
        /// - It may require correct/in-range values for request initialization.
        /// - It may require specifying regional endpoints when creating the service client as shown in
        ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
        /// </remarks>
        public async Task DeleteSshPublicKeyAsync()
        {
            // Create client
            OsLoginServiceClient osLoginServiceClient = await OsLoginServiceClient.CreateAsync();
            // Initialize request argument(s)
            string name = "users/[USER]/sshPublicKeys/[FINGERPRINT]";
            // Make the request
            await osLoginServiceClient.DeleteSshPublicKeyAsync(name);
        }
    }
    // [END oslogin_v1_generated_OsLoginService_DeleteSshPublicKey_async_flattened]
}


text:
layout: page
title: About
---
Lagrange is a minimalist Jekyll. It is intended to have a clean, content focused interface for blog writing. For more information on how to install and use this theme, check out [the documentation]({{ site.github.url }}{% post_url 2016-01-01-Welcome-to-Lagrange %}).


text:
using System;
namespace BankSystem
{
	public enum Customer
	{
		Company, Individual
	}
}


text:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

<TITLE>CLHS: Issue FUNCTION-TYPE-KEY-NAME Writeup</TITLE>
<META HTTP-EQUIV="Author" CONTENT="Kent M. Pitman">
<META HTTP-EQUIV="Organization" CONTENT="The Harlequin Group Limited">
<LINK REL=TOP HREF="../FrontMatter/index.html">
<LINK REL=COPYRIGHT HREF="../FrontMatter/About-HyperSpec.html#Legal">
<LINK REL=DISCLAIMER HREF="../FrontMatter/About-HyperSpec.html#Disclaimer">
<LINK REL=PREV HREF="../Issues/iss176-writeup.html">
<LINK REL=UP HREF="../Issues/iss177.html">
<LINK REL=NEXT HREF="../Issues/iss178-writeup.html">

Issue FUNCTION-TYPE-KEY-NAME Writeup

Issue:         FUNCTION-TYPE-KEY-NAME

References:    CLtL p.47-48, 61

Category:      CLARIFICATION, CHANGE

Edit history:  Version 1, 23-Nov-1987 Sandra Loosemore

               Version 2, 15-Jan-1988 Sandra Loosemore

	           (from comments by Kent Pitman)

               Version 3, 13-Feb-88 Masinter

Related issues: FUNCTION-TYPE-REST-LIST-ELEMENT,

                KEYWORD-ARGUMENT-NAME-PACKAGE

                FUNCTION-ARGUMENT-TYPE-SEMANTICS

Problem description:

The FUNCTION type specifier list is provided to allow declaration of function

argument types and return value types.  This type specifier uses a syntax

similar to the usual lambda list syntax to specify which types go with which

lambda list variables.  However, there is a problem with &KEY lambda variables

because CLtL does not specify how the types specified in the FUNCTION

declaration are matched up to either the actual arguments passed to the

function, or the lambda variables in the function definition (since the ordering

of keyword arguments is arbitrary).

Proposal (FUNCTION-TYPE-KEY-NAME:SPECIFY-KEYWORD):

(1) Specify that the &KEY parameters in a FUNCTION type specifier lambda list

should be supplied as lists of the form (<keyword> <type>).  The <keyword> must

be a valid keyword-name symbol as must be supplied in the actual arguments of a

call. (This is usually a symbol in the keyword package, but, as per

KEYWORD-ARGUMENT-NAME-PACKAGE, not necessarily so.)

(2) Allow &ALLOW-OTHER-KEYS to appear in a FUNCTION type specifier lambda list.

The interpretation of such declarations is that, when &KEY is given in a

FUNCTION type specifier lambda list, it is safe to assume that the &KEYs given

are exhaustive unless &ALLOW-OTHER-KEYS is present.

&ALLOW-OTHER-KEYS is an indication that other keyword arguments may actually be

supplied and, if supplied, may be used.

Example:

The type of the function MAKE-LIST could be declared as:

   (FUNCTION MAKE-LIST ((INTEGER 0) &KEY (:INITIAL-ELEMENT T)) LIST)

Rationale:

(1) This specifies a direct correspondence between the argument type and its

matching keyword.  All of the information is in one place, and the user does not

have to remember (or even know) the order in which &KEY arguments appear in the

actual function definition.

(2) This is probably an oversight in the original specification.

Current practice:

Many Common Lisp implementations currently ignore FUNCTION type declarations.

The situation regarding type specifications for keyword arguments is so

ambiguous that few users attempt to use them.

Cost to Implementors:

Implementations that ignore the FUNCTION type specifier or keyword arguments in

a FUNCTION type specifier may continue to do so.  This proposal should not

involve massive amounts of code to be rewritten.

Cost to users:

Because the current situation is so ambiguous, FUNCTION type specifiers and

particularly the specification of keyword argument types are not widely used.

However, since this is an incompatible change, it would be nice if

implementations check for, and warn about, old-style usage.

Cost of non-adoption:

If nothing is done, the FUNCTION type specifier will continue to be of limited

use for its intended purpose.

Benefits:

Adopting the proposal will clear up an area of confusion in the language design.

Esthetics:

The syntax is fairly obvious and is analogous to the (<keyword> <variable>)

lambda list syntax.

Discussion:

The exact semantics of function declarations and the types of arguments  is

still under discussion, as are several other issues dealing with declarations.

However, this issue seemed separable.

Copyright 1996, The Harlequin Group Limited.  All Rights Reserved.


text:
package com.intellij.ide.util.newProjectWizard;

import com.intellij.openapi.ui.GraphicsConfig;
import com.intellij.ui.Gray;
import com.intellij.util.ui.GraphicsUtil;
import com.intellij.util.ui.UIUtil;
import sun.swing.SwingUtilities2;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.BasicButtonUI;
import java.awt.*;
import java.awt.geom.GeneralPath;
import java.awt.geom.Path2D;

/**
* @author Konstantin Bulenkov
*/
class WizardArrowUI extends BasicButtonUI {
  private final AbstractButton myButton;
  private static Rectangle viewRect = new Rectangle();
  private static Rectangle textRect = new Rectangle();
  private static Rectangle iconRect = new Rectangle();

  public WizardArrowUI(AbstractButton b, boolean valid) {
    myButton = b;
    //b.setIcon(EmptyIcon.create(1));
    b.setOpaque(false);
    b.setBorder(new EmptyBorder(8, 0, 8, 40));
  }

  @SuppressWarnings({"MethodOverridesStaticMethodOfSuperclass", "UnusedDeclaration"})
  public static ComponentUI createUI(JComponent c) {
    return new WizardArrowUI((AbstractButton)c, false);
  }

  @Override
  protected void paintIcon(Graphics g, JComponent c, Rectangle iconRect) {
  }

  @Override
  protected int getTextShiftOffset() {
    return 5;
  }

  private String layout(AbstractButton b, FontMetrics fm,
                        int width, int height) {
    Insets i = b.getInsets();
    viewRect.x = i.left;
    viewRect.y = i.top;
    viewRect.width = width - (i.right + viewRect.x);
    viewRect.height = height - (i.bottom + viewRect.y);

    textRect.x = textRect.y = textRect.width = textRect.height = 0;
    iconRect.x = iconRect.y = iconRect.width = iconRect.height = 0;

    // layout the text and icon
    return SwingUtilities.layoutCompoundLabel(
      b, fm, b.getText(), b.getIcon(),
      b.getVerticalAlignment(), b.getHorizontalAlignment(),
      b.getVerticalTextPosition(), b.getHorizontalTextPosition(),
      viewRect, iconRect, textRect,
      b.getText() == null ? 0 : b.getIconTextGap());
  }

  @Override
  public void paint(Graphics g, JComponent c) {
    int w = c.getWidth();
    int h = c.getHeight();
    layout(myButton, SwingUtilities2.getFontMetrics(c, g), w, h);

    final GraphicsConfig config = GraphicsUtil.setupAAPainting(g);
    h-=4;
    if (!myButton.isSelected()) {
      w-=15;
    }
    final Path2D.Double path = new GeneralPath.Double();
    path.moveTo(0, 0);
    path.lineTo(w - h / 2, 0);
    path.lineTo(w, h / 2);
    path.lineTo(w-h/2, h);
    path.lineTo(0, h);
    path.lineTo(0, 0);
    g.setColor(myButton.isSelected() ? UIUtil.getListSelectionBackground() : Gray._255.withAlpha(200));
    ((Graphics2D)g).fill(path);
    g.setColor(Gray._0.withAlpha(50));
    ((Graphics2D)g).draw(path);
    config.restore();
    textRect.x = 2;
    textRect.y-=7;
    c.setForeground(UIUtil.getListForeground(myButton.isSelected()));
    GraphicsUtil.setupAntialiasing(g);
    paintText(g, c, textRect, myButton.getText());
  }
}


text:
namespace blackhole {
inline namespace v1 {
namespace formatter {
namespace string {

class factory_t;

class parser_t {
public:
    typedef char char_type;
    typedef std::basic_string<char_type> string_type;

private:
    typedef string_type::const_iterator const_iterator;

    enum class state_t {
        /// Undetermined state.
        unknown,
        /// Parsing literal.
        literal,
        /// Parsing placeholder.
        placeholder,
        /// Parser is broken.
        broken
    };

    state_t state;

    const std::string pattern;
    const_iterator pos;

    std::unordered_map<std::string, std::shared_ptr<factory_t>> factories;

public:
    explicit parser_t(std::string pattern);

    auto next() -> boost::optional<token_t>;

private:
    auto parse_spec() -> std::string;
    auto parse_unknown() -> boost::optional<token_t>;
    auto parse_literal() -> literal_t;
    auto parse_placeholder() -> token_t;

    /// Returns `true` on exact match with the given range from the current position.
    ///
    /// The given range may be larger than `std::distance(pos, std::end(pattern))`.
    template<typename Range>
    auto exact(const Range& range) const -> bool;

    /// Returns `true` on exact match with the given range and position.
    ///
    /// The given range may be larger than `std::distance(pos, std::end(pattern))`.
    ///
    /// \overload
    template<typename Range>
    auto exact(const_iterator pos, const Range& range) const -> bool;

    /// Marks the parser as broken and throws an exception
    template<class Exception, class... Args>
    __attribute__((noreturn)) auto throw_(Args&&... args) -> void;
};

}  // namespace string
}  // namespace formatter
}  // namespace v1
}  // namespace blackhole


text:
class Genre < ApplicationRecord
  has_many :songs, dependent: :restrict_with_error

  validates_presence_of :name
  validates :name, uniqueness: { case_sensitive: false }
end


text:
<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class ProductsModel extends CI_Model {

    function __construct() {
        parent::__construct();
        $this->load->database();
    }

    public function products() {
        $this->db->select("*");
        $this->db->from("products");
        $query = $this->db->get();
        if ($query->num_rows() > 0) {
            return $query->result();
        } else {
            return FALSE;
        }
    }

    public function searchProducts($type, $price, $area){
        $sql = "SELECT * FROM products where 1 ";
        if($type!=""){
            $sql.=" AND type=$type ";
        }
        if($price != ""){
            $sql.="AND $price ";
        }
        if($area != ""){
            $sql.="AND $area";
        }
       $query = $this->db->query($sql);
        if($query->num_rows()>0){
            return $query->result();
        }else{
            return FALSE;
        }
    }
    public function record_cout(){
        return $this->db->count_all("products");
    }

    public function getProductState($state){
        $this->db->select("*");
        $this->db->from("products");
        $this->db->where('state',$state);
        $query = $this->db->get();
        if($query->num_rows()>0){
            return $query->result();
        }else{
            return FALSE;
        }
    }

    public function fetch_products($limit, $offset){
        $this->db->select("*");
        $this->db->from("products");
        $this->db->limit($limit, $offset);
        $query = $this->db->get();
        if($query->num_rows()>0){
            return $query->result();
        }else{
            return FALSE;
        }
    }

    public function delete($id){
        $this->db->where('id', $id);
       $query = $this->db->delete("products");
       if($query){
           return TRUE;
       }else{
           return FALSE;
       }
    }

    public function update($params){
        $data = array(
            'name' => $params['name'],
            'description' => $params['description'],
            'address' => $params['address'],
            'price' => $params['price'],
            'state' => $params['state'],
            'area' => $params['area'],
            'type' => $params['type'],
            'highlight'=>$params['highlight'],
            'update_At' => $params['update_At'],
            'thumbnail' => $params['thumbnail'],
            'slider_img' => $params['slider_img']);
        $this->db->where('id', $params['id']);
        $query = $this->db->update('products', $data);
        if($query){
            return TRUE;
        }else{
            return FALSE;
        }
    }

    public function getProduct($id){
        $this->db->select("*");
        $this->db->from("products");
        $this->db->where("id", $id);
        $query = $this->db->get();
         if ($query->num_rows() > 0) {
            return $query->row();
        } else {
            return FALSE;
        }
    }

    public function addProduct($params) {
        $this->db->trans_start();
        $data = array(
            'name' => $params['name'],
            'description' => $params['description'],
            'address' => $params['address'],
            'price' => $params['price'],
            'state' => $params['state'],
            'area' => $params['area'],
            'type' => $params['type'],
             'highlight'=>$params['highlight'],
            'create_At' => $params['create_At'],
            'update_At' => $params['update_At'],
            'thumbnail' => $params['thumbnail'],
            'slider_img' => $params['slider_img']);

        $query = $this->db->insert('products', $data);
        $insert_id = $this->db->insert_id();
        $this->db->trans_complete();
        if ($insert_id) {
            return $insert_id;
        } else {
            return -1;
       }
    }

}


text: Copyright 2017 Alexander Cafarella


text:
'''
Application example using build() + return
==========================================

An application can be built if you return a widget on build(), or if you set
self.root.
'''

import kivy
kivy.require('1.0.7')

from kivy.app import App
from kivy.uix.button import Button

class TestApp(App):

    def build(self):
        # return a Button() as a root widget
        return Button(text='hello world')

if __name__ == '__main__':
    TestApp().run()


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
org.smslib.modem Class Hierarchy (SMSLib 3.5.3)
</TITLE>

<META NAME="date" CONTENT="2013-03-06">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
      Use
    Tree
      Deprecated
      Index
      Help

SMSLib 3.5.3

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Hierarchy For Package org.smslib.modem

Package Hierarchies:
All Packages

Class Hierarchy

java.lang.Object

org.smslib.AGateway

org.smslib.modem.ModemGateway

org.smslib.modem.IPModemGateway
org.smslib.modem.SerialModemGateway

org.smslib.modem.AModemDriver
org.smslib.modem.CNMIDetector

Enum Hierarchy

java.lang.Object

java.lang.Enum<E> (implements java.lang.Comparable<T>, java.io.Serializable)

org.smslib.modem.ModemGateway.ModemTypes
org.smslib.modem.ModemGateway.IPProtocols

      Overview
      Package
      Class
      Use
    Tree
      Deprecated
      Index
      Help

SMSLib 3.5.3

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

(c) 2002-2011, http://smslib.org


text:
Loup.Dependencer.define('upload-component', () => {
	const blankPixel = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
	const dependencer = Loup.Dependencer.load('loup-dependencer')
	const l = dependencer.load('loup-logger')
	const ajax = dependencer.load('loup-ajax')

	return {
		name: 'upload-component',
		template: `

					<button id='uploadComponent-saveButton' v-on:click='uploadAll' v-bind:disabled='uploadAllLocked'>upload</button>

								Filename
								<input v-bind:id="'desiredName_' + fileBox.fileComponentKey" type='text' placeholder='desired filename' v-model='fileBox.filename'/>

								Tags
								<input v-bind:id="'tagString_' + fileBox.fileComponentKey" type='text' placeholder='space separated tags' v-model='fileBox.tagString'/>

							<input v-bind:id="'file_' + fileBox.fileComponentKey" class='uploadComponent-fileSelector' type='file' v-on:change='fileChanged(fileBox.fileComponentKey)'/>

{{fileBox.errorMessage}}

		`,
		data: () => {
			return {
				nextFileComponentKey: 2,
				uploadAllLocked: false,
				fileComponentKeysToBeUploaded: [],
				fileBoxes: {
					1: {
						fileComponentKey: 1,
						filename: undefined,
						tagString: '',
						errorMessage: undefined,
						previewSrc: blankPixel
					}
				}
			}
		},
		created() {

		},
		methods: {
			fileChanged(fileComponentKey) {
				const fileInput = document.getElementById(`file_${fileComponentKey}`)

				const fileBox = this.fileBoxes[fileComponentKey]
				fileBox.errorMessage = ''
				const wasEmpty = !fileBox.filename
				const isEmpty = fileInput.files.length === 0

				if (wasEmpty && isEmpty) {
					return
				}

				const nextComponentKey = this.nextFileComponentKey++

				if (wasEmpty) {
					Vue.set(this.fileBoxes, nextComponentKey, {
						fileComponentKey: nextComponentKey,
						filename: undefined,
						tagString: '',
						errorMessage: undefined,
						previewSrc: blankPixel,
					})
				}

				const file = fileInput.files[0]

				reader = new FileReader()
				reader.onload = e => {
					this.previewSrc = e.target.result
					fileBox.previewSrc = e.target.result
				}
				reader.readAsDataURL(file)

				fileBox.filename = file.name
				//fileBox.tagString = document.getElementById(`tagString_${fileComponentKey}`)
				fileBox.errorMessage = ''
			},
			uploadAll() {
				l.log('uploadAll called...')
				if (this.uploadAllLocked) {
					l.log('Attempted to upload all while upload all was in progress!')
					return;
				}
				this.uploadAllLocked = true

				this.fileComponentKeysToBeUploaded = Object.keys(this.fileBoxes)
				this.attemptNextUpload()
			},
			attemptNextUpload() {
				const next = this.fileComponentKeysToBeUploaded.shift()

				if (next) {
					l.log(`Attempting to upload file number <${next}>.`)
					const obj = this.fileBoxes[next]
					const fileDOM = document.getElementById(`file_${obj.fileComponentKey}`)

					if (fileDOM.files.length !== 0) {
						const file = fileDOM.files[0]

						const formData = new FormData()

						formData.append('file', file)
						formData.append('filename', obj.filename)
						formData.append('tagString', obj.tagString)

						l.log('Executing upload...')

						ajax.post(
							'/file',
							formData,
							r => {
								const response = JSON.parse(r.responseText)
								l.log(`Upload for file with fileComponentKey<${this.fileComponentKey}> with filename<${this.desiredName}> ok, image id is <${response.id}>.`)

								Vue.delete(this.fileBoxes, next)
							}, r => {
								this.errorMessage = 'File could not be uploaded...'
								l.log(`Upload for file with fileComponentKey<${this.fileComponentKey}> with filename<${this.desiredName}> failed.`)
								obj.errorMessage = 'ERROR'
							}, r => {
								l.log(`upload response<${r.responseText}>'`)
								this.attemptNextUpload()
							})
					} else {
						this.attemptNextUpload()
					}
				} else {
					this.uploadAllLocked = false
				}

			}
		}
	}
});


text:
package oj.leetcode.string.last;

import static org.junit.Assert.*;

import org.junit.Test;

public class LengthOfLastWordTest {

	private final LengthOfLastWord inst = new LengthOfLastWord();

	@Test
	public void test() {
		int length = inst.lengthOfLastWord("hello world");
		assertEquals(length, 5);

		length = inst.lengthOfLastWord("hello");
		assertEquals(length, 5);

		length = inst.lengthOfLastWord("    ");
		assertEquals(length, 0);

		length = inst.lengthOfLastWord("hello world    ");
		assertEquals(length, 5);
	}

}


text:
-- Adding index to sort by uploader
ALTER TABLE /*$wgDBprefix*/filearchive
  ADD INDEX fa_user_timestamp (fa_user_text,fa_timestamp),
  -- Remove useless, incomplete index
  DROP INDEX fa_deleted_user;


text:
"""
Created on Thu Jan 22 19:47:49 2015

@author: stevo
"""

import sys
import click
from signal import signal, SIGPIPE, SIG_DFL; signal(SIGPIPE,SIG_DFL)

def head(fin, numtokens):
    print('reading sentences file.', file=sys.stderr)
    num_tokens_printed = 0;
    c1 = 0
    c2 = 0;
    for line in fin:
        c1 += 1
        if num_tokens_printed > numtokens:
            break
        line = line.rstrip()
        if not line:
            continue
        splits = line.split('\t')
        print(splits[0], file=sys.stdout)
        num_tokens_printed = int(splits[1])
        c2 += 1
    print('read {} lines. Printed {} tokens from {} sentences.'.format(c1, num_tokens_printed, c2), file=sys.stderr);

@click.command()
@click.option('-f', '--sentences', help='File containing one sentence per line incl. counts. Specify "-" to read from stdin.', type=click.File('r'), required=True, default='-')
@click.option('-n', '--numtokens', help='Print the first sentences that have maximally n number of tokens in sum.', default='10')
def run_cli(sentences, numtokens):
    '''
      add the number of tokens for the current line and sum of tokens after the current line from the beginning
    '''
    numtokens=int(numtokens.replace('G','KM').replace('M','KK').replace('K','000'))
    head(sentences, numtokens)

if __name__ == '__main__':
    run_cli()


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<template type="basic" name="DcpN15C13scarbonylSET" author="Agilent" investigator=""
        time_created="20111219T120000" tabname="BioSolidsPack" menu1="Commands" menu2="Set Values" apptype="solidsseq1d"
        application="BioSolids" scans="DcpN15C13scarbonylSET" seqfil="ahYX">
  <protocol title="DcpN15C13scarbonylSET" type="protocol">
    <action  type="CMD" status="Ready" lock="off" title="DcpN15C13scarbonylSET" exp="DcpN15C13scarbonylSET"
        time="1:45" macro="DcpN15C13scarbonylSET" data="" />
  </protocol>
</template>