text:
package com.gdn.venice.client.app.fraud.ui.widgets;

import java.util.HashMap;
import java.util.LinkedHashMap;

import com.gdn.venice.client.app.DataNameTokens;
import com.gdn.venice.client.app.fraud.data.FraudData;
import com.gdn.venice.client.util.Util;
import com.smartgwt.client.data.DSCallback;
import com.smartgwt.client.data.DSRequest;
import com.smartgwt.client.data.DSResponse;
import com.smartgwt.client.data.DataSource;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.DSOperationType;
import com.smartgwt.client.types.SelectionAppearance;
import com.smartgwt.client.types.SelectionStyle;
import com.smartgwt.client.util.BooleanCallback;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.IButton;
import com.smartgwt.client.widgets.ImgButton;
import com.smartgwt.client.widgets.Window;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.events.CloseClickHandler;
import com.smartgwt.client.widgets.events.CloseClientEvent;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.ComboBoxItem;
import com.smartgwt.client.widgets.form.fields.DateTimeItem;
import com.smartgwt.client.widgets.form.fields.HiddenItem;
import com.smartgwt.client.widgets.form.fields.PickerIcon;
import com.smartgwt.client.widgets.form.fields.TextAreaItem;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.form.fields.events.FormItemClickHandler;
import com.smartgwt.client.widgets.form.fields.events.FormItemIconClickEvent;
import com.smartgwt.client.widgets.form.validator.LengthRangeValidator;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.grid.events.FilterEditorSubmitEvent;
import com.smartgwt.client.widgets.grid.events.FilterEditorSubmitHandler;
import com.smartgwt.client.widgets.grid.events.SelectionChangedHandler;
import com.smartgwt.client.widgets.grid.events.SelectionEvent;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.VLayout;
import com.smartgwt.client.widgets.tab.Tab;
import com.smartgwt.client.widgets.toolbar.ToolStrip;
import com.smartgwt.client.widgets.toolbar.ToolStripButton;

/**
 * Widget for Action Log
 *
 * @author Roland
 */

public class FraudCaseManagementActionLogTab extends Tab {
	ToolStripButton addButton;
	ToolStripButton removeButton;
	ListGrid fraudActionLogListGrid;

	Window actionLogDetailWindow;
	DynamicForm actionLogForm = new DynamicForm();
	final HiddenItem partyIdItem = new HiddenItem(DataNameTokens.FRDFRAUDCASEACTIONLOG_PARTYID);
	final TextItem partyItem = new TextItem(DataNameTokens.FRDFRAUDCASEACTIONLOG_PARTYNAME);
	ListGrid partyList;

	public FraudCaseManagementActionLogTab(String title, DataSource actionLogData, final String caseId) {
		super(title);

		addButton = new ToolStripButton();
		addButton.setIcon("[SKIN]/icons/add.png");
		addButton.setTooltip("Add to Action Log");
		addButton.setTitle("Add");

		removeButton = new ToolStripButton();
		removeButton.setIcon("[SKIN]/icons/remove.png");
		removeButton.setTooltip("Remove from Action Log");
		removeButton.setTitle("Remove");

		ToolStrip actionLogToolStrip = new ToolStrip();
		actionLogToolStrip.setWidth100();
		actionLogToolStrip.addButton(addButton);
		actionLogToolStrip.addButton(removeButton);

		ListGridField listGridField[] = Util.getListGridFieldsFromDataSource(actionLogData);
		ListGridField editField = new ListGridField("EDITFIELD", "Edit");
		editField.setWidth(35);
		editField.setCanFilter(false);
		editField.setCanSort(false);
		editField.setAlign(Alignment.CENTER);
        ListGridField finalListGridField[] = {editField, listGridField[0], listGridField[1], listGridField[2], listGridField[3], listGridField[4], listGridField[5]};

		fraudActionLogListGrid = new ListGrid()  {
			@Override
			protected Canvas createRecordComponent(final ListGridRecord record, Integer colNum) {
				if (this.getFieldName(colNum).equalsIgnoreCase("editfield")) {
					ImgButton editImg = new ImgButton();
					editImg.setShowDown(false);
					editImg.setShowRollOver(false);
					editImg.setLayoutAlign(Alignment.CENTER);
					editImg.setSrc("[SKIN]/icons/note_edit.png");
					editImg.setPrompt("Edit Action Log");
					editImg.setHeight(16);
					editImg.setWidth(16);
					editImg.addClickHandler(new ClickHandler() {
						public void onClick(ClickEvent event) {
							HashMap<String, String> params = new HashMap<String, String>();
							params.put(DataNameTokens.FRDFRAUDCASEACTIONLOG_FRAUDACTIONID, record.getAttribute(DataNameTokens.FRDFRAUDCASEACTIONLOG_FRAUDACTIONID));
							actionLogForm.getDataSource().setDefaultParams(params);
							actionLogForm.fetchData(null, new DSCallback() {
								@Override
								public void execute(DSResponse response, Object rawData, DSRequest request) {
									actionLogDetailWindow.setTitle("Edit Action Log");
									actionLogDetailWindow.show();
								}
							});
						}
					});

					return editImg;
				} else {
					return null;
				}
			}
		};

		fraudActionLogListGrid.setDataSource(actionLogData);
		fraudActionLogListGrid.setFields(finalListGridField);
		fraudActionLogListGrid.setAutoFetchData(true);
		fraudActionLogListGrid.setSelectionType(SelectionStyle.SIMPLE);
		fraudActionLogListGrid.setSelectionAppearance(SelectionAppearance.CHECKBOX);
		fraudActionLogListGrid.setShowRowNumbers(true);
		fraudActionLogListGrid.setShowFilterEditor(true);
		fraudActionLogListGrid.setSortField(1);
		fraudActionLogListGrid.setShowRecordComponents(true);
		fraudActionLogListGrid.setShowRecordComponentsByCell(true);

		fraudActionLogListGrid.getField(DataNameTokens.FRDFRAUDCASEACTIONLOG_FRAUDACTIONID).setHidden(true);
		fraudActionLogListGrid.getField(DataNameTokens.FRDFRAUDCASEACTIONLOG_PARTYID).setHidden(true);
		fraudActionLogListGrid.getField(DataNameTokens.FRDFRAUDCASEACTIONLOG_FRAUDACTIONID).setCanEdit(false);
		fraudActionLogListGrid.getField(DataNameTokens.FRDFRAUDCASEACTIONLOG_PARTYID).setCanEdit(false);
		fraudActionLogListGrid.getField(DataNameTokens.FRDFRAUDCASEACTIONLOG_DATETIME).setWidth(120);
		fraudActionLogListGrid.getField(DataNameTokens.FRDFRAUDCASEACTIONLOG_ACTIONTYPE).setWidth(100);
//		fraudActionLogListGrid.getField(DataNameTokens.FRDFRAUDCASEACTIONLOG_DATETIME).setDateFormatter(DateDisplayFormat.TOEUROPEANSHORTDATETIME);

		LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
		map.put("CALL", "Call");
		map.put("MEET", "Meet");
		map.put("SENDDOCUMENT", "Send Document");
		map.put("OTHER", "Other");
		actionLogData.getField(DataNameTokens.FRDFRAUDCASEACTIONLOG_ACTIONTYPE).setValueMap(map);

		VLayout actionLogLayout = new VLayout();
		actionLogLayout.setMembers(actionLogToolStrip, fraudActionLogListGrid);
		setPane(actionLogLayout);
		bindCustomUiHandlers();

		actionLogDetailWindow = buildAddEditWindow(caseId);
	}

	protected void bindCustomUiHandlers() {
		addButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				actionLogDetailWindow.setTitle("Add Action Log");
				actionLogDetailWindow.show();
			}
		});

		removeButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				SC.ask("Are you sure you want to delete this data?", new BooleanCallback() {
					@Override
					public void execute(Boolean value) {
						if(value != null && value) {
							fraudActionLogListGrid.removeSelectedData(new DSCallback() {
								@Override
								public void execute(DSResponse response, Object rawData, DSRequest request) {
									fraudActionLogListGrid.clearCriteria();
									refreshFraudCaseActionLogData();
									SC.say("Data Removed");
								}
							}, null);
						}
					}
				});
			}
		});

		fraudActionLogListGrid.addFilterEditorSubmitHandler(new FilterEditorSubmitHandler() {
			@Override
			public void onFilterEditorSubmit(FilterEditorSubmitEvent event) {
				refreshFraudCaseActionLogData();
			}
		});
	}

	private Window buildAddEditWindow(final String caseId) {
		final Window addEditActionLogWindow = new Window();
		addEditActionLogWindow.setWidth(450);
		addEditActionLogWindow.setHeight(250);
		addEditActionLogWindow.setShowMinimizeButton(false);
		addEditActionLogWindow.setIsModal(true);
		addEditActionLogWindow.setShowModalMask(true);
		addEditActionLogWindow.centerInPage();

		ToolStripButton saveButton = new ToolStripButton();
		saveButton.setIcon("[SKIN]/icons/save.png");
		saveButton.setTooltip("Save Action Log");
		saveButton.setTitle("Save");

		ToolStripButton cancelButton = new ToolStripButton();
		cancelButton.setIcon("[SKIN]/icons/delete.png");
		cancelButton.setTooltip("Cancel Action Log");
		cancelButton.setTitle("Cancel");

		ToolStrip actionLogDetailToolStrip = new ToolStrip();
		actionLogDetailToolStrip.setWidth100();
		actionLogDetailToolStrip.addButton(saveButton);
		actionLogDetailToolStrip.addButton(cancelButton);

		DataSource actionLogDetailData = FraudData.getFraudCaseActionLogDetailData();
		actionLogForm.setDataSource(actionLogDetailData);
		actionLogForm.setUseAllDataSourceFields(false);
		actionLogForm.setNumCols(2);

		HiddenItem caseIdItem = new HiddenItem(DataNameTokens.FRDFRAUDCASEACTIONLOG_SUSPICIONCASEID);
		HiddenItem actionLogIdItem = new HiddenItem(DataNameTokens.FRDFRAUDCASEACTIONLOG_FRAUDACTIONID);

		ComboBoxItem actionType = new ComboBoxItem(DataNameTokens.FRDFRAUDCASEACTIONLOG_ACTIONTYPE);
		LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
		map.put("CALL", "Call");
		map.put("MEET", "Meet");
		map.put("SENDDOCUMENT", "Send Document");
		map.put("OTHER", "Other");
		actionType.setWidth("140");
		actionType.setValueMap(map);

		partyItem.setTitle("Party");
		partyItem.setWidth("200");
        PickerIcon searchPartytPicker = new PickerIcon(PickerIcon.SEARCH, new FormItemClickHandler() {
			public void onFormItemClick(FormItemIconClickEvent event) {
				buildSelectPartyWindow().show();
			}
		});
        partyItem.setIcons(searchPartytPicker);

        DateTimeItem actionLogDate = new DateTimeItem(DataNameTokens.FRDFRAUDCASEACTIONLOG_DATETIME);
//        actionLogDate.setDateFormatter(DateDisplayFormat.TOEUROPEANSHORTDATETIME);
        actionLogDate.setWidth("140");
		TextAreaItem notesItem = new TextAreaItem(DataNameTokens.FRDFRAUDCASEACTIONLOG_NOTES);
		notesItem.setWidth("300");
		notesItem.setHeight(70);

		actionLogForm.setFields(
				caseIdItem,
				actionLogIdItem,
				actionType,
				partyIdItem,
				partyItem,
				actionLogDate,
				notesItem
			);

		//validation
		//length
		LengthRangeValidator lengthRangeValidator = new LengthRangeValidator();
		lengthRangeValidator.setMax(1000);
		actionLogForm.getField(DataNameTokens.FRDFRAUDCASEACTIONLOG_NOTES).setValidators(lengthRangeValidator);

		//required
		actionLogForm.getField(DataNameTokens.FRDFRAUDCASEACTIONLOG_ACTIONTYPE).setRequired(true);
		actionLogForm.getField(DataNameTokens.FRDFRAUDCASEACTIONLOG_PARTYNAME).setRequired(true);
		actionLogForm.getField(DataNameTokens.FRDFRAUDCASEACTIONLOG_DATETIME).setRequired(true);
		actionLogForm.getField(DataNameTokens.FRDFRAUDCASEACTIONLOG_NOTES).setRequired(true);

		VLayout actionLogLayout = new VLayout();
		actionLogLayout.setHeight100();
		actionLogLayout.setWidth100();
		actionLogLayout.setMembers(actionLogDetailToolStrip, actionLogForm);
		addEditActionLogWindow.addItem(actionLogLayout);

		saveButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				SC.ask("Are you sure you want to save this data?", new BooleanCallback() {
					@Override
					public void execute(Boolean value) {
						if(value != null && value ==  true) {
							actionLogForm.getField(DataNameTokens.FRDFRAUDCASEACTIONLOG_SUSPICIONCASEID).setValue(caseId);
							if(addEditActionLogWindow.getTitle().toString().toLowerCase().trim().startsWith("add")){
								actionLogForm.setSaveOperationType(DSOperationType.ADD);
							} else {
								actionLogForm.setSaveOperationType(DSOperationType.UPDATE);
							}

							actionLogForm.saveData(new DSCallback() {
								@Override
								public void execute(DSResponse response, Object rawData, DSRequest request) {
									//Refresh list gird dan hilangkan detail nya
									DSCallback callBack = new DSCallback() {
										@Override
										public void execute(DSResponse response, Object rawData, DSRequest request) {
											fraudActionLogListGrid.setData(response.getData());
											actionLogForm.clearValues();
											addEditActionLogWindow.hide();
											refreshFraudCaseActionLogData();
											if(response.getStatus()==0){
												SC.say("Data Added/Edited");
											}
										}
									};
									fraudActionLogListGrid.getDataSource().fetchData(fraudActionLogListGrid.getFilterEditorCriteria(), callBack);
								}
							});
						}
					}
				});
			}
		});

		cancelButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				actionLogForm.clearValues();
				addEditActionLogWindow.hide();
			}
		});

		addEditActionLogWindow.addCloseClickHandler(new CloseClickHandler() {
			public void onCloseClick(CloseClientEvent event) {
				actionLogForm.clearValues();
				addEditActionLogWindow.hide();
			}
		});

		return addEditActionLogWindow;
	}

	private Window buildSelectPartyWindow() {
		final Window selectPartyWindow = new Window();
		selectPartyWindow.setWidth(500);
		selectPartyWindow.setHeight(350);
		selectPartyWindow.setTitle("Select Party");
		selectPartyWindow.setShowMinimizeButton(false);
		selectPartyWindow.setIsModal(true);
		selectPartyWindow.setShowModalMask(true);
		selectPartyWindow.centerInPage();
		selectPartyWindow.addCloseClickHandler(new CloseClickHandler() {
			public void onCloseClick(CloseClientEvent event) {
				selectPartyWindow.destroy();
			}
		});

		VLayout partyLayout = new VLayout();
		partyLayout.setHeight100();
		partyLayout.setWidth100();

		partyList = new ListGrid();
		partyList.setHeight(300);
		partyList.setSelectionType(SelectionStyle.SIMPLE);
		partyList.setSelectionAppearance(SelectionAppearance.CHECKBOX);
		partyList.setShowFilterEditor(true);
		partyList.setAutoFetchData(true);

		partyList.addFilterEditorSubmitHandler(new FilterEditorSubmitHandler() {
			@Override
			public void onFilterEditorSubmit(FilterEditorSubmitEvent event) {
				DSCallback callBack = new DSCallback() {
					@Override
					public void execute(DSResponse response, Object rawData, DSRequest request) {
						partyList.setData(response.getData());
					}
				};

				partyList.getDataSource().fetchData(partyList.getFilterEditorCriteria(), callBack);
			}
		});

		DataSource partyDataSource = FraudData.getPartyData();
		partyList.setDataSource(partyDataSource);
		partyList.setFields(Util.getListGridFieldsFromDataSource(partyDataSource));
		partyList.getField(DataNameTokens.VENPARTY_PARTYID).setHidden(true);

		HLayout partyButtons = new HLayout(5);
		final IButton buttonSelectParty = new IButton("Select");
		IButton buttonCancel = new IButton("Cancel");

		buttonSelectParty.setDisabled(true);
		buttonSelectParty.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				String partyId = partyList.getSelectedRecord().getAttributeAsString(DataNameTokens.VENPARTY_PARTYID);
				String partyName = partyList.getSelectedRecord().getAttributeAsString(DataNameTokens.VENPARTY_FULLORLEGALNAME);

				partyIdItem.setValue(partyId);
				partyItem.setValue(partyName);

				selectPartyWindow.destroy();
			}
		});
		buttonCancel.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				selectPartyWindow.destroy();
			}
		});
		partyButtons.setAlign(Alignment.CENTER);
		partyButtons.setMembers(buttonSelectParty, buttonCancel);

		partyLayout.setMembers(partyList, partyButtons);
		selectPartyWindow.addItem(partyLayout);

		partyList.addSelectionChangedHandler(new SelectionChangedHandler() {
			@Override
			public void onSelectionChanged(SelectionEvent event) {
				buttonSelectParty.setDisabled(partyList.getSelection().length!=1);
			}
		});

		return selectPartyWindow;
	}

	public void refreshFraudCaseActionLogData() {
		DSCallback callBack = new DSCallback() {
			@Override
			public void execute(DSResponse response, Object rawData, DSRequest request) {
				fraudActionLogListGrid.setData(response.getData());
			}
		};

		fraudActionLogListGrid.getDataSource().fetchData(fraudActionLogListGrid.getFilterEditorCriteria(), callBack);
	}
}


text:
/*
 * This code was generated by
 * ___ _ _ _ _ _    _ ____    ____ ____ _    ____ ____ _  _ ____ ____ ____ ___ __   __
 *  |  | | | | |    | |  | __ |  | |__| | __ | __ |___ |\ | |___ |__/ |__|  | |  | |__/
 *  |  |_|_| | |___ | |__|    |__| |  | |    |__] |___ | \| |___ |  \ |  |  | |__| |  \
 *
 * Twilio - Verify
 * This is the public Twilio REST API.
 *
 * NOTE: This class is auto generated by OpenAPI Generator.
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

package openapi

import (
	"encoding/json"
	"fmt"
	"net/url"
	"strings"

	"github.com/twilio/twilio-go/client"
)

// Optional parameters for the method 'CreateRateLimit'
type CreateRateLimitParams struct {
	// Provides a unique and addressable name to be assigned to this Rate Limit, assigned by the developer, to be optionally used in addition to SID. **This value should not contain PII.**
	UniqueName *string `json:"UniqueName,omitempty"`
	// Description of this Rate Limit
	Description *string `json:"Description,omitempty"`
}

func (params *CreateRateLimitParams) SetUniqueName(UniqueName string) *CreateRateLimitParams {
	params.UniqueName = &UniqueName
	return params
}
func (params *CreateRateLimitParams) SetDescription(Description string) *CreateRateLimitParams {
	params.Description = &Description
	return params
}

// Create a new Rate Limit for a Service
func (c *ApiService) CreateRateLimit(ServiceSid string, params *CreateRateLimitParams) (*VerifyV2RateLimit, error) {
	path := "/v2/Services/{ServiceSid}/RateLimits"
	path = strings.Replace(path, "{"+"ServiceSid"+"}", ServiceSid, -1)

	data := url.Values{}
	headers := make(map[string]interface{})

	if params != nil && params.UniqueName != nil {
		data.Set("UniqueName", *params.UniqueName)
	}
	if params != nil && params.Description != nil {
		data.Set("Description", *params.Description)
	}

	resp, err := c.requestHandler.Post(c.baseURL+path, data, headers)
	if err != nil {
		return nil, err
	}

	defer resp.Body.Close()

	ps := &VerifyV2RateLimit{}
	if err := json.NewDecoder(resp.Body).Decode(ps); err != nil {
		return nil, err
	}

	return ps, err
}

// Delete a specific Rate Limit.
func (c *ApiService) DeleteRateLimit(ServiceSid string, Sid string) error {
	path := "/v2/Services/{ServiceSid}/RateLimits/{Sid}"
	path = strings.Replace(path, "{"+"ServiceSid"+"}", ServiceSid, -1)
	path = strings.Replace(path, "{"+"Sid"+"}", Sid, -1)

	data := url.Values{}
	headers := make(map[string]interface{})

	resp, err := c.requestHandler.Delete(c.baseURL+path, data, headers)
	if err != nil {
		return err
	}

	defer resp.Body.Close()

	return nil
}

// Fetch a specific Rate Limit.
func (c *ApiService) FetchRateLimit(ServiceSid string, Sid string) (*VerifyV2RateLimit, error) {
	path := "/v2/Services/{ServiceSid}/RateLimits/{Sid}"
	path = strings.Replace(path, "{"+"ServiceSid"+"}", ServiceSid, -1)
	path = strings.Replace(path, "{"+"Sid"+"}", Sid, -1)

	data := url.Values{}
	headers := make(map[string]interface{})

	resp, err := c.requestHandler.Get(c.baseURL+path, data, headers)
	if err != nil {
		return nil, err
	}

	defer resp.Body.Close()

	ps := &VerifyV2RateLimit{}
	if err := json.NewDecoder(resp.Body).Decode(ps); err != nil {
		return nil, err
	}

	return ps, err
}

// Optional parameters for the method 'ListRateLimit'
type ListRateLimitParams struct {
	// How many resources to return in each list page. The default is 50, and the maximum is 1000.
	PageSize *int `json:"PageSize,omitempty"`
	// Max number of records to return.
	Limit *int `json:"limit,omitempty"`
}

func (params *ListRateLimitParams) SetPageSize(PageSize int) *ListRateLimitParams {
	params.PageSize = &PageSize
	return params
}
func (params *ListRateLimitParams) SetLimit(Limit int) *ListRateLimitParams {
	params.Limit = &Limit
	return params
}

// Retrieve a single page of RateLimit records from the API. Request is executed immediately.
func (c *ApiService) PageRateLimit(ServiceSid string, params *ListRateLimitParams, pageToken, pageNumber string) (*ListRateLimitResponse, error) {
	path := "/v2/Services/{ServiceSid}/RateLimits"

	path = strings.Replace(path, "{"+"ServiceSid"+"}", ServiceSid, -1)

	data := url.Values{}
	headers := make(map[string]interface{})

	if params != nil && params.PageSize != nil {
		data.Set("PageSize", fmt.Sprint(*params.PageSize))
	}

	if pageToken != "" {
		data.Set("PageToken", pageToken)
	}
	if pageNumber != "" {
		data.Set("Page", pageNumber)
	}

	resp, err := c.requestHandler.Get(c.baseURL+path, data, headers)
	if err != nil {
		return nil, err
	}

	defer resp.Body.Close()

	ps := &ListRateLimitResponse{}
	if err := json.NewDecoder(resp.Body).Decode(ps); err != nil {
		return nil, err
	}

	return ps, err
}

// Lists RateLimit records from the API as a list. Unlike stream, this operation is eager and loads 'limit' records into memory before returning.
func (c *ApiService) ListRateLimit(ServiceSid string, params *ListRateLimitParams) ([]VerifyV2RateLimit, error) {
	response, errors := c.StreamRateLimit(ServiceSid, params)

	records := make([]VerifyV2RateLimit, 0)
	for record := range response {
		records = append(records, record)
	}

	if err := <-errors; err != nil {
		return nil, err
	}

	return records, nil
}

// Streams RateLimit records from the API as a channel stream. This operation lazily loads records as efficiently as possible until the limit is reached.
func (c *ApiService) StreamRateLimit(ServiceSid string, params *ListRateLimitParams) (chan VerifyV2RateLimit, chan error) {
	if params == nil {
		params = &ListRateLimitParams{}
	}
	params.SetPageSize(client.ReadLimits(params.PageSize, params.Limit))

	recordChannel := make(chan VerifyV2RateLimit, 1)
	errorChannel := make(chan error, 1)

	response, err := c.PageRateLimit(ServiceSid, params, "", "")
	if err != nil {
		errorChannel <- err
		close(recordChannel)
		close(errorChannel)
	} else {
		go c.streamRateLimit(response, params, recordChannel, errorChannel)
	}

	return recordChannel, errorChannel
}

func (c *ApiService) streamRateLimit(response *ListRateLimitResponse, params *ListRateLimitParams, recordChannel chan VerifyV2RateLimit, errorChannel chan error) {
	curRecord := 1

	for response != nil {
		responseRecords := response.RateLimits
		for item := range responseRecords {
			recordChannel <- responseRecords[item]
			curRecord += 1
			if params.Limit != nil && *params.Limit < curRecord {
				close(recordChannel)
				close(errorChannel)
				return
			}
		}

		record, err := client.GetNext(c.baseURL, response, c.getNextListRateLimitResponse)
		if err != nil {
			errorChannel <- err
			break
		} else if record == nil {
			break
		}

		response = record.(*ListRateLimitResponse)
	}

	close(recordChannel)
	close(errorChannel)
}

func (c *ApiService) getNextListRateLimitResponse(nextPageUrl string) (interface{}, error) {
	if nextPageUrl == "" {
		return nil, nil
	}
	resp, err := c.requestHandler.Get(nextPageUrl, nil, nil)
	if err != nil {
		return nil, err
	}

	defer resp.Body.Close()

	ps := &ListRateLimitResponse{}
	if err := json.NewDecoder(resp.Body).Decode(ps); err != nil {
		return nil, err
	}
	return ps, nil
}

// Optional parameters for the method 'UpdateRateLimit'
type UpdateRateLimitParams struct {
	// Description of this Rate Limit
	Description *string `json:"Description,omitempty"`
}

func (params *UpdateRateLimitParams) SetDescription(Description string) *UpdateRateLimitParams {
	params.Description = &Description
	return params
}

// Update a specific Rate Limit.
func (c *ApiService) UpdateRateLimit(ServiceSid string, Sid string, params *UpdateRateLimitParams) (*VerifyV2RateLimit, error) {
	path := "/v2/Services/{ServiceSid}/RateLimits/{Sid}"
	path = strings.Replace(path, "{"+"ServiceSid"+"}", ServiceSid, -1)
	path = strings.Replace(path, "{"+"Sid"+"}", Sid, -1)

	data := url.Values{}
	headers := make(map[string]interface{})

	if params != nil && params.Description != nil {
		data.Set("Description", *params.Description)
	}

	resp, err := c.requestHandler.Post(c.baseURL+path, data, headers)
	if err != nil {
		return nil, err
	}

	defer resp.Body.Close()

	ps := &VerifyV2RateLimit{}
	if err := json.NewDecoder(resp.Body).Decode(ps); err != nil {
		return nil, err
	}

	return ps, err
}

redpajama_set_name: RedPajamaGithub


text:
DEBIAN_FRONTEND=noninteractive
export DEBIAN_FRONTEND

echo "*** Installing Serverspec ***"
gem install serverspec


text:
<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">5dp</dimen>
    <dimen name="activity_vertical_margin">5dp</dimen>
    <dimen name="navigation_drawer_width">240dp</dimen>
</resources>


text:
var Effect = require('../Effect');
var overdrive = require('soundbank-overdrive');
var numberInRangeType = require('../types/numberInRange');

module.exports = Effect.extend({

  type: 'overdrive',

  props: {
    wet: ['volumeRange', true, 50],
    dry: ['volumeRange', true, 50],
    preBand: ['preBandRange', true, 50],
    color: ['frequencyRange', true, 800],
    postCut: ['frequencyRange', true, 3000],
    gain: ['volumeRange', true, 100]
  },

  dataTypes: {
    preBandRange: numberInRangeType('preBandRange', 0, 100)
  },

  createNode: function () {

    var input = this.context.createGain();
    var dry = input._dry = this.context.createGain();
    var _overdrive = input._overdrive = overdrive(this.context);
    var output = input._output = this.context.createGain();

    input.connect(dry);
    dry.connect(output);

    input.connect(_overdrive);
    _overdrive.connect(output);

    return this.combineNodes(input, output);
  },

  configureNode: function (node) {

    node._dry.gain.value = this.dry / 100;

    node._overdrive.gain.value = this.wet / 100;
    node._overdrive.preBand.value = this.preBand / 100;
    node._overdrive.color.value = this.color;
    node._overdrive.postCut.value = this.postCut;

    node._output.gain.value = this.gain / 100;
  }
});


text:
package com.navercorp.pinpoint.rpc.packet;

import org.jboss.netty.buffer.ChannelBuffer;

/**
 * @author emeroad
 */
public interface Packet {

    short getPacketType();

    byte[] getPayload();

   ChannelBuffer toBuffer();
}


text:
#include <aws/transcribe/model/ListMedicalTranscriptionJobsRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

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

ListMedicalTranscriptionJobsRequest::ListMedicalTranscriptionJobsRequest() :
    m_status(TranscriptionJobStatus::NOT_SET),
    m_statusHasBeenSet(false),
    m_jobNameContainsHasBeenSet(false),
    m_nextTokenHasBeenSet(false),
    m_maxResults(0),
    m_maxResultsHasBeenSet(false)
{
}

Aws::String ListMedicalTranscriptionJobsRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_statusHasBeenSet)
  {
   payload.WithString("Status", TranscriptionJobStatusMapper::GetNameForTranscriptionJobStatus(m_status));
  }

  if(m_jobNameContainsHasBeenSet)
  {
   payload.WithString("JobNameContains", m_jobNameContains);

  }

  if(m_nextTokenHasBeenSet)
  {
   payload.WithString("NextToken", m_nextToken);

  }

  if(m_maxResultsHasBeenSet)
  {
   payload.WithInteger("MaxResults", m_maxResults);

  }

  return payload.View().WriteReadable();
}

Aws::Http::HeaderValueCollection ListMedicalTranscriptionJobsRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "Transcribe.ListMedicalTranscriptionJobs"));
  return headers;

}


text:
test: clean
	python2 Test*.py; make clean
	python3 Test*.py; make clean

clean:
	rm -rf *.pyc __pycache__


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace ReleaseTest
{
    public class TesterSpheres : Tester
    {
        float elapsed;
        public TesterSpheres(Game game)
            : base(game)
        {
        }

        public override void Initialize()
        {
            base.Initialize();
        }

        public override void Update(GameTime gameTime)
        {
            float dt = (float)gameTime.ElapsedGameTime.TotalSeconds;
            elapsed += dt;

            base.Update(gameTime);
        }

        public override void Draw(GameTime gameTime)
        {
            base.Draw(gameTime);
        }
    }
}


text:
// This is EXPERIMENTAL interface for media transport.
//
// The goal is to refactor WebRTC code so that audio and video frames
// are sent / received through the media transport interface. This will
// enable different media transport implementations, including QUIC-based
// media transport.

#include "api/transport/media/media_transport_interface.h"

#include <cstdint>
#include <utility>

#include "api/transport/datagram_transport_interface.h"

namespace webrtc {

MediaTransportSettings::MediaTransportSettings() = default;
MediaTransportSettings::MediaTransportSettings(const MediaTransportSettings&) =
    default;
MediaTransportSettings& MediaTransportSettings::operator=(
    const MediaTransportSettings&) = default;
MediaTransportSettings::~MediaTransportSettings() = default;

SendDataParams::SendDataParams() = default;
SendDataParams::SendDataParams(const SendDataParams&) = default;

RTCErrorOr<std::unique_ptr<MediaTransportInterface>>
MediaTransportFactory::CreateMediaTransport(
    rtc::PacketTransportInternal* packet_transport,
    rtc::Thread* network_thread,
    const MediaTransportSettings& settings) {
  return std::unique_ptr<MediaTransportInterface>(nullptr);
}

RTCErrorOr<std::unique_ptr<MediaTransportInterface>>
MediaTransportFactory::CreateMediaTransport(
    rtc::Thread* network_thread,
    const MediaTransportSettings& settings) {
  return std::unique_ptr<MediaTransportInterface>(nullptr);
}

RTCErrorOr<std::unique_ptr<DatagramTransportInterface>>
MediaTransportFactory::CreateDatagramTransport(
    rtc::Thread* network_thread,
    const MediaTransportSettings& settings) {
  return std::unique_ptr<DatagramTransportInterface>(nullptr);
}

std::string MediaTransportFactory::GetTransportName() const {
  return "";
}

MediaTransportInterface::MediaTransportInterface() = default;
MediaTransportInterface::~MediaTransportInterface() = default;

absl::optional<std::string>
MediaTransportInterface::GetTransportParametersOffer() const {
  return absl::nullopt;
}

void MediaTransportInterface::Connect(
    rtc::PacketTransportInternal* packet_transport) {}

void MediaTransportInterface::SetKeyFrameRequestCallback(
    MediaTransportKeyFrameRequestCallback* callback) {}

absl::optional<TargetTransferRate>
MediaTransportInterface::GetLatestTargetTransferRate() {
  return absl::nullopt;
}

void MediaTransportInterface::AddNetworkChangeCallback(
    MediaTransportNetworkChangeCallback* callback) {}

void MediaTransportInterface::RemoveNetworkChangeCallback(
    MediaTransportNetworkChangeCallback* callback) {}

void MediaTransportInterface::SetFirstAudioPacketReceivedObserver(
    AudioPacketReceivedObserver* observer) {}

void MediaTransportInterface::AddTargetTransferRateObserver(
    TargetTransferRateObserver* observer) {}
void MediaTransportInterface::RemoveTargetTransferRateObserver(
    TargetTransferRateObserver* observer) {}

void MediaTransportInterface::AddRttObserver(
    MediaTransportRttObserver* observer) {}
void MediaTransportInterface::RemoveRttObserver(
    MediaTransportRttObserver* observer) {}

size_t MediaTransportInterface::GetAudioPacketOverhead() const {
  return 0;
}

void MediaTransportInterface::SetAllocatedBitrateLimits(
    const MediaTransportAllocatedBitrateLimits& limits) {}

}  // namespace webrtc


text:
#import "OTCTweet.h"

@interface OTCDirectMessage : OTCTweet
    {
@private
    OTCTwitterUser __strong* _recipient;
    OTCTwitterUser __strong* _sender;
    }

@property ( strong, readonly ) OTCTwitterUser* recipient;
@property ( strong, readonly ) OTCTwitterUser* sender;

#pragma mark Initialization
+ ( instancetype ) directMessageWithJSON: ( NSDictionary* )_JSONDict;

@end

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


text:
/*global describe, it*/
"use strict";

var fs = require("fs"),
	es = require("event-stream"),
	should = require("should");

var PluginError = require('gulp-util').PluginError;
var gulp = require('gulp');

require("mocha");

delete require.cache[require.resolve("../")];

var gutil = require("gulp-util"),
	stitch = require("../");

describe("gulp-stitch", function () {

	var expectedFile = new gutil.File({
		path: "test/expected/foo_stitch.js",
		cwd: "test/",
		base: "test/expected",
		contents: fs.readFileSync("test/expected/foo_stitch.js")
	});

	it("should produce expected file via buffer", function (done) {

		var srcFile = new gutil.File({
			path: "test/test_out",
			cwd: "test/",
			base: "test/",
		  contents: new Buffer("test = 123")
		});

		var stream = stitch("output_file",['test/fixtures/js']);

		stream.on("error", function(err) {
			should.exist(err);
			done(err);
		});

		stream.on("data", function (newFile) {
			should.exist(newFile);
			should.exist(newFile.contents);
      srcFile.contents = newFile.contents;
		});
		stream.on("end", function () {
			done();
			String(srcFile.contents).should.equal(String(expectedFile.contents));
    });

    stream.write(srcFile);
    stream.end();

			//String(srcFile.contents).should.equal(String(expectedFile.contents));
	});

	it("should error on stream", function (done) {

		var srcFile = new gutil.File({
			path: "test/fixtures/hello.txt",
			cwd: "test/",
			base: "test/fixtures",
			contents: fs.createReadStream("test/fixtures/hello.txt")
		});

		var stream = stitch('dummy');

		stream.on("error", function(err) {
			should.exist(err);
			done();
		});

		stream.write(srcFile);
		stream.end();
	});

	it("should PluginError on stream", function (done) {

		var srcFile = new gutil.File({
			path: "test/fixtures/hello.txt",
			cwd: "test/",
			base: "test/fixtures",
			contents: fs.createReadStream("test/fixtures/hello.txt")
		});

    try {
		  var stream = stitch();
    }
    catch(err) {
      should.ok(err instanceof PluginError,'not an instance of PluginError');
      done();
    }
	});

	/*
	it("should produce expected file via stream", function (done) {

		var srcFile = new gutil.File({
			path: "test/fixtures/hello.txt",
			cwd: "test/",
			base: "test/fixtures",
			contents: fs.createReadStream("test/fixtures/hello.txt")
		});

		var stream = stitch("World");

		stream.on("error", function(err) {
			should.exist(err);
			done();
		});

		stream.on("data", function (newFile) {

			should.exist(newFile);
			should.exist(newFile.contents);

			newFile.contents.pipe(es.wait(function(err, data) {
				should.not.exist(err);
				data.should.equal(String(expectedFile.contents));
				done();
			}));
		});

		stream.write(srcFile);
		stream.end();
	});
	*/
});


text:
function y = polyval(p, x)
%POLYVAL  Evaluate polynomial with CHEBFUN argument.
%   Y = POLYVAL(P, X) returns the value of a polynomial P evaluated at the
%   CHEBFUNX. P is a column vector of length N + 1 whose elements are the
%   coefficients of the polynomial in descending powers.
%        Y = P(1)*X^N + P(2)*X^(N-1) + ... + P(N)*X + P(N+1)
%
%   If P is a matrix _or_ X is a quasimatrix then a quasimatrix Y is returned.
%   If P is a matrix _and_ X is a quasimatrix then an error is thrown.
%
% Example:
%   Evaluate the polynomial p(x) = 3x^2 + 2x + 1:
%
%   p = [3 2 1].;
%   x = chebfun('x');
%   polyval(p, x)
%
% See also CHEBPOLYVAL.

if ( (size(p, 2) > 1) && (numColumns(x) > 1) )
    error('CHEBFUN:CHEBFUN:polyval:dimMismatch', ...
        'Input P must be a column vector or X must be a scalar-valued CHEBFUN.');
elseif ( ~isnumeric(p) )
    error('CHEBFUN:CHEBFUN:polyval:firstArg', ...
        'First input argument must be a vector or a matrix.');
end

% Ensure column CHEBFUN:
isTrans = get(x, 'isTransposed');
if ( isTrans )
    x = x.';
end

% Ensure correct number of columns:
x = repmat(x, 1, size(p, 2));

% Horner's scheme:
y = 0*x + p(1,:);
for j = 2:size(p, 1)
    y = y.*x + p(j,:);
end

% Revert to row CHEBFUN:
if ( isTrans )
    y = y.';
end

end


text:
package org.waveprotocol.wave.model.id;

/**
 * This class holds useful utilities for ids.
 *
 * @author zdwang@google.com (David Wang)
 */
public class IdUtil implements IdConstants {

  protected IdUtil() {
  }

  /**
   * Tests whether a wavelet id is of a conversation root wavelet.
   */
  public static boolean isConversationRootWaveletId(WaveletId waveletId) {
    return waveletId.getId().equals(CONVERSATION_ROOT_WAVELET)
        || isLegacyConversationRootWaveletId(waveletId);
  }

  /**
   * Tests whether a wavelet id is a legacy conversation root wavelet.
   */
  private static boolean isLegacyConversationRootWaveletId(WaveletId id) {
    return id.getId().equals("conversation/root");
  }

  /**
   * Tests whether an wavelet id is of a conversation wavelet.
   */
  public static boolean isConversationalId(WaveletId waveletId) {
    return getInitialToken(waveletId.getId()).equals(CONVERSATION_WAVELET_PREFIX)
        || isLegacyConversationalId(waveletId);
  }

  /**
   * Tests whether a wavelet id is of a legacy conversational wavelet.
   */
  private static boolean isLegacyConversationalId(WaveletId id) {
    // NOTE(user): Legacy private-replies have random ids, and do not
    // necessarily follow the id schema of starting with the conversation
    // prefix. Therefore, an id without a prefix is considered to be
    // conversational.
    return getInitialToken(id.getId()).isEmpty();
  }

  /**
   * Tests whether a document id is a blip id. A legacy "ghost" blip id is a
   * blip id.
   */
  public static boolean isBlipId(String id) {
    return hasInitialTokenUnescaped(id, BLIP_PREFIX) || isGhostBlipId(id) || isLegacyBlipId(id);
  }

  /**
   * Tests whether a document id is a legacy blip id.
   */
  private static final boolean isLegacyBlipId(String id) {

    // NOTE(anorth): legacy blips have random ids containing "*"; data
    // documents from this time have a few well-known prefixes.
    return id.contains("*") && !id.startsWith("m/") && !id.startsWith("attach+") && !id
        .startsWith("spell+");
  }

  /**
   * Tests whether a document id is a ghost blip document id.
   */
  public static final boolean isGhostBlipId(String id) {
    return hasInitialTokenUnescaped(id, GHOST_BLIP_PREFIX);
  }

  /**
   * Tests whether a document id is an attachment data document id.
   */
  public static boolean isAttachmentDataDocument(String id) {
    return hasInitialTokenUnescaped(id, ATTACHMENT_METADATA_PREFIX)
        || isLegacyAttachmentDataDocumentId(id);
  }

  private static boolean isLegacyAttachmentDataDocumentId(String id) {
    return id.startsWith("m/attachment/");
  }

  /**
   * Tests whether a document id is a manifest document ID.
   */
  public static boolean isManifestDocument(String id) {
    return id.equals(MANIFEST_DOCUMENT_ID);
  }

  /**
   * Tests whether a document id is a tags document ID.
   */
  public static boolean isTagsDataDocument(String id) {
    return id.equals(TAGS_DOC_ID);
  }

  /**
   * Tests whether a document id is a robot document id.
   */
  public static boolean isRobotDocId(String documentId) {
    return hasInitialTokenUnescaped(documentId, ROBOT_PREFIX);
  }

  /**
   * Gets the address that a user data wavelet ID is for.
   *
   * @return UDW address, or {@code null} if the ID is not a user data wavelet
   *         ID.
   */
  public static final String getUserDataWaveletAddress(WaveletId waveletId) {
    String[] parts = split(waveletId.getId());
    if (parts.length != 2 || !parts[0].equals(USER_DATA_WAVELET_PREFIX)) {
      return null;
    }
    return parts[1];
  }

  /**
   * Tests if a wavelet id is the id of a user's user-data wavelet.
   *
   * @param waveletId
   * @return true if {@code waveletId} is the waveletId of an user-data wavelet.
   */
  public static final boolean isUserDataWavelet(WaveletId waveletId) {
    return hasInitialTokenUnescaped(waveletId.getId(), USER_DATA_WAVELET_PREFIX);
  }

  /**
   * Tests if a wavelet id is the id of a user's user-data wavelet.
   *
   * @return true if {@code waveletId} is the waveletId of the user-data
   *         wavelet of {@code address}.
   */
  public static final boolean isUserDataWavelet(String address, WaveletId waveletId) {
    return address.equals(getUserDataWaveletAddress(waveletId));
  }

  /**
   * Extracts the initial token of an id followed by the
   * {@link IdConstants#TOKEN_SEPARATOR} or an empty string if the separator was
   * not found.
   *
   * @param id
   * @return the initial token of the id, or an empty string if no separator was
   *         found.
   */
  public static String getInitialToken(String id) {
    String[] tokens = SimplePrefixEscaper.DEFAULT_ESCAPER.split(TOKEN_SEPARATOR, id);
    if (tokens.length > 1) {
      return tokens[0];
    } else {
      return "";
    }
  }

  /**
   * Tests whether a string has an initial token followed by
   * {@link IdConstants#TOKEN_SEPARATOR} without un-escaping the token first.
   * The token must not contain the separator.
   */
  public static boolean hasInitialTokenUnescaped(String id, String token) {
    // Ensure token doesn't contain the separator so startsWith is safe.
    assert token.indexOf(TOKEN_SEPARATOR) == -1;
    return id.startsWith(token + TOKEN_SEPARATOR);
  }

  /** Splits an id into an array of tokens on {@link IdConstants#TOKEN_SEPARATOR}. */
  public static String[] split(String id) {
    try {
      return SimplePrefixEscaper.DEFAULT_ESCAPER.split(TOKEN_SEPARATOR, id);
    } catch (IllegalArgumentException e) {
      return null;
    }
  }

  /**
   * Joins an array of tokens with {@link IdConstants#TOKEN_SEPARATOR} into an
   * id string.
   */
  public static String join(String... tokens) {
    return SimplePrefixEscaper.DEFAULT_ESCAPER.join(TOKEN_SEPARATOR, tokens);
  }
}


text:
using .geometry_msgs.msg

const Nmsgs = 10
const rate = 20. #Hz
const msgs = PoseStamped[]
const refs = Array{Vector3}(undef, Nmsgs)
const t0 = to_nsec(get_rostime())

for i=1:Nmsgs
    refs[i] = Vector3(rand(3)...)
end

const ros_pub = Publisher("vectors", Vector3, queue_size = 10)
rossleep(Duration(3.0))

function publish_messages(pubobj, msgs, rate_hz)
    r = Rate(rate_hz)
    for msg in msgs
        publish(pubobj, msg)
        rossleep(r)
    end
    rossleep(Duration(1.0))
end

function pose_cb(msg::PoseStamped, msgs::Vector{PoseStamped})
    mtime = to_nsec(msg.header.stamp) - t0
    mtime > 0 && println("Message received, time: ",mtime," nanoseconds")
    if msg.header.stamp.secs > 1.0
        push!(msgs, msg)
        println("Got message #",msg.header.seq)
    end
end
pose_cb(PoseStamped(), msgs) #warm up run

const ros_sub = Subscriber("poses", PoseStamped, pose_cb, (msgs,), queue_size = 10)

#First message doesn't go out for some reason
publish(ros_pub, Vector3(1.1,2.2,3.3))
rossleep(Duration(1.0))

#Test messages
publish_messages(ros_pub, refs, 20.0)
rossleep(Duration(1.0))

println("Received ",length(msgs)," / ",Nmsgs)

@test length(msgs) == Nmsgs
for i=1:Nmsgs
    @test msgs[i].pose.position.x ≈ refs[i].x
    @test msgs[i].pose.position.y ≈ refs[i].y
    @test msgs[i].pose.position.z ≈ refs[i].z
end
empty!(msgs)


text:
import _extends from "@babel/runtime/helpers/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties";
var _excluded = ["children"];
import { createScopedElement } from "../../lib/jsxRuntime";
import { PanelHeaderButton } from "../PanelHeaderButton/PanelHeaderButton";
import { Icon28DoneOutline } from "@vkontakte/icons";
import { IOS } from "../../lib/platform";
import { usePlatform } from "../../hooks/usePlatform";
import { getTitleFromChildren } from "../../lib/utils";

/**
 * @see https://vkcom.github.io/VKUI/#/PanelHeaderSubmit
 */
export var PanelHeaderSubmit = function PanelHeaderSubmit(_ref) {
  var _ref$children = _ref.children,
    children = _ref$children === void 0 ? "Готово" : _ref$children,
    restProps = _objectWithoutProperties(_ref, _excluded);
  var platform = usePlatform();
  return createScopedElement(PanelHeaderButton, _extends({
    "aria-label": getTitleFromChildren(children),
    primary: true
  }, restProps), platform === IOS ? children : createScopedElement(Icon28DoneOutline, null));
};
//# sourceMappingURL=PanelHeaderSubmit.js.map


text:
require "focuslight"

module Focuslight::Config
  DEFAULT_DATADIR = File.expand_path('data', "#{__dir__}/../..")
  DEFAULT_LOG_PATH = File.expand_path('log/application.log', "#{__dir__}/../..")
  CONFIG = {
    datadir: ENV.fetch('DATADIR', DEFAULT_DATADIR),
    float_support: ENV.fetch('FLOAT_SUPPORT', false),
    dburl: ENV.fetch('DBURL', 'sqlite://data/gforecast.db'),
    dbtimeout: ENV.fetch('DBTIMEOUT', '60000').to_i,
    log_path: ENV.fetch('LOG_PATH', DEFAULT_LOG_PATH),
    log_level: ENV.fetch('LOG_LEVEL', 'info'),
    log_shift_age: ENV.fetch('LOG_SHIFT_AGE', '0'),
    log_shift_size: ENV.fetch('LOG_SHIFT_SIZE', '1048576'),
  }

  def self.get(name)
    CONFIG.fetch(name)
  end
end


text:
from django.db.models import Count
from tastypie.resources import ModelResource, ALL_WITH_RELATIONS
from tastypie import http, fields
from tastypie.exceptions import ImmediateHttpResponse
from tastypie.bundle import Bundle

import json

from django.core.exceptions import ValidationError, ObjectDoesNotExist
from django.http import HttpResponse

from .models import Run, RunCaseVersion, RunSuite, Result
from ..mtapi import MTResource, MTApiKeyAuthentication, MTAuthorization
from ..core.api import (ProductVersionResource, ProductResource,
                        ReportResultsAuthorization, UserResource)
from ..environments.api import EnvironmentResource
from ..environments.models import Environment
from ..library.api import (CaseVersionResource, BaseSelectionResource,
                           SuiteResource)
from ..library.models import CaseVersion, Suite

from ...view.lists.filters import filter_url

import logging
logger = logging.getLogger(__name__)

class RunSuiteAuthorization(MTAuthorization):
    """Atypically named permission."""

    @property
    def permission(self):
        """This permission should be checked by is_authorized."""
        return "execution.manage_runs"

class RunCaseVersionResource(ModelResource):
    """
    RunCaseVersion represents the connection between a run and a caseversion.

    It is possible to return a result for each runcaseversion.  So the result
    will sit as a peer to the caseversion under the runcaseversion.

    """

    run = fields.ToOneField(
        "moztrap.model.execution.api.RunResource",
        "run",
        related_name="runcaseversion")
    caseversion = fields.ToOneField(CaseVersionResource, "caseversion", full=True)

    class Meta:
        queryset = RunCaseVersion.objects.all()
        list_allowed_methods = ['get']
        filtering = {
            "run": ALL_WITH_RELATIONS,
            "caseversion": ALL_WITH_RELATIONS,
            }
        fields = ["id", "run"]

class RunResource(ModelResource):
    """
    Fetch the test runs for the specified product and version.

    It is also possible to create a new testrun, when posted.

    """

    productversion = fields.ForeignKey(ProductVersionResource, "productversion")
    environments = fields.ToManyField(
        EnvironmentResource,
        "environments",
        full=False,
        )
    runcaseversions = fields.ToManyField(
        RunCaseVersionResource,
        "runcaseversions",
        )

    class Meta:
        queryset = Run.objects.all()
        list_allowed_methods = ["get", "post"]
        fields = [
            "id",
            "name",
            "description",
            "status",
            "productversion",
            "environments",
            "runcaseversions",
            ]
        filtering = {
            "productversion": ALL_WITH_RELATIONS,
            "status": "exact",
        }
        authentication = MTApiKeyAuthentication()
        authorization = ReportResultsAuthorization()
        always_return_data = True

    def dehydrate(self, bundle):
        """Add some convenience fields to the return JSON."""

        pv = bundle.obj.productversion
        bundle.data["productversion_name"] = pv.version
        bundle.data["product_name"] = pv.product.name

        return bundle

    def dispatch_detail(self, request, **kwargs):
        """For details, we want the full info on environments for the run """

        self.fields["environments"].full = True
        return super(RunResource, self).dispatch_detail(request, **kwargs)

    def dispatch_list(self, request, **kwargs):
        """For list, we don't want the full info on environments """

        self.fields["environments"].full = False
        return super(RunResource, self).dispatch_list(request, **kwargs)

    def create_response(self, request, data,
                        response_class=HttpResponse, **response_kwargs):
        """On posting a run, return a url to the MozTrap UI for that new run."""

        resp = super(RunResource, self).create_response(
            request,
            data,
            response_class=response_class,
            **response_kwargs
            )

        if isinstance(data, Bundle):
            # data will be a bundle if we are creating a new Run.  And in that
            # case we want to add a URI to viewing this new run result in the UI
            full_url = filter_url(
                "results_runcaseversions",
                Run.objects.get(pk=data.data["id"]),
                )

            new_content = json.loads(resp.content)
            new_content["ui_uri"] = full_url
            new_content["resource_uri"] = data.data["resource_uri"]

            resp.content = json.dumps(new_content)
            # need to set the content type to application/json
            resp._headers["content-type"] = ("Content-Type", "application/json; charset=utf-8")
        return resp

    def obj_create(self, bundle, request=None, **kwargs):
        """Set the created_by field for the run to the request's user"""
        request = request or bundle.request
        bundle = super(RunResource, self).obj_create(bundle=bundle, request=request, **kwargs)
        bundle.obj.created_by = request.user
        bundle.obj.save()
        return bundle

    def hydrate_runcaseversions(self, bundle):
        """
        Handle the runcaseversion creation during a POST of a new Run.

        Tastypie handles the creation of the run itself.  But we handle the
        RunCaseVersions and Results because we have special handler methods for
        setting the statuses which we want to keep DRY.

        """

        try:
            run = bundle.obj
            run.save()

            # walk results

            for data in bundle.data["runcaseversions"]:

                status = data.pop("status")

                # find caseversion for case
                cv = CaseVersion.objects.get(
                    productversion=run.productversion,
                    case=data.pop("case"),
                    )

                # create runcaseversion for this run to caseversion
                rcv, created = RunCaseVersion.objects.get_or_create(
                    run=run,
                    caseversion=cv,
                    )

                data["user"] = bundle.request.user
                data["environment"] = Environment.objects.get(
                    pk=data["environment"])

                # create result via methods on runcaseversion
                rcv.get_result_method(status)(**data)

            bundle.data["runcaseversions"] = []
            return bundle

        except KeyError as e:
            raise ValidationError(
                "bad result object data missing key: {0}".format(e))

        except ObjectDoesNotExist as e:
            raise ValidationError(e)

class ResultResource(ModelResource):
    """
    Endpoint for submitting results for a set of runcaseversions.

    This endpoint is write only.  The submitted result objects should
    be formed like this::

        {
            "objects": [
                {
                    "case": "1",
                    "environment": "23",
                    "run_id": "1",
                    "status": "passed"
                },
                {
                    "case": "14",
                    "comment": "why u no make sense??",
                    "environment": "23",
                    "run_id": "1",
                    "status": "invalidated"
                },
                {
                    "bug": "http://www.deathvalleydogs.com",
                    "case": "326",
                    "comment": "why u no pass?",
                    "environment": "23",
                    "run_id": "1",
                    "status": "failed",
                    "stepnumber": 1
                }
            ]
        }

    """

    class Meta:
        queryset = Result.objects.all()
        resource_name = "result"
        list_allowed_methods = ["get", "patch"]

        filtering = {
            "created_on": ALL_WITH_RELATIONS,
        }

        authentication = MTApiKeyAuthentication()
        authorization = ReportResultsAuthorization()

    def obj_create(self, bundle, request=None, **kwargs):
        """
        Manually create the proper results objects.

        This is necessary because we have special handler methods in
        RunCaseVersion for setting the statuses which we want to keep DRY.

        """
        request = request or bundle.request
        data = bundle.data.copy()

        try:
            status = data.pop("status")
            case = data.pop("case")
            env = Environment.objects.get(pk=data.get("environment"))
            run = data.pop("run_id")

        except KeyError as e:
            raise ValidationError(
                "bad result object data missing key: {0}".format(e))

        except Environment.DoesNotExist as e:
            raise ValidationError(
                "Specified environment does not exist: {0}".format(e))

        data["environment"] = env

        try:
            rcv = RunCaseVersion.objects.get(
                run__id=run,
                caseversion__case__id=case,
                environments=env,
                )

        except RunCaseVersion.DoesNotExist as e:
            raise ValidationError(
                "RunCaseVersion not found for run: {0}, case: {1}, environment: {2}:\nError {3}".format(
                        str(run), str(case), str(env), e))

        self.authorized_create_detail([rcv], bundle)
        data["user"] = request.user

        method = rcv.get_result_method(status)
        bundle.obj = method(**data)
        return bundle

class RunSuiteResource(MTResource):
    """
    Create, Read, Update and Delete capabilities for RunSuite.

    Filterable by suite and run fields.
    """

    run = fields.ForeignKey(RunResource, 'run')
    suite = fields.ForeignKey(SuiteResource, 'suite')

    class Meta(MTResource.Meta):
        queryset = RunSuite.objects.all()
        fields = ["suite", "run", "order", "id"]
        filtering = {
            "suite": ALL_WITH_RELATIONS,
            "run": ALL_WITH_RELATIONS
        }
        authorization = RunSuiteAuthorization()

    @property
    def model(self):
        return RunSuite

    @property
    def read_create_fields(self):
        """run and suite are read-only"""
        return ["suite", "run"]

    def hydrate_suite(self, bundle):
        """suite is read-only on PUT
        suite.product must match run.productversion.product on CREATE
        """

        # CREATE
        if bundle.request.META['REQUEST_METHOD'] == 'POST':
            suite_id = self._id_from_uri(bundle.data['suite'])
            suite = Suite.objects.get(id=suite_id)
            run_id = self._id_from_uri(bundle.data['run'])
            run = Run.objects.get(id=run_id)
            if suite.product.id != run.productversion.product.id:
                error_message = str(
                    "suite's product must match run's product."
                )
                logger.error(
                    "\n".join([error_message, "suite prod: %s, run prod: %s"]),
                    suite.product.id, run.productversion.product.id)
                raise ImmediateHttpResponse(
                    response=http.HttpBadRequest(error_message))

        return bundle

class SuiteSelectionResource(BaseSelectionResource):
    """
    Specialty end-point for an AJAX call from the multi-select widget
    for selecting suites.
    """

    product = fields.ForeignKey(ProductResource, "product")
    runs = fields.ToManyField(RunResource, "runs")
    created_by = fields.ForeignKey(
        UserResource, "created_by", full=True, null=True)

    class Meta:
        queryset = Suite.objects.all().select_related(
            "created_by",
            ).annotate(case_count=Count("cases"))

        list_allowed_methods = ['get']
        fields = ["id", "name", "created_by"]
        filtering = {
            "product": ALL_WITH_RELATIONS,
            "runs": ALL_WITH_RELATIONS,
            "created_by": ALL_WITH_RELATIONS,
            }
        ordering = ["runs"]

    def dehydrate(self, bundle):
        """Add some convenience fields to the return JSON."""

        suite = bundle.obj
        bundle.data["suite_id"] = suite.id
        bundle.data["case_count"] = suite.case_count
        bundle.data["filter_cases"] = filter_url("manage_cases", suite)

        return bundle


text:
using MailChimp.Net.Core;
using MailChimp.Net.Interfaces;
using MailChimp.Net.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;

namespace MailChimp.Net.Logic
{
    /// <summary>
    /// The campaign folder logic.
    /// </summary>
    internal class FileManagerFileLogic : BaseLogic, IFileManagerFileLogic
    {

        private const string BaseUrl = "file-manager/files";

        public FileManagerFileLogic(MailChimpOptions mailChimpConfiguration)
            : base(mailChimpConfiguration)
        {
        }

        /// <exception cref="ObjectDisposedException">Either the current stream or <paramref>
        ///         <name>destination</name>
        ///     </paramref>
        ///     were closed before the <see cref="M:System.IO.Stream.CopyTo(System.IO.Stream)" /> method was called.</exception>
        /// <exception cref="NotSupportedException">The current stream does not support reading.-or-<paramref>
        ///         <name>destination</name>
        ///     </paramref>
        ///     does not support writing.</exception>
        private string ConvertToBase64(Stream stream)
        {
            byte[] bytes;
            using (var memoryStream = new MemoryStream())
            {
                stream.CopyTo(memoryStream);
                bytes = memoryStream.ToArray();
            }
            return Convert.ToBase64String(bytes);
        }

        [Obsolete("This method is deprecated.")]
        public async Task<FileManagerFile> AddFileAsync(string name, string folderId, string fileName)
        {
            return await AddFileAsync(name, int.TryParse(folderId, out var result) ? result : 0, fileName);
        }
        public async Task<FileManagerFile> AddFileAsync(string name, int folderId, string fileName)
        {
            using (var fs = File.OpenRead(fileName))
            using (var client = CreateMailClient(BaseUrl))
            {

                var response = await client.PostAsJsonAsync(string.Empty, new { name, folder_id = folderId, file_data = ConvertToBase64(fs) }).ConfigureAwait(false);
                await response.EnsureSuccessMailChimpAsync().ConfigureAwait(false);

                var fileManagerFile = await response.Content.ReadAsAsync<FileManagerFile>().ConfigureAwait(false);
                return fileManagerFile;
            }
        }

        [Obsolete("This method is deprecated.")]
        public async Task<FileManagerFile> AddAsync(string name, string folderId, string base64String)
        {
            return await AddAsync(name, int.TryParse(folderId, out var result) ? result : 0, base64String);
        }
        public async Task<FileManagerFile> AddAsync(string name, int folderId, string base64String)
        {
            using (var client = CreateMailClient(BaseUrl))
            {
                var response = await client.PostAsJsonAsync(string.Empty, new { name, folder_id = folderId, file_data = base64String }).ConfigureAwait(false);
                await response.EnsureSuccessMailChimpAsync().ConfigureAwait(false);

                var fileManagerFile = await response.Content.ReadAsAsync<FileManagerFile>().ConfigureAwait(false);
                return fileManagerFile;
            }
        }

        [Obsolete("This method is deprecated.")]
        public async Task<FileManagerFile> AddAsync(string name, string folderId, Stream fileStream)
        {
            return await AddAsync(name, int.TryParse(folderId, out var result) ? result : 0, fileStream);
        }
        public async Task<FileManagerFile> AddAsync(string name, int folderId, Stream fileStream)
        {
            using (var client = CreateMailClient(BaseUrl))
            {
                var response = await client.PostAsJsonAsync(string.Empty, new { name, folder_id = folderId, file_data = ConvertToBase64(fileStream) }).ConfigureAwait(false);
                await response.EnsureSuccessMailChimpAsync().ConfigureAwait(false);

                var fileManagerFile = await response.Content.ReadAsAsync<FileManagerFile>().ConfigureAwait(false);
                return fileManagerFile;
            }
        }

        public async Task<IEnumerable<FileManagerFile>> GetAllAsync(FileManagerRequest request = null)
        {
            return (await GetResponseAsync(request).ConfigureAwait(false))?.Files;
        }

        public async Task<FileManagerFileResponse> GetResponseAsync(FileManagerRequest request = null)
        {
            request = request ?? new FileManagerRequest
            {
                Limit = _limit
            };

            using (var client = CreateMailClient(BaseUrl))
            {
                var response = await client.GetAsync(request.ToQueryString()).ConfigureAwait(false);
                await response.EnsureSuccessMailChimpAsync().ConfigureAwait(false);

                var fileManagerFileResponse = await response.Content.ReadAsAsync<FileManagerFileResponse>().ConfigureAwait(false);
                return fileManagerFileResponse;
            }
        }

        public async Task<FileManagerFile> GetAsync(string fileId, BaseRequest request = null)
        {
            using (var client = CreateMailClient($"{BaseUrl}/"))
            {
                var response = await client.GetAsync($"{fileId}{request?.ToQueryString()}").ConfigureAwait(false);
                await response.EnsureSuccessMailChimpAsync().ConfigureAwait(false);

                var fileManagerFile = await response.Content.ReadAsAsync<FileManagerFile>().ConfigureAwait(false);
                return fileManagerFile;
            }
        }

        public async Task DeleteAsync(string fileId)
        {
            using (var client = CreateMailClient($"{BaseUrl}/"))
            {
                var response = await client.DeleteAsync($"{fileId}").ConfigureAwait(false);
                await response.EnsureSuccessMailChimpAsync().ConfigureAwait(false);
            }
        }
        [Obsolete("This method is deprecated.")]
        public async Task<FileManagerFile> UpdateFileAsync(string fileId, string name, string folderId, string fileName)
        {
            return await UpdateFileAsync(fileId, name, int.TryParse(folderId, out var result) ? result : 0, fileName);
        }
        public async Task<FileManagerFile> UpdateFileAsync(string fileId, string name, int folderId, string fileName)
        {
            using (var fs = File.OpenRead(fileName))
            using (var client = CreateMailClient($"{BaseUrl}/"))
            {
                var response = await client.PatchAsJsonAsync($"{fileId}", new { name, folder_id = folderId, file_data = ConvertToBase64(fs) }).ConfigureAwait(false);
                await response.EnsureSuccessMailChimpAsync().ConfigureAwait(false);

                var folder = await response.Content.ReadAsAsync<FileManagerFile>().ConfigureAwait(false);
                return folder;

            }
        }

        [Obsolete("This method is deprecated.")]
        public async Task<FileManagerFile> UpdateAsync(string fileId, string name, string folderId, string base64String)
        {
            return await UpdateAsync(fileId, name, int.TryParse(folderId, out var result) ? result : 0, base64String);
        }
        public async Task<FileManagerFile> UpdateAsync(string fileId, string name, int folderId, string base64String)
        {
            using (var client = CreateMailClient($"{BaseUrl}/"))
            {
                var response = await client.PatchAsJsonAsync($"{fileId}", new { name, folder_id = folderId, file_data = base64String }).ConfigureAwait(false);
                await response.EnsureSuccessMailChimpAsync().ConfigureAwait(false);

                var folder = await response.Content.ReadAsAsync<FileManagerFile>().ConfigureAwait(false);
                return folder;

            }
        }
        [Obsolete("This method is deprecated.")]
        public async Task<FileManagerFile> UpdateAsync(string fileId, string name, string folderId, Stream stream)
        {
            return await UpdateAsync(fileId, name, int.TryParse(folderId, out var result) ? result : 0, stream);
        }
        public async Task<FileManagerFile> UpdateAsync(string fileId, string name, int folderId, Stream stream)
        {
            using (var client = CreateMailClient($"{BaseUrl}/"))
            {
                var response = await client.PatchAsJsonAsync($"{fileId}", new { name, folder_id = folderId, file_data = ConvertToBase64(stream) }).ConfigureAwait(false);
                await response.EnsureSuccessMailChimpAsync().ConfigureAwait(false);

                var folder = await response.Content.ReadAsAsync<FileManagerFile>().ConfigureAwait(false);
                return folder;

            }
        }
    }
}


text:
package com.xcysoft.foundation.cppt.dao;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;

import cn.newcapec.framework.core.utils.pagesUtils.Page;

import com.xcysoft.foundation.cppt.dao.base.BaseMenuDao;

/**
 *
 * @author huangxin
 *
 */
@Repository
@SuppressWarnings("all")
public class MenuDao extends BaseMenuDao {

	/**
	 *
	 * @param paramMap
	 * @return
	 */
	public Page findAll(Map<String, Object> paramMap,
			LinkedHashMap<String, String> orderby) {
		List<Object> param = new ArrayList<Object>();
		StringBuilder sql = new StringBuilder(
				"select t.* from s_menu t where 1=1");
		if (null != paramMap) {
			if (paramMap.containsKey("menu_name")
					&& StringUtils.isNotBlank(paramMap.get("menu_name")
							.toString())) {
				sql.append(" and t.menu_name like ?");
				param.add("%" + paramMap.get("menu_name") + "%");
			}
			if (paramMap.containsKey("pid")
					&& StringUtils.isNotBlank(paramMap.get("pid").toString())) {
				sql.append(" and t.pid = ?");
				param.add(paramMap.get("pid"));
			}
		}
		return this.sqlQueryForPage(sql.toString(), param.toArray(), orderby);
	}

	public List findAllChildren(Map<String, Object> paramMap,
			LinkedHashMap<String, String> orderby) {
		List<Object> param = new ArrayList<Object>();
		StringBuilder sql = new StringBuilder(
				"select t.* from s_menu t where 1=1");
		if (null != paramMap) {
			if (paramMap.containsKey("menu_name")
					&& StringUtils.isNotBlank(paramMap.get("menu_name")
							.toString())) {
				sql.append(" and t.menu_name like ?");
				param.add("%" + paramMap.get("menu_name") + "%");
			}
			if (paramMap.containsKey("pid")
					&& StringUtils.isNotBlank(paramMap.get("pid").toString())) {
				sql.append(" and t.path like CONCAT((select path from s_menu where id=?), ',%')");
				param.add(paramMap.get("pid"));
			}
		}
		return this.sqlQueryForList(sql.toString(), param.toArray(), orderby);
	}
}


text:
#ifndef vcl_config_compiler_h_config_win32_vc70_
#define vcl_config_compiler_h_config_win32_vc70_
//:
// \file
// This file is *not* generated.

//----------------------------------------------------------------------
// syntax-like things.

//: VCL_HAS_BOOL
// Set to 1 if "bool" is accepted by the compiler as a built-in type.
#define VCL_HAS_BOOL 1

//: VCL_HAS_DYNAMIC_CAST
//
// True if the compiler supports dynamic cast.
//
#define VCL_HAS_DYNAMIC_CAST 1

//: VCL_HAS_RTTI
//
// True if the compiler supports RTTI, viz the 'typeid' function.
//
#define VCL_HAS_RTTI 0

//: VCL_HAS_TYPENAME
//
// True if the compiler supports the "typename" keyword
//
#define VCL_HAS_TYPENAME 1

//: VCL_HAS_EXPORT
//
// True if the compiler supports the "export" keyword. FIXME.
//
#define VCL_HAS_EXPORT 0

//: VCL_HAS_MUTABLE
//
// True if the compiler supports the "mutable" keyword
//
#define VCL_HAS_MUTABLE 1

//: VCL_HAS_EXPLICIT
//
// True if the compiler supports the "explicit" keyword
//
#define VCL_HAS_EXPLICIT 1

//: VCL_FOR_SCOPE_HACK:
//
// True if the compiler uses old-style 'for' loop scoping.
// Setting this nonzero causes the Henderson trick to be used.
#define VCL_FOR_SCOPE_HACK 1

//: VCL_COMPLEX_POW_WORKS
//
// It appears several programmers have (independently)
// not realised their lack of knowledge of complex numbers.
// pow(complex(-1,0),0.5) should return (0,1) not (Nan,0), etc.
#define VCL_COMPLEX_POW_WORKS 0

//: VCL_DEFAULT_VALUE(x)
//
// Used to provide default values for function args in definition
// Some compilers (GCC272) require defaults in template function definitions
// Other compilers (VC50) disallow defaults in both decls and defs

//#define VCL_DEFAULT_VALUE(x) /* no need */
//#define VCL_DEFAULT_VALUE(x) = x
#define VCL_DEFAULT_VALUE(x) /* no need */

//----------------------------------------------------------------------
// constant initializer issues.

//: VCL_STATIC_CONST_INIT_INT_DECL(x)
//
// ANSI allows
// \code
//     class A {
//       static const int x = 27;
//     };
// \endcode
// And there is a speed advantage, so we want to use it where supported.
// However, the standard also requires (9.4.2/4) that the constant be
// defined in namespace scope. (That is, space must be allocated.)
// To make matters worse, some compilers (at least VC 7) mistakenly
// allocate storage without the definition in namespace scope,
// which results in multiply defined symbols.
// To use the macro, use VCL_STATIC_CONST_INIT_INT_DECL in the class
// definition (header file). This declares the constant.
// \code
//     class A {
//       static const int x VCL_STATIC_CONST_INIT_INT_DECL(27);
//     };
// \endcode
// Use VCL_STATIC_CONST_INIT_INT_DEFN in some .cxx file to define
// the constant, but only if VCL_STATIC_CONST_INIT_INT_NO_DEFN
// evaluates to false.
// \code
//     #if !VCL_STATIC_CONST_INIT_INT_NO_DEFN
//     const int A::x VCL_STATIC_CONST_INIT_INT_DEFN(27);
//     #endif
// \endcode
//
// In order to be able to query the setting of this, one actually must
// define VCL_CAN_STATIC_CONST_INIT_INT to either 0 or 1.

//#define VCL_CAN_STATIC_CONST_INIT_INT 1 /* allowed */
//#define VCL_CAN_STATIC_CONST_INIT_INT 0 /* not allowed */
#ifndef VCL_CAN_STATIC_CONST_INIT_INT
# define VCL_CAN_STATIC_CONST_INIT_INT 0
#endif
#if VCL_CAN_STATIC_CONST_INIT_INT
# define VCL_STATIC_CONST_INIT_INT_DECL(x) = x
# define VCL_STATIC_CONST_INIT_INT_DEFN(x) /* initialized at declaration */
# define VCL_STATIC_CONST_INIT_INT_NO_DEFN 0
#else
# define VCL_STATIC_CONST_INIT_INT_DECL(x) /* not allowed */
# define VCL_STATIC_CONST_INIT_INT_DEFN(x) = x
# define VCL_STATIC_CONST_INIT_INT_NO_DEFN 0
#endif

//: VCL_STATIC_CONST_INIT_FLOAT(x)
//
// GCC allows the above, but with floating point types, ANSI doesn't.
// Again, we'll use it if we've got it.
//
// In order to be able to query the setting of this, one actually must
// define VCL_CAN_STATIC_CONST_INIT_FLOAT to either 0 or 1.

//#define VCL_CAN_STATIC_CONST_INIT_FLOAT 1 /* allowed */
//#define VCL_CAN_STATIC_CONST_INIT_FLOAT 0 /* not allowed */
#ifndef VCL_CAN_STATIC_CONST_INIT_FLOAT
# define VCL_CAN_STATIC_CONST_INIT_FLOAT 0
#endif
#if VCL_CAN_STATIC_CONST_INIT_FLOAT
# define VCL_STATIC_CONST_INIT_FLOAT_DECL(x) = x
# define VCL_STATIC_CONST_INIT_FLOAT_DEFN(x) /* initialized at declaration */
# define VCL_STATIC_CONST_INIT_FLOAT_NO_DEFN 0
#else
# define VCL_STATIC_CONST_INIT_FLOAT_DECL(x) /* not allowed */
# define VCL_STATIC_CONST_INIT_FLOAT_DEFN(x) = x
# define VCL_STATIC_CONST_INIT_FLOAT_NO_DEFN 0
#endif

//----------------------------------------------------------------------
// various template issues.

//: VCL_HAS_MEMBER_TEMPLATES
//
// True if the compiler supports template members of template classes.  e.g.
// \code
//     template <class U> class A {
//       template <class V> void f(V);
//     }
// \endcode
#define VCL_HAS_MEMBER_TEMPLATES 1

//: VCL_CAN_DO_PARTIAL_SPECIALIZATION
//
// True if the compiler supports partial specializations of templates. e.g.
// \code
// template <class T>
// class vector<T*> : public vector<void *> { .. inline methods .. };
// \endcode
//
#define VCL_CAN_DO_PARTIAL_SPECIALIZATION 0

//: VCL_DEFINE_SPECIALIZATION
//
// In order to *define* a template (function or class) specialization, the
// definition must be preceded by "template <>" on ISO-conforming compilers.
// Some compilers (eg gcc 2.7.2) make no distinction between an instance
// of a templated function and a function with the same name and signature,
// and so do not support the use of "template <>". Use VCL_DEFINE_SPECIALIZATION
// instead.
//
// Note that you DO NOT need to forward declare a specialization. E.g. if
// foo.h says "template <class T> void foo(T *);" and foo.cxx specializes
// void foo<int>(int *), the client doesn't need to know that the template
// symbol he links against is a specialization.

//#define VCL_DEFINE_SPECIALIZATION /* template <> */
//#define VCL_DEFINE_SPECIALIZATION template <>
// !!! different from VC6
#define VCL_DEFINE_SPECIALIZATION template <>

//: VCL_CANNOT_SPECIALIZE_CV
//
// Template specialization considers top-level cv-qualifiers of the
// argument type.  For example, A<int> and A<int const> are distinct
// types.  Some compilers (eg Borland 5.5) do not make this distinction.
// Specializations using top-level cv-qualifiers should not be defined
// in addition to the unqualified equivalents unless
// VCL_CANNOT_SPECIALIZE_CV is false.
//#define VCL_CANNOT_SPECIALIZE_CV 1 /* cannot specialize with cv-qualifiers */
//#define VCL_CANNOT_SPECIALIZE_CV 0 /* can specialize with cv-qualifiers */
#define VCL_CANNOT_SPECIALIZE_CV 0

//: VCL_TEMPLATE_MATCHES_TOO_OFTEN
//
// A function template is selected by overload resolution only if no
// non-template requires equal or better conversions.  Some compilers
// (eg MSVC 6.x and 7.0, Borland 5.5 and 5.6) select the template
// incorrectly in a case like this:
// \code
//    class A {};
//    template <class T> void f(T);
//    void f(const A&);
//    void g() { f(A()); } // should call non-template
// \endcode
//
// The work-around is to explicitly give the template a worse
// conversion than the non-templated overloads:
// \code
//    class A {};
//    template <class T> inline void f(T t) { f(t, 1); }
//    template <class T> void f(T t, long);
//    void f(const A&, int);
//    void g() { f(A()); } // will call non-template
// \endcode
// In this example, the inline one-argument template will always be
// called, which will call the real function with an "int" passed to
// the second argument.  The templated two-argument function has a
// "long" second argument while the others have "int".  Therefore, the
// template will be chosen only if no non-templates match.
//
// The VCL_TEMPLATE_MATCHES_TOO_OFTEN macro is set to 1
// if this work-around is required and 0 otherwise.
//#define VCL_TEMPLATE_MATCHES_TOO_OFTEN 1 /* need work-around */
//#define VCL_TEMPLATE_MATCHES_TOO_OFTEN 0 /* do not need it */
#ifdef VCL_VC71                 // If C++.NET 2003 Version 7.1
# define VCL_TEMPLATE_MATCHES_TOO_OFTEN 0
#else
# define VCL_TEMPLATE_MATCHES_TOO_OFTEN 1
#endif

//: VCL_HAS_SLICED_DESTRUCTOR_BUG
//
// Consider this example code that creates a temporary in the call to f:
// \code
//  struct A { A(); A(const A&); ~A(); };
//  struct B: public A { B(); B(const B& b); ~B(); };
//  struct C { operator B(); };
//  void f(A);
//  void g(C c) { f(c); } // fails to call ~B() on 2nd temporary B
// \endcode
// Compilers will call c.operator B() to implement the conversion
// necessary to call f(c).  Some compilers will then create a
// temporary A by copy-constructing the temporary B to bind the
// argument of f.  Others will create a second temporary B by
// copy-constructing the first temporary B and bind the A-portion of
// the object to the argument of f.  Some compilers (at least Intel
// C++ 7.0 and 7.1) will create a second temporary B but forget to
// call ~B() when destroying it.  This can cause resource leaks.
//
// The VCL_HAS_SLICED_DESTRUCTOR_BUG is set to 1 if this bug exists in
// the compiler and 0 otherwise.
//#define VCL_HAS_SLICED_DESTRUCTOR_BUG 1 /* bug exists */
//#define VCL_HAS_SLICED_DESTRUCTOR_BUG 0 /* bug does not exist */
#define VCL_HAS_SLICED_DESTRUCTOR_BUG 0

//: VCL_NULL_TMPL_ARGS
//
// Define to <> for compilers that require them in friend template function
// declarations (i.e., EGCS, VC C++.NET 2003).

#ifdef VCL_VC71                 // If C++.NET 2003 Version 7.1
# define VCL_NULL_TMPL_ARGS <>
#else
# define VCL_NULL_TMPL_ARGS /* <> */
#endif

//----------------------------------------------------------------------
// template instantiation

//: VCL_ALLOWS_INLINE_INSTANTIATION
//
// True if the compiler allows explicit instantiation of inline
// function templates. The native SGI CC 7.2.1 does not.
#define VCL_ALLOWS_INLINE_INSTANTIATION 1

//: VCL_NEEDS_INLINE_INSTANTIATION
//
// True if the compiler needs explicit instantiation of inline
// function templates. gcc 2.7.2 (with -fno-implicit-templates) does.
#define VCL_NEEDS_INLINE_INSTANTIATION 0

//: VCL_DO_NOT_INSTANTIATE(text, ret)
//
// If a method is defined on some template, but makes no sense for some
// instances of that template, the compiler should not complain unless the
// method is actually used.  For example
// \code
//     template <class T>
//     class T {
//       int bad_method() {
//         return T::f();  // Requires T to have static method f
//       }
//     };
// \endcode
//
// The language allows you to use a T<int> even though int::f() is garbage,
// *providing* you never call T.bad_method().
//
// Most compilers don't implement that yet, so the solution is to provide a
// dummy specialization of T::bad_method that returns something mundane and
// stops the standard bad_method from being generated.  For this, use:
// \code
//     VCL_DO_NOT_INSTANTIATE(int T::bad_method(), some_return_value)
// \endcode
// if the function is void, use VCL_VOID_RETURN as the return value

//#define VCL_DO_NOT_INSTANTIATE(text, ret) text { return ret; }
//#define VCL_DO_NOT_INSTANTIATE(text, ret) template <> text { return ret; }
//#define VCL_DO_NOT_INSTANTIATE(text, ret) /* no need -- magic compiler */
//FIXME #define VCL_DO_NOT_INSTANTIATE(text, ret)
#define VCL_DO_NOT_INSTANTIATE(text, ret) \
VCL_DEFINE_SPECIALIZATION \
text { return ret; }

//: VCL_UNINSTANTIATE_SPECIALIZATION(symbol)
//
// OK, various compilers do various silly things about instantiation of
// functions/methods that have been specialized.  Use this macro to tell
// the compiler not to generate code for methods which have been specialized
// \code
//      VCL_UNINSTANTIATE_SPECIALIZATION(int T::specialized_method())
// \endcode
// It should be placed after the "template class A<T>;"

//#define VCL_UNINSTANTIATE_SPECIALIZATION(symbol)  @pragma do_not_instantiate text@
//#define VCL_UNINSTANTIATE_SPECIALIZATION(symbol) /* no need - sensible compiler */
//FIXME #define VCL_UNINSTANTIATE_SPECIALIZATION(symbol)
#define VCL_UNINSTANTIATE_SPECIALIZATION(symbol) // which compiler needs this ?

//: VCL_UNINSTANTIATE_UNSEEN_SPECIALIZATION(symbol)
//
// gcc is sensible about specializations if it has seen the definition,
// but if it's in another file, need to use extern to tell it.
// \code
//      VCL_UNINSTANTIATE_UNSEEN_SPECIALIZATION(int T::specialized_method())
// \endcode
// It should be placed before the "template class A<T>;"

//#define VCL_UNINSTANTIATE_UNSEEN_SPECIALIZATION(symbol) extern symbol;
//#define VCL_UNINSTANTIATE_UNSEEN_SPECIALIZATION(symbol) /* no need */
//FIXME #define VCL_UNINSTANTIATE_UNSEEN_SPECIALIZATION(symbol)
#define VCL_UNINSTANTIATE_UNSEEN_SPECIALIZATION(symbol) /* never used */

//: VCL_INSTANTIATE_STATIC_TEMPLATE_MEMBER(symbol)
//
// Some compilers (e.g. gcc 2.7.2) do not accept a templated definition
// of static members, as in
// \code
//   template <class T>
//   struct A {
//     A() { }
//     static char *fmt;
//   };
//
//   template <class T>
//   char *A<T>::fmt = 0;
//
//   template struct A<int>;
// \endcode
// The way round this is to supply an explicit definition for every
// instance of the class needed.
//
// Put the templated definition like this
// \code
//      #if VCL_CAN_DO_STATIC_TEMPLATE_MEMBER
//      template <class T>
//      char *A<T>::fmt = 0;
//      #endif
// \endcode
// and place
// \code
//      VCL_INSTANTIATE_STATIC_TEMPLATE_MEMBER(int A<int>::fmt = 0)
// \endcode
// before the
// \code
//      template class A<int>;
// \endcode
// with
// \code
//      VCL_UNINSTANTIATE_STATIC_TEMPLATE_MEMBER(A<int>::var)
// \endcode
// afterwards.

//#define VCL_INSTANTIATE_STATIC_TEMPLATE_MEMBER(symbol) /* no need */
//#define VCL_INSTANTIATE_STATIC_TEMPLATE_MEMBER(symbol) symbol;
//
#define VCL_CAN_DO_STATIC_TEMPLATE_MEMBER 1
#if VCL_CAN_DO_STATIC_TEMPLATE_MEMBER
# define VCL_INSTANTIATE_STATIC_TEMPLATE_MEMBER(symbol)   /* */
# define VCL_UNINSTANTIATE_STATIC_TEMPLATE_MEMBER(symbol) /* */
#else
# define VCL_INSTANTIATE_STATIC_TEMPLATE_MEMBER(symbol) symbol;
# define VCL_UNINSTANTIATE_STATIC_TEMPLATE_MEMBER(symbol) // which compiler needs this ?
#endif

//: VCL_CAN_DO_NON_TYPE_FUNCTION_TEMPLATE_PARAMETER
//
// Some compilers (e.g. SunPro 5.0) do not accept non-type template
// parameters in function templates. E.g.
// \code
// template <class T, int n> struct vicky { T data[n]; } // can do
//
// template <class T, int n>
// void a_function_template(vicky<T, n> const &) { ... } // cannot
// \endcode
#define VCL_CAN_DO_NON_TYPE_FUNCTION_TEMPLATE_PARAMETER 1

//----------------------------------------------------------------------
// overload resolution problems.

//: VCL_NEED_FRIEND_FOR_TEMPLATE_OVERLOAD
//
// On some compilers (in particular gcc 2.7.2.3), the compiler doesn't
// know how to cast a templated derived class to a templated base class
// (eg. vnl_matrix_fixed<3,3,double> -> vnl_matrix<double>) when doing overload
// resolution. Making the overloaded function a friend of the class makes
// the problem go away.
//
// True if the compiler needs this hack.

//#define VCL_NEED_FRIEND_FOR_TEMPLATE_OVERLOAD 0
//#define VCL_NEED_FRIEND_FOR_TEMPLATE_OVERLOAD 1
#define VCL_NEED_FRIEND_FOR_TEMPLATE_OVERLOAD 0

//: VCL_OVERLOAD_CAST
//
// Some compilers (gcc 2.7.2.3 and SGI native 6.0) often won't perform
// certain implicit casts. E.g. casting a templated derived class to a
// templated base class (see above), or even realizing that
// "template void foo(float const * const *, float * const *, int, int)"
// can be called with parameters of type "(float **, float **, int, int)".
//
//   To fix the code, it is tempting to add an explicit cast and get on
// with things, but that would throw away the checking performed by more
// helpful compilers. Use VCL_OVERLOAD_CAST instead.

//#define VCL_OVERLOAD_CAST(T, x) ((T)(x))
//#define VCL_OVERLOAD_CAST(T, x) (x)
#define VCL_OVERLOAD_CAST(T, x) (x)

//----------------------------------------------------------------------
// stuff

//: VCL_NO_STATIC_DATA_MEMBERS
//
// True if compiler does not support static data members in template classes.
//
#define VCL_NO_STATIC_DATA_MEMBERS 0

//: VCL_HAS_TEMPLATE_SYMBOLS
//
// True if the compiler mangles function template instances differently
// from non-templated functions with the same name and signature.
// This is correct behaviour.
//
#define VCL_HAS_TEMPLATE_SYMBOLS 0

//----------------------------------------------------------------------
// default template arguments

//: VCL_DEFAULT_TMPL_ARG(arg)
//
// It is wrong to provide a default for a template parameter in two
// declarations in the same scope (14.1.12), e.g.
// \code
//   template <class S, class T = int> class X;
//   template <class S, class T = int> class X { /* ... */ };
// \endcode
// is wrong.
// However, some older compilers insist on seeing the default argument
// again when defining a class body or instantiating.
// To satisfy them, use this macro as follows :
// \code
//   template <class S, class T VCL_DEFAULT_TMPL_ARG(= int)> X { /* ... */ };
//   template X<double VCL_DEFAULT_TMPL_ARG(, int)>;
// \endcode
//
// It's possible we need two macros, one for redeclaration and
// one for instantiation.

//#define VCL_DEFAULT_TMPL_ARG(arg) /* no need */
//#define VCL_DEFAULT_TMPL_ARG(arg) arg
#define VCL_DEFAULT_TMPL_ARG(arg)

//
#define VCL_CAN_DO_COMPLETE_DEFAULT_TYPE_PARAMETER 1
#define VCL_CAN_DO_TEMPLATE_DEFAULT_TYPE_PARAMETER 1

// VCL_DFL_TYPE_PARAM_STLDECL(A, a) and VCL_DFL_TMPL_PARAM_STLDECL(A, a)
// EGCS doesn't like definition of default types, viz:
// \code
//   template <class A = default> class vector;
//   template <class A = default> class vector { ... };
// \endcode
// This macro is used to say "define if not previously defined, like
// \code
//   template <VCL_DFL_TYPE_PARAM_STLDECL(A,a)> class vector { ... };
// \endcode

//#define VCL_DFL_TYPE_PARAM_STLDECL(A,a) A = a
//#define VCL_DFL_TYPE_PARAM_STLDECL(A,a) A /* = a */
//#define VCL_DFL_TYPE_PARAM_STLDECL(A,a) __DFL_TYPE_PARAM(A,a)
//FIXME #define VCL_DFL_TYPE_PARAM_STLDECL(A,a)
//
//#define VCL_DFL_TMPL_PARAM_STLDECL(A,a) A = a
//#define VCL_DFL_TMPL_PARAM_STLDECL(A,a) A /* = a */
//#define VCL_DFL_TMPL_PARAM_STLDECL(A,a) __STL_DFL_TMPL_PARAM(A,a)
//FIXME #define VCL_DFL_TMPL_PARAM_STLDECL(A,a)

// VCL_DFL_TMPL_ARG(class)
// Similarly, when instantiating a templated class with a default
// template argument, some compilers don't like the redeclaration of
// that argument, while others insist on it.
// In such cases, specify the default argument as follows:
// \code
//   template class vector <int VCL_DFL_TMPL_ARG(default_iterator) >;
// \endcode
// (Note the missing comma after int: it is inside the macro.)

//#define VCL_DFL_TMPL_ARG(classname) , classname
//#define VCL_DFL_TMPL_ARG(classname) /* , classname */
//#define VCL_DFL_TMPL_ARG(classname) __DFL_TMPL_ARG(classname)
//FIXME #define VCL_DFL_TMPL_ARG(classname)

//: VCL_SUNPRO_CLASS_SCOPE_HACK(A)
//
// Nice one.  Can't use std::vector<T> in a class on SunPro 5, must use
// std::vector<T, std::allocator<T> >.  Of course, we cannot expect that other
// compilers call the default allocator std::allocator<T>, so we must use
// a macro.  I could call it something generic, like
// VCL_CLASS_SCOPE_HACK, but to be honest, it's a sunpro problem,
// they deserve the blame.
// Usage (the comma is inside the macro) :
// \code
//    vector<T VCL_SUNPRO_CLASS_SCOPE_HACK(std::allocator<T >)>
// \endcode

//#define VCL_SUNPRO_CLASS_SCOPE_HACK(A) /* , A */
//#define VCL_SUNPRO_CLASS_SCOPE_HACK(A) , A
#define VCL_SUNPRO_CLASS_SCOPE_HACK(A) /* , A */

//----------------------------------------------------------------------
// exception and namespace issues

//: VCL_HAS_EXCEPTIONS
// Set to true if the compiler supports the use of exceptions.
#define VCL_HAS_EXCEPTIONS 1

//: VCL_HAS_NAMESPACES
// Set to true if the compiler supports the use of namespaces.
#define VCL_HAS_NAMESPACES 1

//: VCL_ALLOWS_NAMESPACE_STD
// Set to true if the compiler allows namespace std:: for the standard library.
// !!! different from VC6
#define VCL_ALLOWS_NAMESPACE_STD 1

//: VCL_NEEDS_NAMESPACE_STD
// Set to true if the compiler needs namespace std:: for the standard library.
// !!! different from VC6
#define VCL_NEEDS_NAMESPACE_STD 1

//----------------------------------------------------------------------
// infinity issues

//: VCL_NUMERIC_LIMITS_HAS_INFINITY
// Set to true if there is a numeric_limits and it reports having a floating point infinity.
#define VCL_NUMERIC_LIMITS_HAS_INFINITY 1

//: VCL_PROCESSOR_HAS_INFINITY
// Set to true if the processor really does have an infinity.
// Although this is strictly not a C++ issue, some platforms' versions of
// numeric_limits<double> imply that there is no infinity, when there is.
#define VCL_PROCESSOR_HAS_INFINITY 1

//----------------------------------------------------------------------
// signedness of char

//: VCL_CHAR_IS_SIGNED
// Set to true if the type "char" is signed.
#define VCL_CHAR_IS_SIGNED 1

//----------------------------------------------------------------------

// architecture macros removed -- they're not in the C++ standard

#endif // vcl_config_compiler_h_config_win32_vc70_


text:
#include "avro_private.h"
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <dirent.h>

int test_cases = 0;
avro_writer_t avro_stderr;

static void run_tests(char *dirpath, int should_pass)
{
	char jsontext[4096];
	size_t jsonlen, rval;
	char filepath[1024];
	DIR *dir;
	struct dirent *dent;
	FILE *fp;
	avro_schema_t schema;
	avro_schema_error_t avro_schema_error;

	dir = opendir(dirpath);
	if (dir == NULL) {
		fprintf(stderr, "Unable to open '%s'\n", dirpath);
		exit(EXIT_FAILURE);
	}
	do {
		dent = readdir(dir);
		if (dent && dent->d_name[0] != '.') {
			int test_rval;
			snprintf(filepath, sizeof(filepath), "%s/%s", dirpath,
				 dent->d_name);
			fprintf(stderr, "TEST %s...", filepath);
			jsonlen = 0;
			fp = fopen(filepath, "r");
			if (!fp) {
				fprintf(stderr, "can't open!\n");
				exit(EXIT_FAILURE);
			}
			rval = fread(jsontext, 1, sizeof(jsontext) - 1, fp);
			jsontext[rval] = '\0';
			test_rval =
			    avro_schema_from_json(jsontext, jsonlen, &schema,
						  &avro_schema_error);
			test_cases++;
			if (test_rval == 0) {
				if (should_pass) {
					avro_schema_t schema_copy =
					    avro_schema_copy(schema);
					fprintf(stderr, "pass\n");
					avro_schema_to_json(schema,
							    avro_stderr);
					fprintf(stderr, "\n");
					if (!avro_schema_equal
					    (schema, schema_copy)) {
						fprintf(stderr,
							"failed to avro_schema_equal(schema,avro_schema_copy())\n");
						exit(EXIT_FAILURE);
					}
					avro_schema_decref(schema_copy);
					avro_schema_decref(schema);
				} else {
					/*
					 * Unexpected success
					 */
					fprintf(stderr,
						"fail! (shouldn't succeed but did)\n");
					exit(EXIT_FAILURE);
				}
			} else {
				if (should_pass) {
					fprintf(stderr,
						"fail! (should have succeeded but didn't)\n");
					exit(EXIT_FAILURE);
				} else {
					fprintf(stderr, "pass\n");
				}
			}
		}
	}
	while (dent != NULL);
}

int main(int argc, char *argv[])
{
	char *srcdir = getenv("srcdir");
	char path[1024];

	AVRO_UNUSED(argc);
	AVRO_UNUSED(argv);

	if (!srcdir) {
		srcdir = ".";
	}

	avro_stderr = avro_writer_file(stderr);

	/*
	 * Run the tests that should pass
	 */
	snprintf(path, sizeof(path), "%s/schema_tests/pass", srcdir);
	fprintf(stderr, "RUNNING %s\n", path);
	run_tests(path, 1);
	snprintf(path, sizeof(path), "%s/schema_tests/fail", srcdir);
	fprintf(stderr, "RUNNING %s\n", path);
	run_tests(path, 0);

	fprintf(stderr, "==================================================\n");
	fprintf(stderr,
		"Finished running %d schema test cases successfully \n",
		test_cases);
	fprintf(stderr, "==================================================\n");

	avro_writer_free(avro_stderr);
	return EXIT_SUCCESS;
}