text:
import React, { ReactElement } from "react"
import {
  render as originalRender,
  RenderOptions,
  screen,
} from "@testing-library/react"
import userEvent from "@testing-library/user-event"

import {
  ArtworkFilterContextProps,
  ArtworkFilterContextProvider,
  useArtworkFilterContext,
} from "Components/ArtworkFilter/ArtworkFilterContext"
import {
  getPredefinedSizesByMetric,
  parseRange,
  SizeFilter,
  SIZES_IN_CENTIMETERS,
  SIZES_IN_INCHES,
  getCustomSizeRangeInInches,
  CustomSize,
} from "../SizeFilter"

jest.mock("Utils/Hooks/useMatchMedia", () => ({
  __internal__useMatchMedia: () => ({}),
}))

const render = (ui: ReactElement, options: RenderOptions = {}) =>
  originalRender(ui, { wrapper: Wrapper, ...options })

const Wrapper: React.FC = ({ children }) => {
  return (
    <ArtworkFilterContextProvider>
      <ClearAllButton />
      {children}
      <ArtworkFilterContextInspector />
    </ArtworkFilterContextProvider>
  )
}

const ClearAllButton: React.FC = () => {
  const artworkFilterContext = useArtworkFilterContext()

  return (
    <button onClick={() => artworkFilterContext.resetFilters()}>
      Clear all
    </button>
  )
}

const ArtworkFilterContextInspector: React.FC = () => {
  const artworkFilterContext = useArtworkFilterContext()

  return (
    <aside data-testid="artwork-filter-context-inspector">
      {JSON.stringify(artworkFilterContext, null, 2)}
    </aside>
  )
}

const currentContext = (): ArtworkFilterContextProps => {
  let contextInspector: HTMLElement
  try {
    contextInspector = screen.getByTestId("artwork-filter-context-inspector")
  } catch (error) {
    if (error.name === "TestingLibraryElementError")
      throw new Error(
        `The currentContext() helper function requires an <ArtworkFilterContextInspector /> to be mounted in the current DOM.`
      )
  }
  return JSON.parse(contextInspector!.textContent!)
}

describe("SizeFilter", () => {
  it("toggles custom input render", () => {
    render(<SizeFilter expanded />)

    // note: an <input type="number" /> has a role of 'spinbutton'
    expect(screen.queryByRole("spinbutton")).not.toBeInTheDocument()

    userEvent.click(screen.getByText("Show custom size"))

    expect(screen.getByText("Hide custom size")).toBeInTheDocument()
    expect(screen.getAllByRole("spinbutton")).toHaveLength(4)
    expect(screen.getByText("Height")).toBeInTheDocument()
    expect(screen.getByText("Width")).toBeInTheDocument()
  })

  it("updates context on filter change", () => {
    render(<SizeFilter expanded />)
    expect(currentContext().filters?.sizes).toEqual([])

    userEvent.click(screen.getAllByRole("checkbox")[0])
    expect(currentContext().filters?.sizes).toEqual(["SMALL"])

    userEvent.click(screen.getAllByRole("checkbox")[2])
    expect(currentContext().filters?.sizes).toEqual(["SMALL", "LARGE"])
  })

  it("updates the filter values", async () => {
    render(<SizeFilter expanded />)

    userEvent.click(screen.getByText("Show custom size"))
    userEvent.type(screen.getAllByRole("spinbutton")[0], "12")
    userEvent.type(screen.getAllByRole("spinbutton")[1], "16")
    userEvent.type(screen.getAllByRole("spinbutton")[2], "12")
    userEvent.type(screen.getAllByRole("spinbutton")[3], "16")
    userEvent.click(screen.getByText("Set size"))

    expect(currentContext().filters?.sizes).toEqual([])
    expect(currentContext().filters?.height).toEqual(
      "4.724409448818897-6.299212598425196"
    )
    expect(currentContext().filters?.width).toEqual(
      "4.724409448818897-6.299212598425196"
    )
  })

  it("updates the filter values when only one dimension is added", () => {
    render(<SizeFilter expanded />)
    userEvent.click(screen.getByText("Show custom size"))
    screen.getAllByRole("spinbutton").map(field => userEvent.clear(field)) // 😭
    userEvent.type(screen.getAllByRole("spinbutton")[2], "12")
    userEvent.type(screen.getAllByRole("spinbutton")[3], "24")
    userEvent.click(screen.getByText("Set size"))

    expect(currentContext().filters?.sizes).toEqual([])
    expect(currentContext().filters?.height).toEqual(
      "4.724409448818897-9.448818897637794"
    )
    expect(currentContext().filters?.width).toEqual("*-*")
  })

  it("clears local input state after Clear All", () => {
    render(<SizeFilter expanded />)

    // before: filter state and input state are empty
    expect(currentContext().filters?.height).toEqual("*-*")
    expect(currentContext().filters?.width).toEqual("*-*")
    expect(screen.queryByDisplayValue("1")).not.toBeInTheDocument()
    expect(screen.queryByDisplayValue("2")).not.toBeInTheDocument()
    expect(screen.queryByDisplayValue("3")).not.toBeInTheDocument()
    expect(screen.queryByDisplayValue("4")).not.toBeInTheDocument()

    // act: enter custom height and width
    userEvent.click(screen.getByText("Show custom size"))
    screen.getAllByRole("spinbutton").map(field => userEvent.clear(field)) // 😭
    userEvent.type(screen.getAllByRole("spinbutton")[0], "1")
    userEvent.type(screen.getAllByRole("spinbutton")[1], "2")
    userEvent.type(screen.getAllByRole("spinbutton")[2], "3")
    userEvent.type(screen.getAllByRole("spinbutton")[3], "4")
    userEvent.click(screen.getByText("Set size"))

    // assert: state and ui are updated
    expect(currentContext().filters?.sizes).toEqual([])
    expect(currentContext().filters?.width).toEqual(
      "0.39370078740157477-0.7874015748031495"
    )
    expect(currentContext().filters?.height).toEqual(
      "1.1811023622047243-1.574803149606299"
    )
    expect(screen.queryByDisplayValue("1")).toBeInTheDocument()
    expect(screen.queryByDisplayValue("2")).toBeInTheDocument()
    expect(screen.queryByDisplayValue("3")).toBeInTheDocument()
    expect(screen.queryByDisplayValue("4")).toBeInTheDocument()

    // act: clear all filters
    userEvent.click(screen.getByText("Clear all"))

    // assert: state and ui are cleared
    expect(currentContext().filters?.height).toEqual("*-*")
    expect(currentContext().filters?.width).toEqual("*-*")
    expect(screen.queryByDisplayValue("1")).not.toBeInTheDocument()
    expect(screen.queryByDisplayValue("2")).not.toBeInTheDocument()
    expect(screen.queryByDisplayValue("3")).not.toBeInTheDocument()
    expect(screen.queryByDisplayValue("4")).not.toBeInTheDocument()
  })

  describe("Metric", () => {
    it("should display predefined sizes in centimeters by default", () => {
      render(<SizeFilter expanded />)

      expect(screen.getByText("Small (under 40cm)")).toBeInTheDocument()
      expect(screen.getByText("Medium (40 – 100cm)")).toBeInTheDocument()
      expect(screen.getByText("Large (over 100cm)")).toBeInTheDocument()
    })

    it("should display predefined sizes in inches when `in` metric is selected", () => {
      render(<SizeFilter expanded />)

      userEvent.click(screen.getByText("in"))

      expect(screen.getByText("Small (under 16in)")).toBeInTheDocument()
      expect(screen.getByText("Medium (16in – 40in)")).toBeInTheDocument()
      expect(screen.getByText("Large (over 40in)")).toBeInTheDocument()
    })

    it("restore default metric when `Clear All` button is pressed", () => {
      render(<SizeFilter expanded />)

      userEvent.click(screen.getByText("in"))
      userEvent.click(screen.getByText("Clear all"))

      const element = screen.getByRole("radio", {
        name: "cm",
      })

      expect(element).toBeChecked()
    })
  })

  describe("the `expanded` prop", () => {
    it("hides the filter controls when not set", () => {
      render(<SizeFilter />)
      expect(screen.queryByRole("checkbox")).not.toBeInTheDocument()
    })

    it("hides the filter controls when `false`", () => {
      render(<SizeFilter expanded={false} />)
      expect(screen.queryByRole("checkbox")).not.toBeInTheDocument()
    })

    it("shows the filter controls when `true`", () => {
      render(<SizeFilter expanded={true} />)
      expect(screen.getAllByRole("checkbox")).toHaveLength(3)
    })
  })
})

describe("getPredefinedSizesByMetric", () => {
  it("should return predefined sizes in centimeters when `cm` metric is specified", () => {
    expect(getPredefinedSizesByMetric("cm")).toEqual(SIZES_IN_CENTIMETERS)
  })

  it("should return predefined sizes in inches when `in` metric is specified", () => {
    expect(getPredefinedSizesByMetric("in")).toEqual(SIZES_IN_INCHES)
  })
})

describe("parseRange", () => {
  it("correctly parse range in inches", () => {
    expect(parseRange("10-20", "in")).toEqual([10, 20])
  })

  it("correctly parse range in inches with default value", () => {
    expect(parseRange("10-*", "in")).toEqual([10, "*"])
  })

  it("correctly parse range in inches when all values are default", () => {
    expect(parseRange("*-*", "in")).toEqual(["*", "*"])
  })

  it("correctly parse range in centimeters", () => {
    expect(parseRange("1-2", "cm")).toEqual([3, 5])
  })

  it("correctly parse range in centimeters with default value", () => {
    expect(parseRange("1-*", "cm")).toEqual([3, "*"])
  })

  it("correctly parse range in centimeters when all values are default", () => {
    expect(parseRange("*-*", "cm")).toEqual(["*", "*"])
  })
})

describe("getCustomSizeRangeInInches", () => {
  it("should return correct custom size ranges in inches", () => {
    const range: CustomSize = {
      width: [5, 10],
      height: [15, 20],
    }
    const result = {
      width: "5-10",
      height: "15-20",
    }

    expect(getCustomSizeRangeInInches(range, "in")).toEqual(result)
  })

  it("should return correct custom size ranges in inches when default values are passed", () => {
    const range: CustomSize = {
      width: [5, "*"],
      height: ["*", 20],
    }
    const result = {
      width: "5-*",
      height: "*-20",
    }

    expect(getCustomSizeRangeInInches(range, "in")).toEqual(result)
  })

  it("should return custom size ranges with default values", () => {
    const range: CustomSize = {
      width: ["*", "*"],
      height: ["*", "*"],
    }
    const result = {
      width: "*-*",
      height: "*-*",
    }

    expect(getCustomSizeRangeInInches(range, "in")).toEqual(result)
  })

  it("should return correct custom size ranges in centimeters", () => {
    const range: CustomSize = {
      width: [5, 10],
      height: [15, 20],
    }
    const result = {
      width: "1.968503937007874-3.937007874015748",
      height: "5.905511811023622-7.874015748031496",
    }

    expect(getCustomSizeRangeInInches(range, "cm")).toEqual(result)
  })

  it("should return correct custom size ranges in centimeters when default values are passed", () => {
    const range: CustomSize = {
      width: ["*", 10],
      height: [15, "*"],
    }
    const result = {
      width: "*-3.937007874015748",
      height: "5.905511811023622-*",
    }

    expect(getCustomSizeRangeInInches(range, "cm")).toEqual(result)
  })
})


text:
<?php

use Cake\Datasource\ConnectionManager;
use Cake\Utility\Hash;

ConnectionManager::config(Hash::merge([
	'default' => [
		'className' => 'Cake\Database\Connection',
		'driver' => 'Cake\Database\Driver\Mysql',
		'persistent' => false,
		'host' => $_ENV['DB1_HOST'],
		'username' => $_ENV['DB1_USER'],
		'password' => $_ENV['DB1_PASS'],
		'database' => $_ENV['DB1_NAME'],
		'prefix' => false,
		'encoding' => strtolower(str_replace('-', '', read('App.encoding'))),
		'timezone' => read('App.timezone'),
		'quoteIdentifiers' => false
	],
	'test' => [
		'className' => 'Cake\Database\Connection',
		'driver' => 'Cake\Database\Driver\Mysql',
		'persistent' => false,
		'host' => 'localhost',
		'username' => 'app',
		'password' => 'app',
		'database' => 'test_app',
		'prefix' => false,
		'encoding' => strtolower(str_replace('-', '', read('App.encoding'))),
		'timezone' => read('App.timezone'),
		'quoteIdentifiers' => false
	]
], consume('Datasources')));

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * User: Mario Giustiniani
 * Date: 04/05/14
 * Time: 15.56
 */
$file = __DIR__.'/../vendor/autoload.php';
if (!file_exists($file)) {
    throw new RuntimeException('Install dependencies to run test suite.');
}

$autoload = require_once $file;

use Doctrine\Common\Annotations\AnnotationRegistry;
AnnotationRegistry::registerLoader(function($class) {
    if (strpos($class, 'FOS\RestBundle\Controller\Annotations\\') === 0) {
        $path = __DIR__.'/../'.str_replace('\\', '/', substr($class, strlen('FOS\RestBundle\\')))   .'.php';
        require_once $path;
    }

    return class_exists($class, false);
});


text:
class BaseDelivery:
    def __init__(self, config, logger=None):
        pass

    def deliver(self, user, domain, message, from_):
        raise NotImplementedError


text:
package fixtures.bodybyte;

import com.microsoft.rest.ServiceException;
import fixtures.bodyboolean.AutoRestBoolTestService;
import fixtures.bodyboolean.AutoRestBoolTestServiceImpl;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

public class ByteOperationsTests {
    static AutoRestSwaggerBATByteService client;

    @BeforeClass
    public static void setup() {
        client = new AutoRestSwaggerBATByteServiceImpl("http://localhost:3000");
    }

    @Test
    public void getNull() throws Exception {
        Assert.assertNull(client.getByteOperations().getNull());
    }

    @Test
    public void getEmpty() throws Exception {
        byte[] result = client.getByteOperations().getEmpty();
        Assert.assertEquals(0, result.length);
    }

    @Test
    public void getNonAscii() throws Exception {
        byte[] result = client.getByteOperations().getNonAscii();
        byte[] expected = new byte[] {
                (byte) 0xff, (byte) 0xfe, (byte) 0xfd, (byte) 0xfc, (byte) 0xfb,
                (byte) 0xfa, (byte) 0xf9, (byte) 0xf8, (byte) 0xf7, (byte) 0xf6
        };
        Assert.assertArrayEquals(expected, result);
    }

    @Test
    public void putNonAscii() throws Exception {
        byte[] body = new byte[] {
                (byte) 0xff, (byte) 0xfe, (byte) 0xfd, (byte) 0xfc, (byte) 0xfb,
                (byte) 0xfa, (byte) 0xf9, (byte) 0xf8, (byte) 0xf7, (byte) 0xf6
        };
        client.getByteOperations().putNonAscii(body);
    }

    @Test
    public void getInvalid() throws Exception {
        try {
            client.getByteOperations().getInvalid();
            Assert.assertTrue(false);
        } catch (Exception exception) {
            // expected
            Assert.assertEquals(ServiceException.class, exception.getClass());
            Assert.assertTrue(exception.getMessage().contains("JsonParseException"));
        }
    }
}


text:
package cz.muni.fi.pa165.mushrooms.mvc.forms;

import cz.muni.fi.pa165.mushrooms.dto.MushroomDTO;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author bencikpeter
 */

public class MushroomDTOValidator implements Validator {
    @Override
    public boolean supports(Class<?> aClass) {
        return MushroomDTO.class.isAssignableFrom(aClass);
    }

    @Override
    public void validate(Object o, Errors errors) {
        MushroomDTO dto = (MushroomDTO) o;
        String pattern = "(.*) - (.*)";
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(dto.getIntervalOfOccurrence());
        if (!m.matches()){
            errors.rejectValue("intervalOfOccurrence", "MushroomDTOValidator.intervalOfOccurence.wrongFormat");
        }

    }
}


text:
package com.zireck.calories.domain.interactor;

import com.zireck.calories.domain.executor.PostExecutionThread;
import com.zireck.calories.domain.executor.ThreadExecutor;
import com.zireck.calories.domain.repository.FoodRepository;

import javax.inject.Inject;

import rx.Observable;

/**
 * Created by Zireck on 14/08/2015.
 */
public class GetDrinkList extends Interactor {

    private final FoodRepository mFoodRepository;

    @Inject
    public GetDrinkList(FoodRepository foodRepository, ThreadExecutor threadExecutor,
                       PostExecutionThread postExecutionThread) {
        super(threadExecutor, postExecutionThread);
        mFoodRepository = foodRepository;
    }

    @Override
    protected Observable buildInteractorObservable() {
        return mFoodRepository.drinks();
    }
}


text:
C nicked from pgplot
C*GRGLUN -- get a Fortran logical unit number (Sun/Convex-UNIX)
C+
      SUBROUTINE GLUN(LUN)
      INTEGER LUN
C
C Get an unused Fortran logical unit number.
C Returns a Logical Unit Number that is not currently opened.
C After GRGLUN is called, the unit should be opened to reserve
C the unit number for future calls.  Once a unit is closed, it
C becomes free and another call to GRGLUN could return the same
C number.  Also, GRGLUN will not return a number in the range 1-9
C as older software will often use these units without warning.
C
C Arguments:
C  LUN    : receives the logical unit number, or -1 on error.
C--
C 12-Feb-1989 [AFT/TJP].
C DRL adapted to subroutine GLUN for use with psrevolve
C 16-Jul-1993 @ JB
C-----------------------------------------------------------------------
      INTEGER I
      LOGICAL QOPEN
C---
      DO 10 I=99,10,-1
          INQUIRE (UNIT=I,  OPENED=QOPEN)
          IF (.NOT.QOPEN) THEN
              LUN = I
              RETURN
          END IF
   10 CONTINUE
C none left
      STOP 'RAN OUT OF LUNs!'
      END


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ExtensionMethods;
using ebIModels.Models;
using SRC = ebIModels.Schema.ebInterface4p0;
using ebIModels.Schema;
using SettingsManager;
using LogService;

namespace ebIModels.Mapping.V4p0
{
    public static partial class MapInvoice
    {
        /// <summary>
        /// Mapped ebInterface4p1 InvoiceType auf InvoiceType Model
        /// </summary>
        /// <param name="source">ebInterface4p1 InvoiceType</param>
        /// <returns>InvoiceType Model</returns>
        internal static IInvoiceModel MapV4P0ToVm(SRC.InvoiceType source)
        {
            IInvoiceModel invoice = InvoiceFactory.CreateInvoice();
            #region Rechnungskopf
            invoice.InvoiceNumber = source.InvoiceNumber;
            invoice.InvoiceDate = source.InvoiceDate;
            invoice.GeneratingSystem = source.GeneratingSystem;
            invoice.DocumentTitle = source.DocumentTitle;
            invoice.DocumentType = source.DocumentType.ConvertEnum<DocumentTypeType>();
            invoice.InvoiceCurrency = source.InvoiceCurrency.ConvertEnum<CurrencyType>(); // source.InvoiceCurrency.ConvertEnum<CurrencyType>();
            invoice.Language = source.Language.ConvertEnum<LanguageType>();

            if (source.CancelledOriginalDocument == null)
            {
                invoice.CancelledOriginalDocument = null;
            }
            else
            {
                invoice.CancelledOriginalDocument = new CancelledOriginalDocumentType()
                {
                    DocumentTypeSpecified = false,

                    InvoiceNumber = source.CancelledOriginalDocument
                };
            }
            #endregion

            #region Delivery
            if (source.Delivery != null)
            {
                if (source.Delivery.Item is SRC.PeriodType)
                {
                    var deliveryType = new PeriodType
                    {
                        FromDate = ((SRC.PeriodType)source.Delivery.Item).FromDate,
                        ToDate = ((SRC.PeriodType)source.Delivery.Item).ToDate
                    };
                    invoice.Delivery.Item = deliveryType;
                }
                else
                {
                    var period = new PeriodType();
                    if (source.Delivery.Item != null)
                    {
                        period.FromDate = (DateTime)source.Delivery.Item;
                    }
                    invoice.Delivery.Item = period;    // für das Model immer eine Lieferperiode, damit von/bis leichter abgebildet werden kann
                }
            }
            #endregion

            #region Biller
            invoice.Biller.VATIdentificationNumber = source.Biller.VATIdentificationNumber;
            invoice.Biller.InvoiceRecipientsBillerID = source.Biller.InvoiceRecipientsBillerID;
            invoice.Biller.Address = GetAddress(source.Biller.Address);
            invoice.Biller.Contact = GetContact(source.Biller.Address);
            invoice.Biller.FurtherIdentification = GetFurtherIdentification(source.Biller.FurtherIdentification);

            #endregion

            #region InvoiceRecipient
            invoice.InvoiceRecipient.BillersInvoiceRecipientID = source.InvoiceRecipient.BillersInvoiceRecipientID;
            invoice.InvoiceRecipient.VATIdentificationNumber = source.InvoiceRecipient.VATIdentificationNumber;
            invoice.InvoiceRecipient.Address = GetAddress(source.InvoiceRecipient.Address);
            invoice.InvoiceRecipient.Contact = GetContact(source.InvoiceRecipient.Address);
            if (source.InvoiceRecipient.OrderReference != null)
            {
                invoice.InvoiceRecipient.OrderReference.OrderID = source.InvoiceRecipient.OrderReference.OrderID;
                invoice.InvoiceRecipient.OrderReference.ReferenceDateSpecified = source.InvoiceRecipient.OrderReference.ReferenceDateSpecified;
                invoice.InvoiceRecipient.OrderReference.ReferenceDate = source.InvoiceRecipient.OrderReference.ReferenceDate;

            }
            invoice.InvoiceRecipient.FurtherIdentification = null;
            invoice.InvoiceRecipient.SubOrganizationID = source.InvoiceRecipient.SubOrganizationID;
            invoice.InvoiceRecipient.AccountingArea = source.InvoiceRecipient.AccountingArea;
            #endregion

            #region Details
            invoice.Details.HeaderDescription = source.Details.HeaderDescription;
            invoice.Details.FooterDescription = source.Details.FooterDescription;

            invoice.Details.ItemList = new List<ItemListType>();
            if (source.Details.ItemList != null)
                foreach (SRC.ItemListType srcItemList in source.Details.ItemList)
                {
                    ItemListType item = new ItemListType
                    {
                        ListLineItem = new List<ListLineItemType>()
                    };
                    foreach (SRC.ListLineItemType srcLineItem in srcItemList.ListLineItem)
                    {
                        ListLineItemType lineItem = new ListLineItemType
                        {
                            AdditionalInformation = null,
                            PositionNumber = srcLineItem.PositionNumber,
                            Description = new List<string>()
                        };
                        if (srcLineItem.Description != null)
                        {
                            lineItem.Description = srcLineItem.Description.ToList();
                        }

                        lineItem.ArticleNumber = GetArtikelList(srcLineItem.ArticleNumber);

                        // Menge
                        lineItem.Quantity = new UnitType
                        {
                            Unit = srcLineItem.Quantity.Unit,
                            Value = srcLineItem.Quantity.Value
                        };

                        // Einzelpreis
                        lineItem.UnitPrice = new UnitPriceType()
                        {
                            Value = srcLineItem.UnitPrice
                        };

                        // Auftragsreferenz
                        lineItem.InvoiceRecipientsOrderReference.OrderID =
                            srcLineItem?.InvoiceRecipientsOrderReference?.OrderID;
                        lineItem.InvoiceRecipientsOrderReference.OrderPositionNumber =
                            srcLineItem?.InvoiceRecipientsOrderReference?.OrderPositionNumber;

                        // Rabatte / Zuschläge
                        if (srcLineItem.ReductionAndSurchargeListLineItemDetails != null)
                        {
                            lineItem.ReductionAndSurchargeListLineItemDetails = GetReductionDetails(srcLineItem.ReductionAndSurchargeListLineItemDetails);
                        }
                        lineItem.Description = new List<string>();
                        if (srcLineItem.Description != null)
                        {
                            lineItem.Description = srcLineItem.Description.ToList();
                        }

                        lineItem.LineItemAmount = srcLineItem.LineItemAmount;

                        // Steuer
                        lineItem.TaxItem = MapVatItemType2Vm(srcLineItem.TaxRate, lineItem.LineItemAmount);
                        lineItem.ReCalcLineItemAmount();
                        item.ListLineItem.Add(lineItem);
                    }
                    invoice.Details.ItemList.Add(item);
                }

            #endregion

            #region Tax
            invoice.CalculateTotals();

            #endregion

            #region Amount
            invoice.TotalGrossAmount = source.TotalGrossAmount;
            invoice.PayableAmount = source.TotalGrossAmount;
            #endregion

            #region PaymentMethod
            invoice.PaymentMethod.Comment = source.PaymentMethod.Comment;
            {
                SRC.UniversalBankTransactionType txType = source.PaymentMethod as SRC.UniversalBankTransactionType;
                invoice.PaymentMethod = new PaymentMethodType
                {
                    Item = new UniversalBankTransactionType()
                };
                ((UniversalBankTransactionType)invoice.PaymentMethod.Item).BeneficiaryAccount = new List<AccountType>()
                {
                    new AccountType()
                    {
                        BIC = txType.BeneficiaryAccount.First().BIC,
                        BankName = txType.BeneficiaryAccount.First().BankName,
                        IBAN = txType.BeneficiaryAccount.First().IBAN,
                        BankAccountOwner = txType.BeneficiaryAccount.First().BankAccountOwner

                    },
                };
            }

            #endregion

            #region Paymentconditions
            invoice.PaymentConditions.DueDate = source.PaymentConditions.DueDate;
            if (source.PaymentConditions.Discount != null)
            {
                invoice.PaymentConditions.Discount.Clear();
                foreach (SRC.DiscountType srcDiscount in source.PaymentConditions.Discount)
                {
                    DiscountType discount = new DiscountType()
                    {
                        Amount = srcDiscount.Amount,
                        AmountSpecified = srcDiscount.AmountSpecified,
                        BaseAmount = srcDiscount.BaseAmount,
                        BaseAmountSpecified = srcDiscount.BaseAmountSpecified,
                        PaymentDate = srcDiscount.PaymentDate,
                        Percentage = srcDiscount.Percentage,
                        PercentageSpecified = srcDiscount.PercentageSpecified
                    };
                    invoice.PaymentConditions.Discount.Add(discount);
                }
            }
            #endregion
            return invoice;
        }
        private static ContactType GetContact(SRC.AddressType address)
        {
            ContactType contact = new ContactType()
            {
                Email = new List<string>() { address.Email },
                Name = address.Contact,
                Phone = new List<string>() { address.Phone },
                Salutation = address.Salutation
            };
            return contact;
        }

        private static AddressType GetAddress(SRC.AddressType address)
        {

            if (address == null)
            {
                return null;
            }
            AddressType addrNew = new AddressType
            {
                Name = address.Name,
                //addrNew.Contact = address.Contact;
                Phone = address.Phone,
                POBox = address.POBox,
                Email = address.Email,
                //addrNew.Salutation = address.Salutation;
                Street = address.Street,
                Country = GetCountry(address.Country),
                ZIP = address.ZIP,
                Town = address.Town,
                AddressIdentifier = GetAddressIdentifier(address.AddressIdentifier)
            };
            return addrNew;
        }
        private static CountryType GetCountry(SRC.CountryType countryType)
        {
            if (countryType == null)
                return null;
            CountryType cty = new CountryType(CountryCodeType.AT);
            if (countryType.Text != null)
            {
                cty.CountryCode = countryType.CountryCode.ToString();
                cty.Value = CountryCodes.GetFromCode(cty.CountryCode.ToString()).Country;
            }
            return cty;
        }
        private static ReductionAndSurchargeListLineItemDetailsType GetReductionDetails(SRC.ReductionAndSurchargeListLineItemDetailsType srcRed)
        {
            if (srcRed.Items == null)
                return null;
            ReductionAndSurchargeListLineItemDetailsType lineRed = new ReductionAndSurchargeListLineItemDetailsType();
            //lineRed.Items = new object[srcRed.Items.Length];

            foreach (var item1 in srcRed.Items)
            {
                if (item1 is SRC.ReductionAndSurchargeBaseType)
                {
                    SRC.ReductionAndSurchargeBaseType item = item1 as SRC.ReductionAndSurchargeBaseType;
                    ReductionAndSurchargeBaseType redBase = new ReductionAndSurchargeBaseType
                    {
                        Amount = item.Amount,
                        AmountSpecified = item.AmountSpecified,
                        BaseAmount = item.BaseAmount,
                        Percentage = item.Percentage,
                        PercentageSpecified = item.PercentageSpecified
                    };
                    lineRed.Items.Add(redBase);
                }
            }
            lineRed.ItemsElementName = new List<ItemsChoiceType>();
            foreach (
                SRC.ItemsChoiceType choiceType in
                    srcRed.ItemsElementName)
            {
                lineRed.ItemsElementName.Add(choiceType.ConvertEnum<ItemsChoiceType>());
            }
            return lineRed;
        }

        private static TaxItemType MapVatItemType2Vm(object vatItem, decimal taxableAmount)
        {
            if (vatItem == null)
                return null;
            if (vatItem.GetType() != typeof(SRC.TaxRateType))
            {
                string taxExemption = (string)vatItem;
                TaxItemType taxItem = new TaxItemType()
                {
                    TaxableAmount = taxableAmount,
                    TaxPercent = new TaxPercentType()
                    {
                        TaxCategoryCode = PlugInSettings.VStBefreitCode,
                        Value = 0
                    },
                    Comment = taxExemption
                };
                return taxItem;
            }
            SRC.TaxRateType vATRate = (SRC.TaxRateType)vatItem;
            TaxItemType taxItemVat = new TaxItemType()
            {
                TaxableAmount = taxableAmount,
                TaxPercent = new TaxPercentType()
                {
                    Value = vATRate.Value,
                    TaxCategoryCode = PlugInSettings.Default.GetValueFromPercent(vATRate.Value).Code
                },
                TaxAmount = (taxableAmount * vATRate.Value / 100).FixedFraction(2)
            };
            //Log.DumpToLog(CallerInfo.Create(), vATRate);
            //Log.DumpToLog(CallerInfo.Create(), taxItemVat);
            return taxItemVat;
        }

        private static List<ArticleNumberType> GetArtikelList(SRC.ArticleNumberType[] srcArticle)
        {
            List<ArticleNumberType> artNrList = new List<ArticleNumberType>();
            if (srcArticle == null)
            {
                return artNrList;
            }
            foreach (SRC.ArticleNumberType articleNumberType in srcArticle)
            {
                ArticleNumberType art = new ArticleNumberType
                {
                    Value = articleNumberType.Text[0],
                    ArticleNumberType1Specified = articleNumberType.ArticleNumberType1Specified,
                    ArticleNumberType1 = articleNumberType.ArticleNumberType1.ConvertEnum<ArticleNumberTypeType>()
                };
                artNrList.Add(art);

            }
            return artNrList;
        }
        private static List<AddressIdentifierType> GetAddressIdentifier(SRC.AddressIdentifierType addressIdentifier)
        {
            if (addressIdentifier == null)
            {
                return null;

            }

            List<AddressIdentifierType> adrOutList = new List<AddressIdentifierType>();
            AddressIdentifierType adId = new AddressIdentifierType();

            if (addressIdentifier.AddressIdentifierType1Specified)
            {
                adId.AddressIdentifierType1 = addressIdentifier.AddressIdentifierType1.ConvertEnum<AddressIdentifierTypeType>();
                adId.Value = addressIdentifier.Text[0];

            }
            adId.Value = addressIdentifier.Text[0];
            adrOutList.Add(adId);

            return adrOutList;
        }
        private static List<FurtherIdentificationType> GetFurtherIdentification(SRC.FurtherIdentificationType[] furtherID)
        {
            List<FurtherIdentificationType> fIdList = new List<FurtherIdentificationType>();
            if (furtherID == null)
            {
                return fIdList;
            }

            List<string> supportedIds = Enum.GetNames(typeof(FurtherIdentificationType.SupportedIds)).ToList();
            foreach (SRC.FurtherIdentificationType item in furtherID)
            {
                if (supportedIds.Contains(item.IdentificationType))
                {
                    FurtherIdentificationType fId = new FurtherIdentificationType()
                    {
                        IdentificationType = item.IdentificationType,
                        Value = item.Value
                    };
                    fIdList.Add(fId);
                }
            }
            return fIdList;
        }
    }
}


text:
using UnityEngine;
using System;
using LuaInterface;
using SLua;
using System.Collections.Generic;
public class Lua_UnityEngine_RenderingPath : LuaObject {
	static public void reg(IntPtr l) {
		getEnumTable(l,"UnityEngine.RenderingPath");
		addMember(l,0,"VertexLit");
		addMember(l,1,"Forward");
		addMember(l,2,"DeferredLighting");
		addMember(l,3,"DeferredShading");
		addMember(l,-1,"UsePlayerSettings");
		LuaDLL.lua_pop(l, 1);
	}
}


text:
require File.dirname(__FILE__) + '/../fixtures/classes'

ruby_version_is "1.9" do
  describe "Encoding::UndefinedConversionError#destination_encoding_name" do
    before(:each) do
      @exception = EncodingSpecs::UndefinedConversionError.exception
    end

    it "returns a String" do
      @exception.destination_encoding_name.should be_an_instance_of(String)
    end

    it "is equal to the destination encoding name of the object that raised it" do
      @exception.destination_encoding_name.should == "US-ASCII"
    end
  end
end


text:
package jsky.app.ot.gemini.editor.targetComponent.details

import edu.gemini.spModel.target.system.CoordinateParam.Units
import edu.gemini.spModel.target.system.CoordinateTypes.Epoch
import edu.gemini.spModel.target.system.{ConicTarget, ITarget}

final class MpcMinorPlanetDetailEditor extends ConicDetailEditor(ITarget.Tag.MPC_MINOR_PLANET) {
  import NumericPropertySheet.Prop

  lazy val props = NumericPropertySheet[ConicTarget](Some("Orbital Elements"), _.getTarget.asInstanceOf[ConicTarget],
    Prop("EPOCH", "Orbital Element Epoch (JD)",        _.getEpoch.getValue, (t,d) => t.setEpoch(new Epoch(d, Units.JD))),
    Prop("IN",    "Inclination (deg)",                 _.getInclination),
    Prop("OM",    "Longitude of Ascending Node (deg)", _.getANode),
    Prop("W",     "Argument of Perihelion (deg)",      _.getPerihelion),
    Prop("A",     "Semi-major Axis (AU)",              _.getAQ),
    Prop("EC",    "Eccentricity",                      _.getE, _.setE(_)),
    Prop("MA",    "Mean Anomaly (deg)",                _.getLM)
  )

}


text:
package com.github.koraktor.mavanagaiata.mojo;

import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;

import com.github.koraktor.mavanagaiata.git.GitRepositoryException;

/**
 * This goal provides the currently checked out Git branch in the
 * "mavanagaiata.branch" and "mvngit.branch" properties.
 *
 * @author Sebastian Staudt
 * @since 0.1.0
 */
@Mojo(name ="branch",
      defaultPhase = LifecyclePhase.INITIALIZE)
public class GitBranchMojo extends AbstractGitMojo {

    /**
     * Information about the currently checked out Git branch is retrieved
     * using a JGit Repository instance
     *
     * @see org.eclipse.jgit.lib.Repository#getBranch()
     * @throws MavanagaiataMojoException if retrieving information from the Git
     *         repository fails
     */
    public void run() throws MavanagaiataMojoException {
        try {
            this.addProperty("branch", this.repository.getBranch());
        } catch(GitRepositoryException e) {
            throw MavanagaiataMojoException.create("Unable to read Git branch", e);
        }
    }

}


text:
#include "connection/http.h"
#include <halley/support/exception.h>

#include "halley/support/logger.h"
#include "halley/utils/algorithm.h"
#include "halley/utils/utils.h"

using namespace Halley;

#ifdef _MSC_VER
#pragma warning(disable: 6386 6258 6309 6387 4913)
#endif

#if defined(_WIN32) || defined(__linux) || defined(APPLE)
#define HTTP_AVAILABLE
#define BOOST_SYSTEM_NO_DEPRECATED
#include <boost/asio.hpp>
#endif

Bytes HTTP::request(const String& host, const String& path, const String& method, const String& content, const std::map<String, String>& headers)
{
#ifdef HTTP_AVAILABLE
	// Code adapted from http://www.boost.org/doc/libs/1_49_0_beta1/doc/html/boost_asio/example/http/client/sync_client.cpp
	using boost::asio::ip::tcp;
	boost::asio::io_service io_service;

	// Get a list of endpoints corresponding to the server name.
	const auto hostParts = host.split(':');
    tcp::resolver resolver(io_service);
    tcp::resolver::query query(hostParts[0].c_str(), hostParts.size() >= 2 ? hostParts[1] : "http");
    tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);

    // Try each endpoint until we successfully establish a connection.
    tcp::socket socket(io_service);
    boost::asio::connect(socket, endpoint_iterator);

    // Form the request. We specify the "Connection: close" header so that the
    // server will close the socket after transmitting the response. This will
    // allow us to treat all data up until the EOF as the content.
    boost::asio::streambuf requestBuffer;
    //std::ostream request(&requestBuffer);
	std::stringstream request;
    request << method.c_str() << " " << path.c_str() << " HTTP/1.1\r\n";
    request << "Host: " << hostParts[0].c_str() << "\r\n";
	for (const auto& header: headers) {
		request << header.first.c_str() << ": " << header.second.c_str() << "\r\n";
	}
	if (!std_ex::contains(headers, "Accept")) {
		request << "Accept: */*\r\n";
	}
    request << "Connection: close\r\n";
	request << "\r\n";
	if (!content.isEmpty()) {
		request << content;
	}

	//Logger::logDev("Sending:\n\n" + request.str());
	std::ostream reqStream(&requestBuffer);
	reqStream << request.str();

	// Send the request.
	write(socket, requestBuffer);

	// Read the reply
	Bytes result;
	size_t pos = 0;
	while (true) {
		std::array<char, 2048> buf;
		boost::system::error_code error;

		size_t len = socket.read_some(boost::asio::buffer(buf), error);
		if (error == boost::asio::error::eof) {
			break;
		} else if (error) {
			throw Exception("Error reading from socket: " + error.message(), HalleyExceptions::Network);
		}

		result.resize(result.size() + len);
		memcpy(&result[pos], &buf[0], len);
		pos += len;
	}
	return result;

#else
	return Bytes();
#endif
}


text:
<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="HandheldFriendly" content="true" />
  <link rel="shortcut icon" href="https://www.epa.gov/sites/all/themes/epa/favicon.ico" type="image/vnd.microsoft.icon" />
  <meta name="MobileOptimized" content="width" />
  <meta http-equiv="cleartype" content="on" />
  <meta http-equiv="ImageToolbar" content="false" />
  <meta name="viewport" content="width=device-width" />
  <meta name="version" content="20161218" />

  <meta name="DC.description" content="" />
  <meta name="DC.title" content="" />
  <title>
  Sustainable Sanitation Solutions for Low-Income Urban Households|

  Research Project Database | Grantee Research Project | ORD | US EPA</title>

  <meta name="keywords" content="" />
  <link rel="shortlink" href="" />
  <link rel="canonical" href="" />
  <meta name="DC.creator" content="" />
  <meta name="DC.language" content="en" />
  <meta name="DC.Subject.epachannel" content="" />
  <meta name="DC.type" content="" />
  <meta name="DC.date.created" content="" />
  <meta name="DC.date.modified" content="2014-10-15" />

  <link type="text/css" rel="stylesheet" href="https://www.epa.gov/misc/ui/jquery.ui.autocomplete.css" media="all" />
  <link type="text/css" rel="stylesheet" href="https://www.epa.gov/sites/all/themes/epa/css/lib/jquery.ui.theme.css" media="all" />
  <link type="text/css" rel="stylesheet" href="https://www.epa.gov/sites/all/libraries/template2/s.css" media="all" />

	<link rel="alternate" type="application/atom+xml" title="EPA.gov All Press Releases" href="https://www.epa.gov/newsreleases/search/rss" />
	<link rel="alternate" type="application/atom+xml" title="EPA.gov Headquarters Press Releases" href="https://www.epa.gov/newsreleases/search/rss/field_press_office/headquarters" />
	<link rel="alternate" type="application/atom+xml" title="Greenversations, EPA's Blog" href="https://blog.epa.gov/blog/feed/" />

Jump to main content

  <hgroup class="site-name-and-slogan">

US EPA

United States Environmental Protection Agency

  </hgroup>
  <form class="epa-search" method="get" action="https://search.epa.gov/epasearch/epasearch">
    Search
    <input class="form-text" placeholder="Search EPA.gov" name="querytext" id="search-box" value=""/>
    <button class="epa-search-button" id="search-button" type="submit" title="Search">Search</button>
    <input type="hidden" name="fld" value="" />
    <input type="hidden" name="areaname" value="" />
    <input type="hidden" name="areacontacts" value="" />
    <input type="hidden" name="areasearchurl" value="" />
    <input type="hidden" name="typeofsearch" value="epa" />
    <input type="hidden" name="result_template" value="2col.ftl" />
    <input type="hidden" name="filter" value="sample4filt.hts" />
  </form>

Contact Us

Related Information

Research Grants

P3: Student Design Competition

Research Fellowships

Small Business Innovation Research (SBIR)

Grantee Research Project Results Search

      Sustainable Sanitation Solutions for Low-Income Urban Households

    EPA Grant Number: SU835718

    Title: Sustainable Sanitation Solutions for Low-Income Urban Households

    Investigators:
     Davis, Jennifer
        ,  Escallón, Maria Fernanda
        ,  Moua, Gao Nou
        ,  Russel, Kory C
        ,  Tilmans, Sebastien H

    Institution:

      Stanford University

    	EPA Project Officer:

           Lank, Gregory

        Phase: I

      Project Period:
      August 15, 2014 through
        August 14, 2015

        Project Amount:

          $14,996

      RFA:
      P3 Awards: A National Student Design Competition for Sustainability Focusing on People, Prosperity and the Planet (2014)

        		RFA Text |
          Recipients Lists

      Research Category:

          Pollution Prevention/Sustainable Development
          ,
          P3 Challenge Area - Water
          ,
          P3 Awards
          ,
          Sustainability

Objective:

	Many residents of dense urban communities in developing countries lack access to safe sanitation facilities. In order to meet basic needs, residents are forced to choose between crowded public toilets, open defecation, or private latrines that are expensive to build and maintain. Narrow alleys prevent vehicle access, such that pit latrines must be emptied manually. These conditions increase the risk of fecal contamination of drinking water sources and the urban environment.

	To address the challenges of density, poverty, limited water access, and the often informal status of these communities, we are developing a portable waterless, urine-diverting household toilet with sealable, removable and reusable cartridges that enables safe removal of human waste. The toilet enables a full-cycle service model wherein cartridges are removed and delivered to resource recovery sites without environmental exposure or spills. The cartridges can then be cleaned for reuse, while the waste can be converted into valuable end-products like compost, energy, or biochar, that can help finance the service.

	During testing of our toilet and service in Cap Haitien, Haiti, we determined that a critical missing element of our design is a “flushing” mechanism. Such a device would add a standard dose of dry cover material (such as lime, sawdust, ash, or crushed peanut shells) following each use of the toilet, which will help maintain hygienic conditions and provide a more pleasant user experience.

Approach:

	Our design emphasizes a sanitation service (portable toilet rental with regular emptying), rather than an asset (a conventional pit latrine), as the value proposition for households. Just as mobile phone companies have revolutionized telecommunications services by bundling capital costs within service plans, our model allows subscribers to improve their sanitation services immediately and radically with minimal up-front cost. The proposed project will enhance the value of this service to users, by responded to their expressed preferences for an experience that more closely mimics that of a water-flush toilet.

Expected Results:

The expected outcome is a low-cost, dry material dispensing mechanism for waterless toilets, adaptable to other dry toilets in use globally and to ecosan toilets in remote areas in the United States. The system helps reduce contamination of the environment and drinking water by isolating feces and facilitating their transport to waste management facilities.

Supplemental Keywords:

      sanitation, waterless toilets, slums, urbanization, sustainable infrastructure

Top of Page

 The perspectives, information and conclusions conveyed in research project abstracts, progress reports, final reports, journal abstracts and journal publications convey the viewpoints of the principal investigator and may not represent the views and policies of ORD and EPA.  Conclusions drawn by the principal investigators have not been reviewed by the Agency.

Main menu

Environmental Topics

Laws & Regulations

About EPA

Discover.

Accessibility

EPA Administrator

Budget & Performance

Contracting

Grants

No FEAR Act Data

Privacy and Security

Connect.

Data.gov

Inspector General

Jobs

Newsroom

Open Government

Regulations.gov

Subscribe

USA.gov

White House

Ask.

Contact Us

Hotlines

FOIA Requests

Frequent Questions

Follow.

Facebook

Twitter

YouTube

Flickr

Instagram

Last updated on Wednesday, October 15, 2014


text:
package slb

import (
	"fmt"
	"time"

	"github.com/denverdino/aliyungo/common"
	"github.com/denverdino/aliyungo/util"
)

type AddressType string

const (
	InternetAddressType = AddressType("internet")
	IntranetAddressType = AddressType("intranet")
)

type InternetChargeType string

const (
	PayByBandwidth = InternetChargeType("paybybandwidth")
	PayByTraffic   = InternetChargeType("paybytraffic")
)

type AddressIPVersionType string

const (
	IPv4 = AddressIPVersionType("ipv4")
	IPv6 = AddressIPVersionType("ipv6")
)

type LoadBalancerSpecType string

const (
	S1Small  = "slb.s1.small"
	S2Small  = "slb.s2.small"
	S2Medium = "slb.s2.medium"
	S3Small  = "slb.s3.small"
	S3Medium = "slb.s3.medium"
	S3Large  = "slb.s3.large"
)

type ModificationProtectionType string

const (
	NonProtection     = ModificationProtectionType("NonProtection")
	ConsoleProtection = ModificationProtectionType("ConsoleProtection")
)

type CreateLoadBalancerArgs struct {
	RegionId                     common.Region
	LoadBalancerName             string
	AddressType                  AddressType
	VSwitchId                    string
	InternetChargeType           InternetChargeType
	Bandwidth                    int
	ClientToken                  string
	MasterZoneId                 string
	SlaveZoneId                  string
	LoadBalancerSpec             LoadBalancerSpecType
	AddressIPVersion             AddressIPVersionType
	DeleteProtection             FlagType
	ModificationProtectionStatus ModificationProtectionType
	ModificationProtectionReason string
	ResourceGroupId              string
}

type CreateLoadBalancerResponse struct {
	common.Response
	LoadBalancerId   string
	Address          string
	NetworkType      string
	VpcId            string
	VSwitchId        string
	LoadBalancerName string
	MasterZoneId     string
	SlaveZoneId      string
	AddressIPVersion AddressIPVersionType
}

// CreateLoadBalancer create loadbalancer
//
// You can read doc at http://docs.aliyun.com/#/pub/slb/api-reference/api-related-loadbalancer&CreateLoadBalancer
func (client *Client) CreateLoadBalancer(args *CreateLoadBalancerArgs) (response *CreateLoadBalancerResponse, err error) {
	response = &CreateLoadBalancerResponse{}
	err = client.Invoke("CreateLoadBalancer", args, response)
	if err != nil {
		return nil, err
	}
	return response, err
}

type DeleteLoadBalancerArgs struct {
	LoadBalancerId string
}

type DeleteLoadBalancerResponse struct {
	common.Response
}

// DeleteLoadBalancer delete loadbalancer
//
// You can read doc at http://docs.aliyun.com/#/pub/slb/api-reference/api-related-loadbalancer&DeleteLoadBalancer
func (client *Client) DeleteLoadBalancer(loadBalancerId string) (err error) {
	args := &DeleteLoadBalancerArgs{
		LoadBalancerId: loadBalancerId,
	}
	response := &DeleteLoadBalancerResponse{}
	err = client.Invoke("DeleteLoadBalancer", args, response)
	return err
}

type ModifyLoadBalancerInternetSpecArgs struct {
	LoadBalancerId     string
	InternetChargeType InternetChargeType
	Bandwidth          int
}

type ModifyLoadBalancerInternetSpecResponse struct {
	common.Response
}

// ModifyLoadBalancerInternetSpec Modify loadbalancer internet spec
//
// You can read doc at http://docs.aliyun.com/#/pub/slb/api-reference/api-related-loadbalancer&ModifyLoadBalancerInternetSpec

func (client *Client) ModifyLoadBalancerInternetSpec(args *ModifyLoadBalancerInternetSpecArgs) (err error) {
	response := &ModifyLoadBalancerInternetSpecResponse{}
	err = client.Invoke("ModifyLoadBalancerInternetSpec", args, response)
	return err
}

type ModifyLoadBalancerInstanceSpecArgs struct {
	RegionId         common.Region
	LoadBalancerId   string
	LoadBalancerSpec LoadBalancerSpecType
}

// ModifyLoadBalancerInstanceSpec Modify loadbalancer instance spec
//
// You can read doc at https://help.aliyun.com/document_detail/53360.html

func (client *Client) ModifyLoadBalancerInstanceSpec(args *ModifyLoadBalancerInstanceSpecArgs) (err error) {
	response := &common.Response{}
	err = client.Invoke("ModifyLoadBalancerInstanceSpec", args, response)
	return err
}

type Status string

const InactiveStatus = Status("inactive")
const ActiveStatus = Status("active")
const LockedStatus = Status("locked")

type SetLoadBalancerStatusArgs struct {
	LoadBalancerId     string
	LoadBalancerStatus Status
}

type SetLoadBalancerStatusResponse struct {
	common.Response
}

// SetLoadBalancerStatus Set loadbalancer status
//
// You can read doc at http://docs.aliyun.com/#/pub/slb/api-reference/api-related-loadbalancer&SetLoadBalancerStatus

func (client *Client) SetLoadBalancerStatus(loadBalancerId string, status Status) (err error) {
	args := &SetLoadBalancerStatusArgs{
		LoadBalancerId:     loadBalancerId,
		LoadBalancerStatus: status,
	}
	response := &SetLoadBalancerStatusResponse{}
	err = client.Invoke("SetLoadBalancerStatus", args, response)
	return err
}

type SetLoadBalancerNameArgs struct {
	LoadBalancerId   string
	LoadBalancerName string
}

type SetLoadBalancerNameResponse struct {
	common.Response
}

// SetLoadBalancerName Set loadbalancer name
//
// You can read doc at http://docs.aliyun.com/#/pub/slb/api-reference/api-related-loadbalancer&SetLoadBalancerName

func (client *Client) SetLoadBalancerName(loadBalancerId string, name string) (err error) {
	args := &SetLoadBalancerNameArgs{
		LoadBalancerId:   loadBalancerId,
		LoadBalancerName: name,
	}
	response := &SetLoadBalancerNameResponse{}
	err = client.Invoke("SetLoadBalancerName", args, response)
	return err
}

type DescribeLoadBalancersArgs struct {
	RegionId           common.Region
	LoadBalancerId     string
	LoadBalancerName   string
	AddressType        AddressType
	NetworkType        string
	VpcId              string
	VSwitchId          string
	Address            string
	InternetChargeType InternetChargeType
	ServerId           string
	Tags               string
}

type ListenerPortAndProtocolType struct {
	ListenerPort     int
	ListenerProtocol string
	Description      string
}

type BackendServerType struct {
	ServerId string
	Weight   int
	Type     string
}

type ServiceManagedModeType string

const (
	Managed           = ServiceManagedModeType("Managed")
	Unmanaged         = ServiceManagedModeType("Unmanaged")
	DependencyManaged = ServiceManagedModeType("DependencyManaged")
)

type LoadBalancerType struct {
	LoadBalancerId               string
	ResourceGroupId              string
	LoadBalancerName             string
	LoadBalancerStatus           string
	Address                      string
	RegionId                     common.Region
	RegionIdAlias                string
	AddressType                  AddressType
	VSwitchId                    string
	VpcId                        string
	NetworkType                  string
	Bandwidth                    int
	InternetChargeType           InternetChargeType
	CreateTime                   string //Why not ISO 6801
	CreateTimeStamp              util.ISO6801Time
	DeleteProtection             FlagType
	ModificationProtectionStatus ModificationProtectionType
	ModificationProtectionReason string
	ListenerPorts                struct {
		ListenerPort []int
	}
	ListenerPortsAndProtocol struct {
		ListenerPortAndProtocol []ListenerPortAndProtocolType
	}
	BackendServers struct {
		BackendServer []BackendServerType
	}
	LoadBalancerSpec   LoadBalancerSpecType
	MasterZoneId       string
	SlaveZoneId        string
	AddressIPVersion   AddressIPVersionType
	ServiceManagedMode ServiceManagedModeType
}

type DescribeLoadBalancersResponse struct {
	common.Response
	LoadBalancers struct {
		LoadBalancer []LoadBalancerType
	}
}

// DescribeLoadBalancers Describe loadbalancers
//
// You can read doc at http://docs.aliyun.com/#/pub/slb/api-reference/api-related-loadbalancer&DescribeLoadBalancers

func (client *Client) DescribeLoadBalancers(args *DescribeLoadBalancersArgs) (loadBalancers []LoadBalancerType, err error) {
	response := &DescribeLoadBalancersResponse{}
	err = client.Invoke("DescribeLoadBalancers", args, response)
	if err != nil {
		return nil, err
	}
	return response.LoadBalancers.LoadBalancer, err
}

type DescribeLoadBalancerAttributeArgs struct {
	LoadBalancerId string
}

type DescribeLoadBalancerAttributeResponse struct {
	common.Response
	LoadBalancerType
}

// DescribeLoadBalancerAttribute Describe loadbalancer attribute
//
// You can read doc at http://docs.aliyun.com/#/pub/slb/api-reference/api-related-loadbalancer&DescribeLoadBalancerAttribute

func (client *Client) DescribeLoadBalancerAttribute(loadBalancerId string) (loadBalancer *LoadBalancerType, err error) {
	args := &DescribeLoadBalancersArgs{
		LoadBalancerId: loadBalancerId,
	}
	response := &DescribeLoadBalancerAttributeResponse{}
	err = client.Invoke("DescribeLoadBalancerAttribute", args, response)
	if err != nil {
		return nil, err
	}
	return &response.LoadBalancerType, err
}

type NewDescribeLoadBalancerAttributeArgs struct {
	LoadBalancerId string
	RegionId       common.Region
	MasterZoneId   string
	SlaveZoneId    string
}

// New DescribeLoadBalancerAttribute to describe loadbalancer attribute using regionId avoiding to get not found error
//
// You can read doc at https://www.alibabacloud.com/help/doc-detail/27583.htm

func (client *Client) NewDescribeLoadBalancerAttribute(args *NewDescribeLoadBalancerAttributeArgs) (loadBalancer *LoadBalancerType, err error) {

	response := &DescribeLoadBalancerAttributeResponse{}
	err = client.Invoke("DescribeLoadBalancerAttribute", args, response)
	if err != nil {
		return nil, err
	}
	return &response.LoadBalancerType, err
}

// WaitForListener waits for listener to given status
func (client *Client) WaitForLoadBalancerAsyn(loadBalancerId string, status Status, timeout int) error {
	if timeout <= 0 {
		timeout = DefaultTimeout
	}

	for {
		lb, err := client.DescribeLoadBalancerAttribute(loadBalancerId)

		e, _ := err.(*common.Error)
		if e != nil {
			if e.StatusCode == 404 || e.Code == "InvalidLoadBalancerId.NotFound" {
				continue
			}
			return err
		} else if lb != nil && Status(lb.LoadBalancerStatus) == status {
			//TODO
			break
		}
		timeout = timeout - DefaultWaitForInterval
		if timeout <= 0 {
			return common.GetClientErrorFromString(fmt.Sprintf("Timeout waitting for load balacner %#v", status))
		}
		time.Sleep(DefaultWaitForInterval * time.Second)
	}
	return nil
}

type SetLoadBalancerDeleteProtectionArgs struct {
	LoadBalancerId   string
	DeleteProtection FlagType
	RegionId         common.Region
}

type SetLoadBalancerDeleteProtectionResponse struct {
	common.Response
}

// SetLoadBalancerDeleteProtection loadbalancer delete protection
//
// You can read doc at https://help.aliyun.com/document_detail/122674.html?spm=a2c4g.11186623.6.720.694f4265hwOdXQ
func (client *Client) SetLoadBalancerDeleteProtection(args *SetLoadBalancerDeleteProtectionArgs) (err error) {
	response := &SetLoadBalancerDeleteProtectionResponse{}
	err = client.Invoke("SetLoadBalancerDeleteProtection", args, response)
	return err
}

type SetLoadBalancerModificationProtectionArgs struct {
	RegionId                     common.Region
	LoadBalancerId               string
	ModificationProtectionStatus ModificationProtectionType
	ModificationProtectionReason string
}

type SetLoadBalancerModificationProtectionResponse struct {
	common.Response
}

func (client *Client) SetLoadBalancerModificationProtection(args *SetLoadBalancerModificationProtectionArgs) (err error) {
	response := &SetLoadBalancerModificationProtectionResponse{}
	err = client.Invoke("SetLoadBalancerModificationProtection", args, response)
	return err
}

type ManagedResourceType string

const (
	ManagedLoadBalancer           = ManagedResourceType("LoadBalancer")
	ManagedTls                    = ManagedResourceType("Tls")
	ManagedVServerGroup           = ManagedResourceType("VServerGroup")
	ManagedMasterSlaveServerGroup = ManagedResourceType("MasterSlaveServerGroup")
	ManagedAcl                    = ManagedResourceType("Acl")
	ManagedListener               = ManagedResourceType("Listener")
	ManagedRule                   = ManagedResourceType("Rule")
	ManagedAppRule                = ManagedResourceType("AppRule")
	ManagedDomainExtension        = ManagedResourceType("DomainExtension")
)

type ManagedResourceModel struct {
	ResourceId string
	Port       int
	Protocol   string
}

type ServiceManagedControlArgs struct {
	RegionId           common.Region
	ServiceManagedMode ServiceManagedModeType
	ResourceUid        string
	ResourceBid        string
	ResourceType       ManagedResourceType
	Resources          []ManagedResourceModel
}

type ServiceManagedControlResponse struct {
	common.Response
}

//api: https://yuque.antfin-inc.com/docs/share/63b5a2d3-6fb3-4bd7-a50e-c4b385b866fd?#
func (client *Client) ServiceManagedControl(args *ServiceManagedControlArgs) (err error) {
	response := &ServiceManagedControlResponse{}
	err = client.Invoke("ServiceManagedControl", args, response)
	return err
}


text:
package com.blazebit.persistence.integration.view.spring.impl;

import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.core.env.Environment;
import org.springframework.core.type.filter.TypeFilter;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.w3c.dom.Element;

import java.util.Arrays;
import java.util.Collection;

/**
 * @author Moritz Becker
 * @since 1.2.0
 */
public class XmlEntityViewConfigurationSource extends AbstractEntityViewConfigurationSource {

    private static final String BASE_PACKAGE = "base-package";

    private final Element element;
    private final ParserContext context;

    private final Collection<TypeFilter> includeFilters;
    private final Collection<TypeFilter> excludeFilters;

    public XmlEntityViewConfigurationSource(Element element, ParserContext context, Environment environment) {
        super(environment);
        Assert.notNull(element);
        Assert.notNull(context);

        this.element = element;
        this.context = context;

        TypeFilterParser parser = new TypeFilterParser(context.getReaderContext());
        this.includeFilters = parser.parseTypeFilters(element, TypeFilterParser.Type.INCLUDE);
        this.excludeFilters = parser.parseTypeFilters(element, TypeFilterParser.Type.EXCLUDE);
    }

    @Override
    public Iterable<String> getBasePackages() {
        String attribute = element.getAttribute(BASE_PACKAGE);
        return Arrays.asList(StringUtils.delimitedListToStringArray(attribute, ",", " "));
    }

    @Override
    protected Iterable<TypeFilter> getExcludeFilters() {
        return excludeFilters;
    }

    @Override
    protected Iterable<TypeFilter> getIncludeFilters() {
        return includeFilters;
    }
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Royena rugosa E. Mey. ex A. DC.

### Remarks
null


text:
package boot

object Boot {

  type exercise = () => Unit

  def main(args: Array[String]): Unit = {
    println("This is Chapter 4, Handling errors without exeptions")
    runExercise("Exercise 4.8", exercise48)
  }

  private def mean(xs: Seq[Double]): Option[Double] =
    if(xs.isEmpty) None
    else Some(xs.sum / xs.length)

  private def variance(xs: Seq[Double]): Option[Double] =
    mean(xs).flatMap(m => mean(xs.map( x => math.pow(x - m, 2))))

  private def map2[A,B,C](a: Option[A], b: Option[B])(f: (A,B) => C): Option[C] =
    a.flatMap(aa => b map(bb => f(aa, bb)))

  private def exercise41(): Unit = {
    val o = Some(71)
    val n = None

    println("o = Some(71)")
    println("n = None")

    println("o.map(x => x + 1) = " + o.map(x => x + 1))
    println("o.flatMap(x => Some(x + 1)) = " + o.flatMap(x => Some(x + 1)))
    println("o.getOrElse(17) = " + o.getOrElse(17))
    println("n.getOrElse(17) = " + n.getOrElse(17))
  }

  private def exercise42(): Unit = {
    val l = Seq(1.0,2.0,3.0,4.0,5.0)
    println("l = " + l)
    println("variance(l) = " + variance(l))
  }

  private def exercise44(): Unit = {
    val x = List(Some(1), Some(2), Some(3))
    val xs = List(Some(1), Some(2), None)
    println("x = " + x)
    println("Option.sequence(x) = " + Option.sequence(x))
    println("xs = " + xs)
    println("Option.sequence(xs) = " + Option.sequence(xs))
  }

  private def exercise46(): Unit = {
    val right = Right(71)

    println("right = " + right)

    println("right.map(x => x + 1) = " + right.map(x => x + 1))
    println("right.flatMap(x => Either(x + 1)) = " + right.flatMap(x => Right(x + 1)))
  }

  private def exercise48(): Unit = {
    var answer = "The simplest course would be to implement a new data type that lests us keep a list of errors in the data constructor, like so:\n\n"
    answer += "trait Partial[+A,+B]\n"
    answer += "case class Errors[+A](get: Seq[A]) extends Partial[A, Nothing]\n"
    answer += "case class Success[+B](get: B) extends Partial[Nothing, B]"
    println(answer)
  }

  private def runExercise(fName: String, f: exercise): Unit = {
    println(fName)
    f()
  }
}


text:
package io.druid.segment.virtual;

import com.fasterxml.jackson.annotation.JacksonInject;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Preconditions;
import io.druid.math.expr.Expr;
import io.druid.math.expr.ExprMacroTable;
import io.druid.math.expr.Parser;
import io.druid.query.cache.CacheKeyBuilder;
import io.druid.query.dimension.DimensionSpec;
import io.druid.segment.ColumnSelectorFactory;
import io.druid.segment.DimensionSelector;
import io.druid.segment.FloatColumnSelector;
import io.druid.segment.LongColumnSelector;
import io.druid.segment.ObjectColumnSelector;
import io.druid.segment.VirtualColumn;
import io.druid.segment.column.ColumnCapabilities;
import io.druid.segment.column.ColumnCapabilitiesImpl;
import io.druid.segment.column.ValueType;

import java.util.List;
import java.util.Objects;

public class ExpressionVirtualColumn implements VirtualColumn
{
  private final String name;
  private final String expression;
  private final ValueType outputType;
  private final Expr parsedExpression;

  @JsonCreator
  public ExpressionVirtualColumn(
      @JsonProperty("name") String name,
      @JsonProperty("expression") String expression,
      @JsonProperty("outputType") ValueType outputType,
      @JacksonInject ExprMacroTable macroTable
  )
  {
    this.name = Preconditions.checkNotNull(name, "name");
    this.expression = Preconditions.checkNotNull(expression, "expression");
    this.outputType = outputType != null ? outputType : ValueType.FLOAT;
    this.parsedExpression = Parser.parse(expression, macroTable);
  }

  @JsonProperty("name")
  @Override
  public String getOutputName()
  {
    return name;
  }

  @JsonProperty
  public String getExpression()
  {
    return expression;
  }

  @JsonProperty
  public ValueType getOutputType()
  {
    return outputType;
  }

  @Override
  public ObjectColumnSelector makeObjectColumnSelector(
      final String columnName,
      final ColumnSelectorFactory columnSelectorFactory
  )
  {
    final ExpressionObjectSelector baseSelector = ExpressionSelectors.makeObjectColumnSelector(
        columnSelectorFactory,
        parsedExpression
    );
    return new ObjectColumnSelector()
    {
      @Override
      public Class classOfObject()
      {
        return Object.class;
      }

      @Override
      public Object get()
      {
        return baseSelector.get().value();
      }
    };
  }

  @Override
  public DimensionSelector makeDimensionSelector(
      final DimensionSpec dimensionSpec,
      final ColumnSelectorFactory columnSelectorFactory
  )
  {
    return dimensionSpec.decorate(
        ExpressionSelectors.makeDimensionSelector(
            columnSelectorFactory,
            parsedExpression,
            dimensionSpec.getExtractionFn()
        )
    );
  }

  @Override
  public FloatColumnSelector makeFloatColumnSelector(
      final String columnName,
      final ColumnSelectorFactory columnSelectorFactory
  )
  {
    return ExpressionSelectors.makeFloatColumnSelector(columnSelectorFactory, parsedExpression, 0.0f);
  }

  @Override
  public LongColumnSelector makeLongColumnSelector(
      final String columnName,
      final ColumnSelectorFactory columnSelectorFactory
  )
  {
    return ExpressionSelectors.makeLongColumnSelector(columnSelectorFactory, parsedExpression, 0L);
  }

  @Override
  public ColumnCapabilities capabilities(String columnName)
  {
    return new ColumnCapabilitiesImpl().setType(outputType);
  }

  @Override
  public List<String> requiredColumns()
  {
    return Parser.findRequiredBindings(parsedExpression);
  }

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

  @Override
  public byte[] getCacheKey()
  {
    return new CacheKeyBuilder(VirtualColumnCacheHelper.CACHE_TYPE_ID_EXPRESSION)
        .appendString(name)
        .appendString(expression)
        .appendString(outputType.toString())
        .build();
  }

  @Override
  public boolean equals(final Object o)
  {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    final ExpressionVirtualColumn that = (ExpressionVirtualColumn) o;
    return Objects.equals(name, that.name) &&
           Objects.equals(expression, that.expression) &&
           outputType == that.outputType;
  }

  @Override
  public int hashCode()
  {
    return Objects.hash(name, expression, outputType);
  }

  @Override
  public String toString()
  {
    return "ExpressionVirtualColumn{" +
           "name='" + name + '\'' +
           ", expression='" + expression + '\'' +
           ", outputType=" + outputType +
           '}';
  }
}


text:
class CreateExtensionMeta < ActiveRecord::Migration
  def self.up
    create_table 'extension_meta', :force => true do |t|
      t.column 'name', :string
      t.column 'schema_version', :integer, :default => 0
      t.column 'enabled', :boolean, :default => true
    end
  end

  def self.down
    drop_table 'extension_meta'
  end
end


text:
require 'optparse'

class GGIT

  # init
  def initialize(args, stdin)
    parse_commands(args)
  end

  private

  def parse_commands(args)
    @commands = {}
    display_usage("#!Error: No commands") if args.size == 0
    args.each do |arg|
      case arg
        when "is-git"
            `source ./thisfile.sh`
          break
        else
          display_usage("#!Error: Uknown command")
      end
    end
  end

  # this piece of code is the most important
  def set_current_branch
    @current ||= `git branch | grep "*" | awk '{print $2}'`.strip
  end

  def display_usage(msg=nil)
    puts "#{msg}\n\n" unless msg.nil?
    puts "Usage:\n\n"
    puts "g_ is-git?            :Check if is a git repo.\n"
  end
end


text:
.class Landroid/support/v4/view/ViewPropertyAnimatorCompatJB;
.super Ljava/lang/Object;
.source "ViewPropertyAnimatorCompatJB.java"

# direct methods
.method constructor <init>()V
    .locals 0

    .prologue
    .line 22
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

.method public static setListener(Landroid/view/View;Landroid/support/v4/view/ViewPropertyAnimatorListener;)V
    .locals 2
    .param p0, "view"    # Landroid/view/View;
    .param p1, "listener"    # Landroid/support/v4/view/ViewPropertyAnimatorListener;

    .prologue
    const/4 v1, 0x0

    .line 38
    if-eqz p1, :cond_0

    .line 39
    invoke-virtual {p0}, Landroid/view/View;->animate()Landroid/view/ViewPropertyAnimator;

    move-result-object v0

    new-instance v1, Landroid/support/v4/view/ViewPropertyAnimatorCompatJB$1;

    invoke-direct {v1, p1, p0}, Landroid/support/v4/view/ViewPropertyAnimatorCompatJB$1;-><init>(Landroid/support/v4/view/ViewPropertyAnimatorListener;Landroid/view/View;)V

    invoke-virtual {v0, v1}, Landroid/view/ViewPropertyAnimator;->setListener(Landroid/animation/Animator$AnimatorListener;)Landroid/view/ViewPropertyAnimator;

    .line 37
    :goto_0
    return-void

    .line 56
    :cond_0
    invoke-virtual {p0}, Landroid/view/View;->animate()Landroid/view/ViewPropertyAnimator;

    move-result-object v0

    invoke-virtual {v0, v1}, Landroid/view/ViewPropertyAnimator;->setListener(Landroid/animation/Animator$AnimatorListener;)Landroid/view/ViewPropertyAnimator;

    goto :goto_0
.end method

.method public static withEndAction(Landroid/view/View;Ljava/lang/Runnable;)V
    .locals 1
    .param p0, "view"    # Landroid/view/View;
    .param p1, "runnable"    # Ljava/lang/Runnable;

    .prologue
    .line 29
    invoke-virtual {p0}, Landroid/view/View;->animate()Landroid/view/ViewPropertyAnimator;

    move-result-object v0

    invoke-virtual {v0, p1}, Landroid/view/ViewPropertyAnimator;->withEndAction(Ljava/lang/Runnable;)Landroid/view/ViewPropertyAnimator;

    .line 28
    return-void
.end method

.method public static withLayer(Landroid/view/View;)V
    .locals 1
    .param p0, "view"    # Landroid/view/View;

    .prologue
    .line 33
    invoke-virtual {p0}, Landroid/view/View;->animate()Landroid/view/ViewPropertyAnimator;

    move-result-object v0

    invoke-virtual {v0}, Landroid/view/ViewPropertyAnimator;->withLayer()Landroid/view/ViewPropertyAnimator;

    .line 32
    return-void
.end method

.method public static withStartAction(Landroid/view/View;Ljava/lang/Runnable;)V
    .locals 1
    .param p0, "view"    # Landroid/view/View;
    .param p1, "runnable"    # Ljava/lang/Runnable;

    .prologue
    .line 25
    invoke-virtual {p0}, Landroid/view/View;->animate()Landroid/view/ViewPropertyAnimator;

    move-result-object v0

    invoke-virtual {v0, p1}, Landroid/view/ViewPropertyAnimator;->withStartAction(Ljava/lang/Runnable;)Landroid/view/ViewPropertyAnimator;

    .line 24
    return-void
.end method


text:
namespace Ifa.Configuration.Fluentlty
{
    public class IfaConfigurationSetup
    {
        private int _itemsPerPage;
        private int _window;
        private int _right;
        private int _left;

        public IfaConfigurationSetup ItemsPerPage(int itemsPerPage)
        {
            _itemsPerPage = itemsPerPage;
            return this;
        }

        public IfaConfigurationSetup Window(int window)
        {
            _window = window;
            return this;
        }

        public IfaConfigurationSetup Right(int right)
        {
            _right = right;
            return this;
        }

        public IfaConfigurationSetup Left(int left)
        {
            _left = left;
            return this;
        }

        internal IfaConfiguration Build()
        {
            return new IfaConfiguration
                       {
                           ItemsPerPage = _itemsPerPage,
                           Left = _left,
                           Right = _right,
                           Window = _window
                       };
        }
    }
}


text:
package org.elasticsearch.search.aggregations.bucket.filters;

import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.indices.query.IndicesQueriesRegistry;
import org.elasticsearch.search.aggregations.Aggregator;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 *
 */
public class FiltersParser implements Aggregator.Parser {

    public static final ParseField FILTERS_FIELD = new ParseField("filters");
    public static final ParseField OTHER_BUCKET_FIELD = new ParseField("other_bucket");
    public static final ParseField OTHER_BUCKET_KEY_FIELD = new ParseField("other_bucket_key");
    private final IndicesQueriesRegistry queriesRegistry;

    @Inject
    public FiltersParser(IndicesQueriesRegistry queriesRegistry) {
        this.queriesRegistry = queriesRegistry;
    }

    @Override
    public String type() {
        return InternalFilters.TYPE.name();
    }

    @Override
    public FiltersAggregatorBuilder parse(String aggregationName, XContentParser parser, QueryParseContext context)
            throws IOException {

        List<FiltersAggregator.KeyedFilter> keyedFilters = null;
        List<QueryBuilder<?>> nonKeyedFilters = null;

        XContentParser.Token token = null;
        String currentFieldName = null;
        String otherBucketKey = null;
        Boolean otherBucket = false;
        while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
            if (token == XContentParser.Token.FIELD_NAME) {
                currentFieldName = parser.currentName();
            } else if (token == XContentParser.Token.VALUE_BOOLEAN) {
                if (context.parseFieldMatcher().match(currentFieldName, OTHER_BUCKET_FIELD)) {
                    otherBucket = parser.booleanValue();
                } else {
                    throw new ParsingException(parser.getTokenLocation(),
                            "Unknown key for a " + token + " in [" + aggregationName + "]: [" + currentFieldName + "].");
                }
            } else if (token == XContentParser.Token.VALUE_STRING) {
                if (context.parseFieldMatcher().match(currentFieldName, OTHER_BUCKET_KEY_FIELD)) {
                    otherBucketKey = parser.text();
                } else {
                    throw new ParsingException(parser.getTokenLocation(),
                            "Unknown key for a " + token + " in [" + aggregationName + "]: [" + currentFieldName + "].");
                }
            } else if (token == XContentParser.Token.START_OBJECT) {
                if (context.parseFieldMatcher().match(currentFieldName, FILTERS_FIELD)) {
                    keyedFilters = new ArrayList<>();
                    String key = null;
                    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
                        if (token == XContentParser.Token.FIELD_NAME) {
                            key = parser.currentName();
                        } else {
                            QueryParseContext queryParseContext = new QueryParseContext(queriesRegistry);
                            queryParseContext.reset(parser);
                            queryParseContext.parseFieldMatcher(context.parseFieldMatcher());
                            QueryBuilder<?> filter = queryParseContext.parseInnerQueryBuilder();
                            keyedFilters
                                    .add(new FiltersAggregator.KeyedFilter(key, filter == null ? QueryBuilders.matchAllQuery() : filter));
                        }
                    }
                } else {
                    throw new ParsingException(parser.getTokenLocation(),
                            "Unknown key for a " + token + " in [" + aggregationName + "]: [" + currentFieldName + "].");
                }
            } else if (token == XContentParser.Token.START_ARRAY) {
                if (context.parseFieldMatcher().match(currentFieldName, FILTERS_FIELD)) {
                    nonKeyedFilters = new ArrayList<>();
                    while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
                        QueryParseContext queryParseContext = new QueryParseContext(queriesRegistry);
                        queryParseContext.reset(parser);
                        queryParseContext.parseFieldMatcher(context.parseFieldMatcher());
                        QueryBuilder<?> filter = queryParseContext.parseInnerQueryBuilder();
                        nonKeyedFilters.add(filter == null ? QueryBuilders.matchAllQuery() : filter);
                    }
                } else {
                    throw new ParsingException(parser.getTokenLocation(),
                            "Unknown key for a " + token + " in [" + aggregationName + "]: [" + currentFieldName + "].");
                }
            } else {
                throw new ParsingException(parser.getTokenLocation(),
                        "Unknown key for a " + token + " in [" + aggregationName + "]: [" + currentFieldName + "].");
            }
        }

        if (otherBucket && otherBucketKey == null) {
            otherBucketKey = "_other_";
        }

        FiltersAggregatorBuilder factory;
        if (keyedFilters != null) {
            factory = new FiltersAggregatorBuilder(aggregationName,
                    keyedFilters.toArray(new FiltersAggregator.KeyedFilter[keyedFilters.size()]));
        } else {
            factory = new FiltersAggregatorBuilder(aggregationName,
                    nonKeyedFilters.toArray(new QueryBuilder<?>[nonKeyedFilters.size()]));
        }
        if (otherBucket != null) {
            factory.otherBucket(otherBucket);
        }
        if (otherBucketKey != null) {
            factory.otherBucketKey(otherBucketKey);
        }
        return factory;
    }

    @Override
    public FiltersAggregatorBuilder getFactoryPrototypes() {
        return FiltersAggregatorBuilder.PROTOTYPE;
    }

}


text:
#include <aws/glue/model/DeleteColumnStatisticsForTableResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>

#include <utility>

using namespace Aws::Glue::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;

DeleteColumnStatisticsForTableResult::DeleteColumnStatisticsForTableResult()
{
}

DeleteColumnStatisticsForTableResult::DeleteColumnStatisticsForTableResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  *this = result;
}

DeleteColumnStatisticsForTableResult& DeleteColumnStatisticsForTableResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  AWS_UNREFERENCED_PARAM(result);

  return *this;
}


text:
@interface LXHTwoWaterWaveView ()
{
    UIColor *_waterColor1;
    UIColor *_waterColor2;

    float _currentLinePointY1;
    float _currentLinePointY2;

    float a;
    float b;

    BOOL flag;
}

@end

@implementation LXHTwoWaterWaveView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {

        [self setBackgroundColor:[UIColor clearColor]];

        a = 1.5;
        b = 0;
        flag = NO;

        _waterColor1 = [UIColor redColor];
        _waterColor2 = [UIColor orangeColor];
        _currentLinePointY1 = 330;
        _currentLinePointY2 = 340;

        [NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:@selector(animateWave) userInfo:nil repeats:YES];

    }
    return self;
}

-(void)animateWave
{
    if (flag) {
        a += 0.01;
    }else{
        a -= 0.01;
    }

    if (a <= 1) {
        flag = YES;
    }

    if (a >= 1.5) {
        flag = NO;
    }

    b += 0.1;

    [self setNeedsDisplay];
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    //第一条带上面线的水纹
    CGContextRef context1 = UIGraphicsGetCurrentContext();
    CGMutablePathRef path1 = CGPathCreateMutable();

    //画水
    CGContextSetLineWidth(context1, 5);
    CGContextSetFillColorWithColor(context1, [_waterColor1 CGColor]);

    //设置上面线的颜色
    CGContextSetStrokeColorWithColor(context1, [[UIColor blueColor] CGColor]);

    float y1 = _currentLinePointY1;
    CGPathMoveToPoint(path1, NULL, 0, y1);
    for(float x = 0;x <= self.bounds.size.width;x++){
        y1 = a * sin( x / 180 * M_PI + 4 * b / M_PI ) * 5 + _currentLinePointY1;
        CGPathAddLineToPoint(path1, nil, x, y1);
    }
    CGContextAddPath(context1, path1);

    //设置画线,当然也可以不要,根据需求
    CGContextStrokePath(context1);

    CGPathAddLineToPoint(path1, nil, self.bounds.size.width, rect.size.height);
    CGPathAddLineToPoint(path1, nil, 0, rect.size.height);
    CGPathAddLineToPoint(path1, nil, 0, _currentLinePointY1);

    CGContextAddPath(context1, path1);
    CGContextFillPath(context1);
    CGPathRelease(path1);

    //第二条不带上面线的水纹
    CGContextRef context2 = UIGraphicsGetCurrentContext();
    CGMutablePathRef path2 = CGPathCreateMutable();

    //画水
    CGContextSetLineWidth(context1, 1);
    CGContextSetFillColorWithColor(context2, [_waterColor2 CGColor]);

    float y2 = _currentLinePointY2;
    CGPathMoveToPoint(path2, NULL, 0, y2);
    for(float x = 0;x <= self.bounds.size.width;x++){
        y2 = a * cos(x / 180 * M_PI + 4 * b / M_PI ) * 5 + _currentLinePointY2;
        CGPathAddLineToPoint(path2, nil, x, y2);
    }
    CGContextAddPath(context2, path2);
    CGPathAddLineToPoint(path2, nil, self.bounds.size.width, rect.size.height);
    CGPathAddLineToPoint(path2, nil, 0, rect.size.height);
    CGPathAddLineToPoint(path2, nil, 0, _currentLinePointY2);

    CGContextAddPath(context2, path2);
    CGContextFillPath(context2);
    CGPathRelease(path2);

}

@end


text:
git add .
read commitString
git commit -m commitString
git push origin master


text:
"""Const file for Tesla cars."""
CONF_EXPIRATION = "expiration"
CONF_WAKE_ON_START = "enable_wake_on_start"
DOMAIN = "tesla"
DATA_LISTENER = "listener"
DEFAULT_SCAN_INTERVAL = 660
DEFAULT_WAKE_ON_START = False
MIN_SCAN_INTERVAL = 60

PLATFORMS = [
    "sensor",
    "lock",
    "climate",
    "binary_sensor",
    "device_tracker",
    "switch",
]

ICONS = {
    "battery sensor": "mdi:battery",
    "range sensor": "mdi:gauge",
    "mileage sensor": "mdi:counter",
    "parking brake sensor": "mdi:car-brake-parking",
    "charger sensor": "mdi:ev-station",
    "charger switch": "mdi:battery-charging",
    "update switch": "mdi:update",
    "maxrange switch": "mdi:gauge-full",
    "temperature sensor": "mdi:thermometer",
    "location tracker": "mdi:crosshairs-gps",
    "charging rate sensor": "mdi:speedometer",
    "sentry mode switch": "mdi:shield-car",
}


text:
the following packages need to be installed:

# centos
$ sudo yum install autoconf libtool expat-devel texinfo

# macsox
$ brew install autoconf


text:
//
//  UUSegmentPrivate.h
//  Read
//
//  Created by 虞冠群 on 2016/11/15.
//  Copyright © 2016年 Yu Guanqun. All rights reserved.
//

#ifndef UUSegmentPrivate_h
#define UUSegmentPrivate_h

@interface UUSegment ()

@property (nonatomic, assign) CGFloat           fontSize;
@property (nonatomic, assign) CGFloat           fontWeight;

@end

#endif /* UUSegmentPrivate_h */


text:
package com.barbarum.tutorial.code.number;

import com.barbarum.tutorial.code.sort.SelectionAlgorithm;
import com.barbarum.tutorial.code.sort.SortAlgorithm;

import java.util.Arrays;

public class FindNthMaxInArray {

    public int findNthMax(int[] data, int n) {
        if (data == null || data.length == 0 || n < 1) {
            return -1;
        }
        return SelectionAlgorithm.quickSelect(data, n);
    }

    public static void main(String[] args) {
        int data[] = Arrays
                .stream("9 2 4 7 3 7 10".split(" ", -1))
                .mapToInt(Integer::parseInt)
                .toArray();

        SortAlgorithm.quickSort(data);
        System.out.println(Arrays.toString(data));

        System.out.println(new FindNthMaxInArray().findNthMax(data, 3));
    }
}