text:
import { css, cx } from '@emotion/css';
import React, { ChangeEvent } from 'react';
import { FixedSizeList } from 'react-window';

import { GrafanaTheme } from '@grafana/data';
import {
  Button,
  HorizontalGroup,
  Input,
  Label,
  LoadingPlaceholder,
  stylesFactory,
  withTheme,
  BrowserLabel as PromLabel,
} from '@grafana/ui';

import PromQlLanguageProvider from '../language_provider';
import { escapeLabelValueInExactSelector, escapeLabelValueInRegexSelector } from '../language_utils';

// Hard limit on labels to render
const EMPTY_SELECTOR = '{}';
const METRIC_LABEL = '__name__';
const LIST_ITEM_SIZE = 25;

export interface BrowserProps {
  languageProvider: PromQlLanguageProvider;
  onChange: (selector: string) => void;
  theme: GrafanaTheme;
  autoSelect?: number;
  hide?: () => void;
  lastUsedLabels: string[];
  storeLastUsedLabels: (labels: string[]) => void;
  deleteLastUsedLabels: () => void;
}

interface BrowserState {
  labels: SelectableLabel[];
  labelSearchTerm: string;
  metricSearchTerm: string;
  status: string;
  error: string;
  validationStatus: string;
  valueSearchTerm: string;
}

interface FacettableValue {
  name: string;
  selected?: boolean;
  details?: string;
}

export interface SelectableLabel {
  name: string;
  selected?: boolean;
  loading?: boolean;
  values?: FacettableValue[];
  hidden?: boolean;
  facets?: number;
}

export function buildSelector(labels: SelectableLabel[]): string {
  let singleMetric = '';
  const selectedLabels = [];
  for (const label of labels) {
    if ((label.name === METRIC_LABEL || label.selected) && label.values && label.values.length > 0) {
      const selectedValues = label.values.filter((value) => value.selected).map((value) => value.name);
      if (selectedValues.length > 1) {
        selectedLabels.push(`${label.name}=~"${selectedValues.map(escapeLabelValueInRegexSelector).join('|')}"`);
      } else if (selectedValues.length === 1) {
        if (label.name === METRIC_LABEL) {
          singleMetric = selectedValues[0];
        } else {
          selectedLabels.push(`${label.name}="${escapeLabelValueInExactSelector(selectedValues[0])}"`);
        }
      }
    }
  }
  return [singleMetric, '{', selectedLabels.join(','), '}'].join('');
}

export function facetLabels(
  labels: SelectableLabel[],
  possibleLabels: Record<string, string[]>,
  lastFacetted?: string
): SelectableLabel[] {
  return labels.map((label) => {
    const possibleValues = possibleLabels[label.name];
    if (possibleValues) {
      let existingValues: FacettableValue[];
      if (label.name === lastFacetted && label.values) {
        // Facetting this label, show all values
        existingValues = label.values;
      } else {
        // Keep selection in other facets
        const selectedValues: Set<string> = new Set(
          label.values?.filter((value) => value.selected).map((value) => value.name) || []
        );
        // Values for this label have not been requested yet, let's use the facetted ones as the initial values
        existingValues = possibleValues.map((value) => ({ name: value, selected: selectedValues.has(value) }));
      }
      return {
        ...label,
        loading: false,
        values: existingValues,
        hidden: !possibleValues,
        facets: existingValues.length,
      };
    }

    // Label is facetted out, hide all values
    return { ...label, loading: false, hidden: !possibleValues, values: undefined, facets: 0 };
  });
}

const getStyles = stylesFactory((theme: GrafanaTheme) => ({
  wrapper: css`
    background-color: ${theme.colors.bg2};
    padding: ${theme.spacing.sm};
    width: 100%;
  `,
  list: css`
    margin-top: ${theme.spacing.sm};
    display: flex;
    flex-wrap: wrap;
    max-height: 200px;
    overflow: auto;
    align-content: flex-start;
  `,
  section: css`
    & + & {
      margin: ${theme.spacing.md} 0;
    }
    position: relative;
  `,
  selector: css`
    font-family: ${theme.typography.fontFamily.monospace};
    margin-bottom: ${theme.spacing.sm};
  `,
  status: css`
    padding: ${theme.spacing.xs};
    color: ${theme.colors.textSemiWeak};
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    /* using absolute positioning because flex interferes with ellipsis */
    position: absolute;
    width: 50%;
    right: 0;
    text-align: right;
    transition: opacity 100ms linear;
    opacity: 0;
  `,
  statusShowing: css`
    opacity: 1;
  `,
  error: css`
    color: ${theme.palette.brandDanger};
  `,
  valueList: css`
    margin-right: ${theme.spacing.sm};
  `,
  valueListWrapper: css`
    border-left: 1px solid ${theme.colors.border2};
    margin: ${theme.spacing.sm} 0;
    padding: ${theme.spacing.sm} 0 ${theme.spacing.sm} ${theme.spacing.sm};
  `,
  valueListArea: css`
    display: flex;
    flex-wrap: wrap;
    margin-top: ${theme.spacing.sm};
  `,
  valueTitle: css`
    margin-left: -${theme.spacing.xs};
    margin-bottom: ${theme.spacing.sm};
  `,
  validationStatus: css`
    padding: ${theme.spacing.xs};
    margin-bottom: ${theme.spacing.sm};
    color: ${theme.colors.textStrong};
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  `,
}));

/**
 * TODO #33976: Remove duplicated code. The component is very similar to LokiLabelBrowser.tsx. Check if it's possible
 *              to create a single, generic component.
 */
export class UnthemedPrometheusMetricsBrowser extends React.Component<BrowserProps, BrowserState> {
  valueListsRef = React.createRef<HTMLDivElement>();
  state: BrowserState = {
    labels: [] as SelectableLabel[],
    labelSearchTerm: '',
    metricSearchTerm: '',
    status: 'Ready',
    error: '',
    validationStatus: '',
    valueSearchTerm: '',
  };

  onChangeLabelSearch = (event: ChangeEvent<HTMLInputElement>) => {
    this.setState({ labelSearchTerm: event.target.value });
  };

  onChangeMetricSearch = (event: ChangeEvent<HTMLInputElement>) => {
    this.setState({ metricSearchTerm: event.target.value });
  };

  onChangeValueSearch = (event: ChangeEvent<HTMLInputElement>) => {
    this.setState({ valueSearchTerm: event.target.value });
  };

  onClickRunQuery = () => {
    const selector = buildSelector(this.state.labels);
    this.props.onChange(selector);
  };

  onClickRunRateQuery = () => {
    const selector = buildSelector(this.state.labels);
    const query = `rate(${selector}[$__interval])`;
    this.props.onChange(query);
  };

  onClickClear = () => {
    this.setState((state) => {
      const labels: SelectableLabel[] = state.labels.map((label) => ({
        ...label,
        values: undefined,
        selected: false,
        loading: false,
        hidden: false,
        facets: undefined,
      }));
      return {
        labels,
        labelSearchTerm: '',
        metricSearchTerm: '',
        status: '',
        error: '',
        validationStatus: '',
        valueSearchTerm: '',
      };
    });
    this.props.deleteLastUsedLabels();
    // Get metrics
    this.fetchValues(METRIC_LABEL, EMPTY_SELECTOR);
  };

  onClickLabel = (name: string, value: string | undefined, event: React.MouseEvent<HTMLElement>) => {
    const label = this.state.labels.find((l) => l.name === name);
    if (!label) {
      return;
    }
    // Toggle selected state
    const selected = !label.selected;
    let nextValue: Partial<SelectableLabel> = { selected };
    if (label.values && !selected) {
      // Deselect all values if label was deselected
      const values = label.values.map((value) => ({ ...value, selected: false }));
      nextValue = { ...nextValue, facets: 0, values };
    }
    // Resetting search to prevent empty results
    this.setState({ labelSearchTerm: '' });
    this.updateLabelState(name, nextValue, '', () => this.doFacettingForLabel(name));
  };

  onClickValue = (name: string, value: string | undefined, event: React.MouseEvent<HTMLElement>) => {
    const label = this.state.labels.find((l) => l.name === name);
    if (!label || !label.values) {
      return;
    }
    // Resetting search to prevent empty results
    this.setState({ labelSearchTerm: '' });
    // Toggling value for selected label, leaving other values intact
    const values = label.values.map((v) => ({ ...v, selected: v.name === value ? !v.selected : v.selected }));
    this.updateLabelState(name, { values }, '', () => this.doFacetting(name));
  };

  onClickMetric = (name: string, value: string | undefined, event: React.MouseEvent<HTMLElement>) => {
    // Finding special metric label
    const label = this.state.labels.find((l) => l.name === name);
    if (!label || !label.values) {
      return;
    }
    // Resetting search to prevent empty results
    this.setState({ metricSearchTerm: '' });
    // Toggling value for selected label, leaving other values intact
    const values = label.values.map((v) => ({
      ...v,
      selected: v.name === value || v.selected ? !v.selected : v.selected,
    }));
    // Toggle selected state of special metrics label
    const selected = values.some((v) => v.selected);
    this.updateLabelState(name, { selected, values }, '', () => this.doFacetting(name));
  };

  onClickValidate = () => {
    const selector = buildSelector(this.state.labels);
    this.validateSelector(selector);
  };

  updateLabelState(name: string, updatedFields: Partial<SelectableLabel>, status = '', cb?: () => void) {
    this.setState((state) => {
      const labels: SelectableLabel[] = state.labels.map((label) => {
        if (label.name === name) {
          return { ...label, ...updatedFields };
        }
        return label;
      });
      // New status overrides errors
      const error = status ? '' : state.error;
      return { labels, status, error, validationStatus: '' };
    }, cb);
  }

  componentDidMount() {
    const { languageProvider, lastUsedLabels } = this.props;
    if (languageProvider) {
      const selectedLabels: string[] = lastUsedLabels;
      languageProvider.start().then(() => {
        let rawLabels: string[] = languageProvider.getLabelKeys();
        // Get metrics
        this.fetchValues(METRIC_LABEL, EMPTY_SELECTOR);
        // Auto-select previously selected labels
        const labels: SelectableLabel[] = rawLabels.map((label, i, arr) => ({
          name: label,
          selected: selectedLabels.includes(label),
          loading: false,
        }));
        // Pre-fetch values for selected labels
        this.setState({ labels }, () => {
          this.state.labels.forEach((label) => {
            if (label.selected) {
              this.fetchValues(label.name, EMPTY_SELECTOR);
            }
          });
        });
      });
    }
  }

  doFacettingForLabel(name: string) {
    const label = this.state.labels.find((l) => l.name === name);
    if (!label) {
      return;
    }
    const selectedLabels = this.state.labels.filter((label) => label.selected).map((label) => label.name);
    this.props.storeLastUsedLabels(selectedLabels);
    if (label.selected) {
      // Refetch values for newly selected label...
      if (!label.values) {
        this.fetchValues(name, buildSelector(this.state.labels));
      }
    } else {
      // Only need to facet when deselecting labels
      this.doFacetting();
    }
  }

  doFacetting = (lastFacetted?: string) => {
    const selector = buildSelector(this.state.labels);
    if (selector === EMPTY_SELECTOR) {
      // Clear up facetting
      const labels: SelectableLabel[] = this.state.labels.map((label) => {
        return { ...label, facets: 0, values: undefined, hidden: false };
      });
      this.setState({ labels }, () => {
        // Get fresh set of values
        this.state.labels.forEach(
          (label) => (label.selected || label.name === METRIC_LABEL) && this.fetchValues(label.name, selector)
        );
      });
    } else {
      // Do facetting
      this.fetchSeries(selector, lastFacetted);
    }
  };

  async fetchValues(name: string, selector: string) {
    const { languageProvider } = this.props;
    this.updateLabelState(name, { loading: true }, `Fetching values for ${name}`);
    try {
      let rawValues = await languageProvider.getLabelValues(name);
      // If selector changed, clear loading state and discard result by returning early
      if (selector !== buildSelector(this.state.labels)) {
        this.updateLabelState(name, { loading: false });
        return;
      }
      const values: FacettableValue[] = [];
      const { metricsMetadata } = languageProvider;
      for (const labelValue of rawValues) {
        const value: FacettableValue = { name: labelValue };
        // Adding type/help text to metrics
        if (name === METRIC_LABEL && metricsMetadata) {
          const meta = metricsMetadata[labelValue];
          if (meta) {
            value.details = `(${meta.type}) ${meta.help}`;
          }
        }
        values.push(value);
      }
      this.updateLabelState(name, { values, loading: false });
    } catch (error) {
      console.error(error);
    }
  }

  async fetchSeries(selector: string, lastFacetted?: string) {
    const { languageProvider } = this.props;
    if (lastFacetted) {
      this.updateLabelState(lastFacetted, { loading: true }, `Facetting labels for ${selector}`);
    }
    try {
      const possibleLabels = await languageProvider.fetchSeriesLabels(selector, true);
      // If selector changed, clear loading state and discard result by returning early
      if (selector !== buildSelector(this.state.labels)) {
        if (lastFacetted) {
          this.updateLabelState(lastFacetted, { loading: false });
        }
        return;
      }
      if (Object.keys(possibleLabels).length === 0) {
        this.setState({ error: `Empty results, no matching label for ${selector}` });
        return;
      }
      const labels: SelectableLabel[] = facetLabels(this.state.labels, possibleLabels, lastFacetted);
      this.setState({ labels, error: '' });
      if (lastFacetted) {
        this.updateLabelState(lastFacetted, { loading: false });
      }
    } catch (error) {
      console.error(error);
    }
  }

  async validateSelector(selector: string) {
    const { languageProvider } = this.props;
    this.setState({ validationStatus: `Validating selector ${selector}`, error: '' });
    const streams = await languageProvider.fetchSeries(selector);
    this.setState({ validationStatus: `Selector is valid (${streams.length} series found)` });
  }

  render() {
    const { theme } = this.props;
    const { labels, labelSearchTerm, metricSearchTerm, status, error, validationStatus, valueSearchTerm } = this.state;
    const styles = getStyles(theme);
    if (labels.length === 0) {
      return (

          <LoadingPlaceholder text="Loading labels..." />

      );
    }

    // Filter metrics
    let metrics = labels.find((label) => label.name === METRIC_LABEL);
    if (metrics && metricSearchTerm) {
      metrics = {
        ...metrics,
        values: metrics.values?.filter((value) => value.selected || value.name.includes(metricSearchTerm)),
      };
    }

    // Filter labels
    let nonMetricLabels = labels.filter((label) => !label.hidden && label.name !== METRIC_LABEL);
    if (labelSearchTerm) {
      nonMetricLabels = nonMetricLabels.filter((label) => label.selected || label.name.includes(labelSearchTerm));
    }

    // Filter non-metric label values
    let selectedLabels = nonMetricLabels.filter((label) => label.selected && label.values);
    if (valueSearchTerm) {
      selectedLabels = selectedLabels.map((label) => ({
        ...label,
        values: label.values?.filter((value) => value.selected || value.name.includes(valueSearchTerm)),
      }));
    }
    const selector = buildSelector(this.state.labels);
    const empty = selector === EMPTY_SELECTOR;
    const metricCount = metrics?.values?.length || 0;

    return (

        <HorizontalGroup align="flex-start" spacing="lg">

              1. Select a metric

                <Input
                  onChange={this.onChangeMetricSearch}
                  aria-label="Filter expression for metric"
                  value={metricSearchTerm}
                />

                <FixedSizeList
                  height={Math.min(450, metricCount * LIST_ITEM_SIZE)}
                  itemCount={metricCount}
                  itemSize={LIST_ITEM_SIZE}
                  itemKey={(i) => (metrics!.values as FacettableValue[])[i].name}
                  width={300}
                  className={styles.valueList}
                >
                  {({ index, style }) => {
                    const value = metrics?.values?.[index];
                    if (!value) {
                      return null;
                    }
                    return (

                        <PromLabel
                          name={metrics!.name}
                          value={value?.name}
                          title={value.details}
                          active={value?.selected}
                          onClick={this.onClickMetric}
                          searchTerm={metricSearchTerm}
                        />

                    );
                  }}
                </FixedSizeList>

                2. Select labels to search in

                <Input
                  onChange={this.onChangeLabelSearch}
                  aria-label="Filter expression for label"
                  value={labelSearchTerm}
                />

              {/* Using fixed height here to prevent jumpy layout */}

                {nonMetricLabels.map((label) => (
                  <PromLabel
                    key={label.name}
                    name={label.name}
                    loading={label.loading}
                    active={label.selected}
                    hidden={label.hidden}
                    facets={label.facets}
                    onClick={this.onClickLabel}
                    searchTerm={labelSearchTerm}
                  />
                ))}

                3. Select (multiple) values for your labels

                <Input
                  onChange={this.onChangeValueSearch}
                  aria-label="Filter expression for label values"
                  value={valueSearchTerm}
                />

                {selectedLabels.map((label) => (
                  <div
                    role="list"
                    key={label.name}
                    aria-label={`Values for ${label.name}`}
                    className={styles.valueListWrapper}
                  >

                      <PromLabel
                        name={label.name}
                        loading={label.loading}
                        active={label.selected}
                        hidden={label.hidden}
                        //If no facets, we want to show number of all label values
                        facets={label.facets || label.values?.length}
                        onClick={this.onClickLabel}
                      />

                    <FixedSizeList
                      height={Math.min(200, LIST_ITEM_SIZE * (label.values?.length || 0))}
                      itemCount={label.values?.length || 0}
                      itemSize={28}
                      itemKey={(i) => (label.values as FacettableValue[])[i].name}
                      width={200}
                      className={styles.valueList}
                    >
                      {({ index, style }) => {
                        const value = label.values?.[index];
                        if (!value) {
                          return null;
                        }
                        return (

                            <PromLabel
                              name={label.name}
                              value={value?.name}
                              active={value?.selected}
                              onClick={this.onClickValue}
                              searchTerm={valueSearchTerm}
                            />

                        );
                      }}
                    </FixedSizeList>

                ))}

        </HorizontalGroup>

          4. Resulting selector

            {selector}

          {validationStatus &&
{validationStatus}
}
          <HorizontalGroup>
            <Button aria-label="Use selector for query button" disabled={empty} onClick={this.onClickRunQuery}>
              Use query
            </Button>
            <Button
              aria-label="Use selector as metrics button"
              variant="secondary"
              disabled={empty}
              onClick={this.onClickRunRateQuery}
            >
              Use as rate query
            </Button>
            <Button
              aria-label="Validate submit button"
              variant="secondary"
              disabled={empty}
              onClick={this.onClickValidate}
            >
              Validate selector
            </Button>
            <Button aria-label="Selector clear button" variant="secondary" onClick={this.onClickClear}>
              Clear
            </Button>

              {error || status}

          </HorizontalGroup>

    );
  }
}

export const PrometheusMetricsBrowser = withTheme(UnthemedPrometheusMetricsBrowser);


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

	<link rel="stylesheet" href="./lib/qunit.css" type="text/css" media="screen" />

Crafty: Events

test markup, will be hidden

redpajama_set_name: RedPajamaGithub


text:
====================================================================================
Copyright (c) 2015 Barry Carter <barry.carter@gmail.com>

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

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

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

A simple GUI Widget library for TFT screens.
====================================================================================

What
----

This is a library that allows you to draw simple widgets onto the screen in the
simplest possible way.
There are simple yet powerful grid and list layout options to let you get
working straight away. Multiple screens of information are available by
placing widgets on panels, and making the page you want to see visible, and the
rest invisible.
Callback functions can be used to trigger page changes, code execution or
anything you want to do in your sketch.

Requires:
* Adafruit TFT and Adafruid GFX library
* Touch input library
* SdFat (for optional image support)

Supported widgets
* Label
* Panel
* Button
* Radio Group
* Checkbox
* ListBox
* Multi Line Text Box
* Image Box

Supported layout widgets
* Grid view (with rowspan and colspan)
* List views that auto place the elements
* Just place the widget where you want using x and y

supported features
* Widget margins and padding
* Text size and alignment (only one shitty font)
* Element borders
* Element background colours and font colours
* Icons for buttons
* Press/unpress states (where supported)
* Callback functions for element actions (press, release etc)
* Colours (background, border etc) are specified in normal good ol' RGB
* Easily create your own widget elements

Bad things
* While every effort has been made to keep this lightweight, it just isn't.
  The library may not fit on an Arduino, tests required.
* Sometimes the elements on the scren overdraw. There is 0 dame detection
  and redraws in the library are crafted to keep redrawing while elements low
* The drawing engine is pretty dumb. If the text is bigger than your element,
  it will overflow. You will have to work that one out yourself for now.
* There is no other input except for touchscreen. You can't move around your
  widgets with a joystick, say.
* It isn't going to win any screen redraw speed awards
* No scrollbars I guess thats up to you for a little while.

TODO:
* The header is a bit monolithic. It screams for a refactor
* Those linked lists could probably be thinned down
* you can't delete an element. Sorry!
* Scrollbars
* more fonts?
* Now we have primitives, some shiny widgets.
  * Progress bar
  * Dials
  * Etc

Example:
There are lots of examples int he examples folder.

Here is the minimum you need to get going

#include "GuiLibrary.h"
...
// Set our main window.
Gui gui(&tft, &ts, 0, 0, tft.height(), tft.width());

void setup() {
    GuiLabel *label = new GuiLabel(0, 0, 50, 30, "Hello World!");
    gui.addChild(label);
    gui.draw(); // set first draw going
}

Custom Widget:
You can create your own widgets really easily by taking on the attributes of another element and overriding it. This is called subclassing.

Example, lets create a new label that draws a line through the centre.

// create a new label of type GuiLabel and override the draw
class GuiLabelLine : public GuiLabel {
public:
    GuiLabelLine(int16_t x, int16_t y, int16_t width, int16_t height, char const* text) : GuiLabel(x, y, width, height, text) { };

    // This is the only function we need!
    void draw(void);
};

void GuiLabelLine::draw() {
    if (!visible()) return;

    // we want to draw the outlines and whatnot
    GuiElement::drawBase();

    GuiUtils::drawLine(absoluteX(), GuiUtils::getElementCentreY(), absoluteX() + width, GuiUtils::getElementCentreY(), GuiUtils::getColour(255, 0, 0));

    // draw the normal label
    GuiLabel::draw(false);
}

//////////////////////////


text:
package com.example.zhangqz.coolweather.db;

import org.litepal.crud.DataSupport;

/**
 * Created by zhangqz on 2017/7/27.
 */

public class City extends DataSupport {
    private int id; // 这个是主键id ,不能改名,如使用 mId 则相当于多了一个列 "mid"
    private String mName;
    private int mCode;
    private int mProvinceId;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return mName;
    }

    public void setName(String name) {
        mName = name;
    }

    public int getCode() {
        return mCode;
    }

    public void setCode(int code) {
        mCode = code;
    }

    public int getProvinceId() {
        return mProvinceId;
    }

    public void setProvinceId(int provinceId) {
        mProvinceId = provinceId;
    }
}


text:
CREATE PROCEDURE [dbo].[netsqlazman_RevokeApplicationAccess] (
	@ApplicationId int,
	@SqlUserOrRole sysname,
	@NetSqlAzManFixedServerRole tinyint)
AS
DECLARE @StoreId int
SET @StoreId = (SELECT StoreId FROM dbo.[netsqlazman_Applications]() WHERE ApplicationId = @ApplicationId)
IF EXISTS(SELECT ApplicationId FROM dbo.[netsqlazman_ApplicationsTable] WHERE ApplicationId = @ApplicationId) AND (dbo.[netsqlazman_CheckApplicationPermissions](@ApplicationId, 2) = 1 AND @NetSqlAzManFixedServerRole BETWEEN 0 AND 1 OR dbo.[netsqlazman_CheckStorePermissions](@StoreId, 2) = 1 AND @NetSqlAzManFixedServerRole = 2)
BEGIN
	IF EXISTS(SELECT * FROM dbo.[netsqlazman_ApplicationPermissionsTable] WHERE ApplicationId = @ApplicationId AND SqlUserOrRole = @SqlUserOrRole AND NetSqlAzManFixedServerRole = @NetSqlAzManFixedServerRole)
		DELETE FROM dbo.[netsqlazman_ApplicationPermissionsTable] WHERE ApplicationId = @ApplicationId AND SqlUserOrRole = @SqlUserOrRole AND NetSqlAzManFixedServerRole = @NetSqlAzManFixedServerRole
	ELSE
		RAISERROR ('Permission not found. Revoke Application Access ignored.', -1, -1)
END
ELSE
	RAISERROR ('Application NOT Found or Application permission denied.', 16, 1)

GO
GRANT EXECUTE
    ON OBJECT::[dbo].[netsqlazman_RevokeApplicationAccess] TO [NetSqlAzMan_Managers]
    AS [dbo];


text:
package org.wso2.carbon.identity.mgt.store;

import org.wso2.carbon.identity.base.IdentityException;
import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil;
import org.wso2.carbon.identity.core.util.IdentityTenantUtil;
import org.wso2.carbon.identity.mgt.dto.IdentityMetadataDO;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * This class is used to access the identity metadata. Schema of the identity
 * metadata is as follows :
 * ====================================================
 * ||UserName|TenantID|MetadataType|Metadata|Valid||
 * ====================================================
 */
public class UserIdentityMetadataStore {

    /**
     * Set the validity to invalid
     *
     * @param metadata       TODO
     * @param tempCredential
     * @throws IdentityException
     */
    public void invalidateMetadata(IdentityMetadataDO metadata) throws IdentityException {
        Connection connection = IdentityDatabaseUtil.getDBConnection();
        PreparedStatement prepStmt = null;
        try {
            prepStmt = connection.prepareStatement(SQLQuery.INVALIDATE_METADATA);
            prepStmt.setString(1, metadata.getUserName());
            prepStmt.setInt(2, metadata.getTenantId());
            prepStmt.setString(3, metadata.getMetadataType());
            prepStmt.setString(4, metadata.getMetadata());
            prepStmt.execute();
            IdentityDatabaseUtil.commitTransaction(connection);
        } catch (SQLException e) {
            IdentityDatabaseUtil.rollbackTransaction(connection);
            throw IdentityException.error("Error while storing user identity data", e);
        } finally {
            IdentityDatabaseUtil.closeStatement(prepStmt);
            IdentityDatabaseUtil.closeConnection(connection);
        }
    }

    /**
     * @param metadataSet
     * @throws IdentityException
     */
    public void invalidateMetadataSet(IdentityMetadataDO[] metadataSet) throws IdentityException {
        Connection connection = IdentityDatabaseUtil.getDBConnection();
        PreparedStatement prepStmt = null;
        try {
            prepStmt = connection.prepareStatement(SQLQuery.INVALIDATE_METADATA);
            for (IdentityMetadataDO metadata : metadataSet) {
                prepStmt.setString(1, metadata.getUserName());
                prepStmt.setInt(2, metadata.getTenantId());
                prepStmt.setString(3, metadata.getMetadataType());
                prepStmt.setString(4, metadata.getMetadata());
                prepStmt.addBatch();
            }
            prepStmt.executeBatch();
            IdentityDatabaseUtil.commitTransaction(connection);
        } catch (SQLException e) {
            IdentityDatabaseUtil.rollbackTransaction(connection);
            throw IdentityException.error("Error while invalidating user identity data", e);
        } finally {
            IdentityDatabaseUtil.closeStatement(prepStmt);
            IdentityDatabaseUtil.closeConnection(connection);
        }

    }

    /**
     * Stores identity data.
     *
     * @param metadata
     * @throws IdentityException
     */
    public void storeMetadata(IdentityMetadataDO metadata) throws IdentityException {
        Connection connection = IdentityDatabaseUtil.getDBConnection();
        PreparedStatement prepStmt = null;
        try {
            prepStmt = connection.prepareStatement(SQLQuery.STORE_META_DATA);
            prepStmt.setString(1, metadata.getUserName());
            prepStmt.setInt(2, metadata.getTenantId());
            prepStmt.setString(3, metadata.getMetadataType());
            prepStmt.setString(4, metadata.getMetadata());
            prepStmt.setString(5, Boolean.toString(metadata.isValid()));
            prepStmt.execute();
            IdentityDatabaseUtil.commitTransaction(connection);
        } catch (SQLException e) {
            IdentityDatabaseUtil.rollbackTransaction(connection);
            throw IdentityException.error("Error while storing user identity data", e);
        } finally {
            IdentityDatabaseUtil.closeStatement(prepStmt);
            IdentityDatabaseUtil.closeConnection(connection);
        }
    }

    /**
     * Stores identity data set.
     *
     * @param metadataSet
     * @throws IdentityException
     */
    public void storeMetadataSet(IdentityMetadataDO[] metadataSet) throws IdentityException {
        Connection connection = IdentityDatabaseUtil.getDBConnection();
        PreparedStatement prepStmt = null;
        try {
            prepStmt = connection.prepareStatement(SQLQuery.STORE_META_DATA);
            for (IdentityMetadataDO metadata : metadataSet) {
                prepStmt.setString(1, metadata.getUserName());
                prepStmt.setInt(2, metadata.getTenantId());
                prepStmt.setString(3, metadata.getMetadataType());
                prepStmt.setString(4, metadata.getMetadata());
                prepStmt.setString(5, Boolean.toString(metadata.isValid()));
                prepStmt.addBatch();
            }
            prepStmt.executeBatch();
            IdentityDatabaseUtil.commitTransaction(connection);
        } catch (SQLException e) {
            IdentityDatabaseUtil.rollbackTransaction(connection);
            throw IdentityException.error("Error while storing user identity data", e);
        } finally {
            IdentityDatabaseUtil.closeStatement(prepStmt);
            IdentityDatabaseUtil.closeConnection(connection);
        }
    }

    /**
     * This method should return only one result. An exception will be thrown if
     * duplicate entries found.
     * This can be used to check if the given metada exist in the database or to
     * check the validity.
     *
     * @param userName
     * @param tenantId
     * @param metadataType
     * @param metadata
     * @return
     * @throws IdentityException
     */
    public IdentityMetadataDO loadMetadata(String userName, int tenantId, String metadataType,
                                           String metadata) throws IdentityException {
        Connection connection = IdentityDatabaseUtil.getDBConnection(false);
        PreparedStatement prepStmt = null;
        ResultSet results = null;
        try {
            prepStmt = connection.prepareStatement(SQLQuery.LOAD_META_DATA);
            prepStmt.setString(1, userName);
            prepStmt.setInt(2, tenantId);
            prepStmt.setString(3, metadataType);
            prepStmt.setString(4, metadata);
            results = prepStmt.executeQuery();
            if (results.next()) {
                return new IdentityMetadataDO(results.getString(1), results.getInt(2),
                        results.getString(3), results.getString(4),
                        Boolean.parseBoolean(results.getString(5)));
            }
            if (results.next()) {
                throw IdentityException.error("Duplicate entry found for " + metadataType);
            }
            return null;
        } catch (SQLException e) {
            throw IdentityException.error("Error while reading user identity data", e);
        } finally {
            IdentityDatabaseUtil.closeResultSet(results);
            IdentityDatabaseUtil.closeStatement(prepStmt);
            IdentityDatabaseUtil.closeConnection(connection);
        }
    }

    /**
     * @param userName
     * @param tenantId
     * @return
     * @throws IdentityException
     */
    public IdentityMetadataDO[] loadMetadata(String userName, int tenantId)
            throws IdentityException {
        Connection connection = IdentityDatabaseUtil.getDBConnection(false);
        PreparedStatement prepStmt = null;
        ResultSet results = null;
        try {
            prepStmt = connection.prepareStatement(SQLQuery.LOAD_USER_METADATA);
            prepStmt.setString(1, userName);
            prepStmt.setInt(2, IdentityTenantUtil.getTenantIdOfUser(userName));

            results = prepStmt.executeQuery();
            List<IdentityMetadataDO> metada = new ArrayList<IdentityMetadataDO>();
            while (results.next()) {
                metada.add(new IdentityMetadataDO(results.getString(1), results.getInt(2),
                        results.getString(3), results.getString(4),
                        Boolean.parseBoolean(results.getString(5))));
            }
            IdentityMetadataDO[] resultMetadata = new IdentityMetadataDO[metada.size()];
            return metada.toArray(resultMetadata);
        } catch (SQLException e) {
            throw IdentityException.error("Error while reading user identity data", e);
        } finally {
            IdentityDatabaseUtil.closeResultSet(results);
            IdentityDatabaseUtil.closeStatement(prepStmt);
            IdentityDatabaseUtil.closeConnection(connection);
        }
    }

    /**
     * Can be used to return primary security questions etc
     *
     * @param userName
     * @param tenantId
     * @param metadataType
     * @return
     * @throws IdentityException
     */
    public IdentityMetadataDO[] loadMetadata(String userName, int tenantId, String metadataType)
            throws IdentityException {
        Connection connection = IdentityDatabaseUtil.getDBConnection(false);
        PreparedStatement prepStmt = null;
        ResultSet results = null;
        try {
            prepStmt = connection.prepareStatement(SQLQuery.LOAD_TENANT_METADATA);
            prepStmt.setInt(1, tenantId);
            prepStmt.setString(2, metadataType);
            results = prepStmt.executeQuery();
            List<IdentityMetadataDO> metada = new ArrayList<IdentityMetadataDO>();
            while (results.next()) {
                metada.add(new IdentityMetadataDO(results.getString(1), results.getInt(2),
                        results.getString(3), results.getString(4),
                        Boolean.parseBoolean(results.getString(5))));
            }
            IdentityMetadataDO[] resultMetadata = new IdentityMetadataDO[metada.size()];
            return metada.toArray(resultMetadata);
        } catch (SQLException e) {
            throw IdentityException.error("Error while reading user identity data", e);
        } finally {
            IdentityDatabaseUtil.closeResultSet(results);
            IdentityDatabaseUtil.closeStatement(prepStmt);
            IdentityDatabaseUtil.closeConnection(connection);
        }
    }

    /**
     * This class contains the SQL queries.
     */
    private static class SQLQuery {

        /**
         * Query to load temporary passwords and confirmation codes
         */
        public static final String LOAD_META_DATA =
                "SELECT "
                        + "USER_NAME, TENANT_ID, METADATA_TYPE, METADATA, VALID "
                        + "FROM IDN_IDENTITY_META_DATA "
                        + "WHERE USER_NAME = ? AND TENANT_ID = ? AND METADATA_TYPE = ? AND METADATA = ?";

        /**
         * Query to load user metadata
         */
        public static final String LOAD_USER_METADATA =
                "SELECT "
                        + "USER_NAME, TENANT_ID, METADATA_TYPE, METADATA, VALID "
                        + "FROM IDN_IDENTITY_META_DATA "
                        + "WHERE USER_NAME = ? AND TENANT_ID = ? ";

        /**
         * Query to load security questions
         */
        public static final String LOAD_TENANT_METADATA =
                "SELECT "
                        + "USER_NAME, TENANT_ID, METADATA_TYPE, METADATA, VALID "
                        + "FROM IDN_IDENTITY_META_DATA "
                        + "WHERE TENANT_ID = ? AND METADATA_TYPE = ?";

        public static final String STORE_META_DATA =
                "INSERT "
                        + "INTO IDN_IDENTITY_META_DATA "
                        + "(USER_NAME, TENANT_ID, METADATA_TYPE, METADATA, VALID)"
                        + "VALUES (?,?,?,?,?)";

        public static final String INVALIDATE_METADATA =
                "UPDATE "
                        + "IDN_IDENTITY_META_DATA "
                        + "SET VALID = 'false' "
                        + "WHERE USER_NAME = ? AND TENANT_ID = ? AND METADATA_TYPE = ? AND METADATA = ?";

        private SQLQuery() {
        }
    }
}


text:
_For background on this project check out this [blog post](http://www.philipotoole.com/building-a-distributed-key-value-store-using-raft/). Please note that this project has been archived, and is no longer maintained._

hraftd
======

hraftd is a reference example use of the [Hashicorp Raft implementation v1.0](https://github.com/hashicorp/raft). [Raft](https://raft.github.io/) is a _distributed consensus protocol_, meaning its purpose is to ensure that a set of nodes -- a cluster -- agree on the state of some arbitrary state machine, even when nodes are vulnerable to failure and network partitions. Distributed consensus is a fundamental concept when it comes to building fault-tolerant systems.

A simple example system like hraftd makes it easy to study the Raft consensus protocol in general, and Hashicorp's Raft implementation in particular. It can be run on Linux, OSX, and Windows.

## Reading and writing keys

The reference implementation is a very simple in-memory key-value store. You can set a key by sending a request to the HTTP bind address (which defaults to `localhost:11000`):
```bash
curl -XPOST localhost:11000/key -d '{"foo": "bar"}'
```

You can read the value for a key like so:
```bash
curl -XGET localhost:11000/key/foo
```

## Running hraftd
*Building hraftd requires Go 1.16 or later. [gvm](https://github.com/moovweb/gvm) is a great tool for installing and managing your versions of Go.*

Starting and running a hraftd cluster is easy. Download and build hraftd like so:
```bash
mkdir work # or any director you like
cd work
export GOPATH=$PWD
mkdir -p src/github.com/otoolep
cd src/github.com/otoolep/
git clone git@github.com:otoolep/hraftd.git
cd hraftd
go install
```

Run your first hraftd node like so:
```bash
$GOPATH/bin/hraftd -id node0 ~/node0
```

You can now set a key and read its value back:
```bash
curl -XPOST localhost:11000/key -d '{"user1": "batman"}'
curl -XGET localhost:11000/key/user1
```

### Bring up a cluster
_A walkthrough of setting up a more realistic cluster is [here](https://github.com/otoolep/hraftd/blob/master/CLUSTERING.md)._

Let's bring up 2 more nodes, so we have a 3-node cluster. That way we can tolerate the failure of 1 node:
```bash
$GOPATH/bin/hraftd -id node1 -haddr :11001 -raddr :12001 -join :11000 ~/node1
$GOPATH/bin/hraftd -id node2 -haddr :11002 -raddr :12002 -join :11000 ~/node2
```
_This example shows each hraftd node running on the same host, so each node must listen on different ports. This would not be necessary if each node ran on a different host._

This tells each new node to join the existing node. Once joined, each node now knows about the key:
```bash
curl -XGET localhost:11000/key/user1
curl -XGET localhost:11001/key/user1
curl -XGET localhost:11002/key/user1
```

Furthermore you can add a second key:
```bash
curl -XPOST localhost:11000/key -d '{"user2": "robin"}'
```

Confirm that the new key has been set like so:
```bash
curl -XGET localhost:11000/key/user2
curl -XGET localhost:11001/key/user2
curl -XGET localhost:11002/key/user2
```

#### Stale reads
Because any node will answer a GET request, and nodes may "fall behind" updates, stale reads are possible. Again, hraftd is a simple program, for the purpose of demonstrating a distributed key-value store. If you are particularly interested in learning more about issue, you should check out [rqlite](https://github.com/rqlite/rqlite). rqlite allows the client to control [read consistency](https://github.com/rqlite/rqlite/blob/master/DOC/CONSISTENCY.md), allowing the client to trade off read-responsiveness and correctness.

Read-consistency support could be ported to hraftd if necessary.

### Tolerating failure
Kill the leader process and watch one of the other nodes be elected leader. The keys are still available for query on the other nodes, and you can set keys on the new leader. Furthermore, when the first node is restarted, it will rejoin the cluster and learn about any updates that occurred while it was down.

A 3-node cluster can tolerate the failure of a single node, but a 5-node cluster can tolerate the failure of two nodes. But 5-node clusters require that the leader contact a larger number of nodes before any change e.g. setting a key's value, can be considered committed.

### Leader-forwarding
Automatically forwarding requests to set keys to the current leader is not implemented. The client must always send requests to change a key to the leader or an error will be returned.

## Production use of Raft
For a production-grade example of using Hashicorp's Raft implementation, to replicate a SQLite database, check out [rqlite](https://github.com/rqlite/rqlite).


text:
Starter code for Matrix Addition Pipelining lab

Please add your names and GitHub account names here.

:octocat:


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

namespace Agathas.Storefront.Services.Implementations
{
    public class BasketDoesNotExistException : Exception
    {
    }
}


text:
package aws

import (
	"crypto/md5"
	"encoding/json"
	"fmt"
	"log"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/lambda"
	"github.com/hashicorp/terraform/helper/schema"
	"github.com/hashicorp/terraform/helper/validation"
)

func dataSourceAwsLambdaInvocation() *schema.Resource {
	return &schema.Resource{
		Read: dataSourceAwsLambdaInvocationRead,

		Schema: map[string]*schema.Schema{
			"function_name": {
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},

			"qualifier": {
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: true,
				Default:  "$LATEST",
			},

			"input": {
				Type:         schema.TypeString,
				Required:     true,
				ForceNew:     true,
				ValidateFunc: validation.ValidateJsonString,
			},

			"result": {
				Type:     schema.TypeString,
				Computed: true,
			},

			"result_map": {
				Type:     schema.TypeMap,
				Computed: true,
				Elem: &schema.Schema{
					Type: schema.TypeString,
				},
			},
		},
	}
}

func dataSourceAwsLambdaInvocationRead(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).lambdaconn

	functionName := d.Get("function_name").(string)
	qualifier := d.Get("qualifier").(string)
	input := []byte(d.Get("input").(string))

	res, err := conn.Invoke(&lambda.InvokeInput{
		FunctionName:   aws.String(functionName),
		InvocationType: aws.String(lambda.InvocationTypeRequestResponse),
		Payload:        input,
		Qualifier:      aws.String(qualifier),
	})

	if err != nil {
		return err
	}

	if res.FunctionError != nil {
		return fmt.Errorf("Lambda function (%s) returned error: (%s)", functionName, string(res.Payload))
	}

	if err = d.Set("result", string(res.Payload)); err != nil {
		return err
	}

	var result map[string]interface{}

	if err = json.Unmarshal(res.Payload, &result); err != nil {
		return err
	}

	if err = d.Set("result_map", result); err != nil {
		log.Printf("[WARN] Cannot use the result invocation as a string map: %s", err)
	}

	d.SetId(fmt.Sprintf("%s_%s_%x", functionName, qualifier, md5.Sum(input)))

	return nil
}


text:
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.autofill_assistant.carousel;

import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupMenu;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView.ViewHolder;

import org.chromium.chrome.autofill_assistant.R;
import org.chromium.chrome.browser.autofill_assistant.LayoutUtils;

/**
 * The {@link ViewHolder} responsible for reflecting an {@link AssistantChip} to a {@link
 * ButtonView}.
 */
public class AssistantChipViewHolder extends ViewHolder {
    private final ButtonView mView;
    private @Nullable PopupMenu mPopupMenu;

    /** The type of this ViewHolder, as returned by {@link #getViewType(AssistantChip)}. */
    private final int mType;

    private AssistantChipViewHolder(ButtonView view, int type) {
        super(view);
        mView = view;
        mType = type;
    }

    public static AssistantChipViewHolder create(ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater = LayoutUtils.createInflater(parent.getContext());
        ButtonView view = null;
        switch (viewType) {
            case AssistantChip.Type.CHIP_ASSISTIVE:
                view = (ButtonView) layoutInflater.inflate(
                        R.layout.autofill_assistant_button_assistive, /* root= */ null);
                break;
            case AssistantChip.Type.BUTTON_FILLED_BLUE:
                view = (ButtonView) layoutInflater.inflate(
                        R.layout.autofill_assistant_button_filled, /* root= */ null);
                break;
            case AssistantChip.Type.BUTTON_HAIRLINE:
                view = (ButtonView) layoutInflater.inflate(
                        R.layout.autofill_assistant_button_hairline, /* root= */ null);
                break;
            default:
                assert false : "Unsupported view type " + viewType;
        }

        view.setLayoutParams(new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));

        return new AssistantChipViewHolder(view, viewType);
    }

    public static int getViewType(AssistantChip chip) {
        return chip.getType();
    }

    public ButtonView getView() {
        return mView;
    }

    public int getType() {
        return mType;
    }

    public void bind(AssistantChip chip) {
        mView.setEnabled(!chip.isDisabled());
        mView.setVisibility(chip.isVisible() ? View.VISIBLE : View.GONE);

        String text = chip.getText();
        if (text.isEmpty()) {
            mView.getPrimaryTextView().setVisibility(View.GONE);
        } else {
            mView.getPrimaryTextView().setText(text);
            mView.getPrimaryTextView().setVisibility(View.VISIBLE);
        }

        // Setting this view to clickable may be required for a11y to correctly announce it.
        mView.setClickable(true);

        // If a popup is specified, show the popup menu and invoke the popup callback.
        if (chip.getPopupItems() != null) {
            mPopupMenu = new PopupMenu(mView.getContext(), mView);
            for (int i = 0; i < chip.getPopupItems().size(); i++) {
                mPopupMenu.getMenu().add(Menu.NONE, i, Menu.NONE, chip.getPopupItems().get(i));
            }
            mPopupMenu.setOnMenuItemClickListener(item -> {
                chip.getOnPopupItemSelectedCallback().onResult(item.getItemId());
                return true;
            });
            mView.setOnClickListener(ignoredView -> {
                if (chip.getSelectedListener() != null) {
                    chip.getSelectedListener().run();
                }
                mPopupMenu.show();
            });
        } else {
            if (chip.getSelectedListener() != null) {
                mView.setOnClickListener(ignoredView -> chip.getSelectedListener().run());
            }
        }

        int iconResource;
        int iconDescriptionResource = 0;
        switch (chip.getIcon()) {
            case AssistantChip.Icon.CLEAR:
                iconResource = R.drawable.ic_clear_black_chrome_24dp;
                iconDescriptionResource = R.string.close;
                break;
            case AssistantChip.Icon.DONE:
                iconResource = R.drawable.ic_done_black_24dp;
                iconDescriptionResource = R.string.done;
                break;
            case AssistantChip.Icon.REFRESH:
                iconResource = R.drawable.ic_refresh_black_24dp;
                iconDescriptionResource = R.string.menu_refresh;
                break;
            case AssistantChip.Icon.OVERFLOW:
                iconResource = R.drawable.ic_overflow_black_24dp;
                iconDescriptionResource = R.string.autofill_assistant_overflow_options;
                break;
            default:
                iconResource = ButtonView.INVALID_ICON_ID;
                break;
        }

        mView.setIcon(iconResource, /* tintWithTextColor= */ true);

        String contentDescription = chip.getContentDescription();
        if (contentDescription != null) {
            mView.setContentDescription(contentDescription);
        } else if (iconDescriptionResource != 0 && text.isEmpty()) {
            mView.setContentDescription(mView.getContext().getString(iconDescriptionResource));
        } else {
            mView.setContentDescription(text);
        }
    }
}


text:
<?php

	include("include/init.php");
	loadlib("foursquare_api");

	$redir = $GLOBALS['cfg']['abs_root_url'] . get_str('redir');

	# Some basic sanity checking like are you already logged in?

	if ($GLOBALS['cfg']['user']['id']){
		header("location: {$redir}");
		exit();
	}

	if (! $GLOBALS['cfg']['enable_feature_signin']){
		$GLOBALS['smarty']->display("page_signin_disabled.txt");
		exit();
	}

	# TO DO: pass redir around...

	$url = foursquare_api_get_auth_url();

	header("location: {$url}");
	exit();
?>


text:
function main() {
  var n = parseInt(readLine());
  var arr = readLine().split(' ');
  arr = arr.map(Number);

  console.log(arr.reverse().join(' '));
}


text:
<?php

namespace Exedra\Routeller\Attributes;

use Exedra\Routeller\Contracts\RouteAttribute;

#[\Attribute(\Attribute::IS_REPEATABLE|\Attribute::TARGET_CLASS|\Attribute::TARGET_METHOD)]
class Flag implements RouteAttribute
{
    protected $flag;

    public function __construct($flag)
    {
        $this->flag = $flag;
    }

    public function getProperty(): string
    {
        return 'flags';
    }

    public function getValue(): mixed
    {
        return [$this->flag];
    }
}


text:
module.exports = function(RED) {
    "use strict";
    // require any external libraries we may need....
    var mailin = require('mailin');
	var os = require('os');

    // The main node definition - most things happen in here
    function MailinSMTP(config) {
        // Create a RED node
        RED.nodes.createNode(this,config);

		var node = this;

		var conf = {
		  port: config.port,
		  disableWebhook: true, // Disable the webhook posting.,
		  tmp: os.tmpdir() + "/mailin"
		}

		mailin.start(conf);

		mailin.on('message', function (connection, data, content) {

		  var msg = {};
		  msg.payload = data;

		  node.send(msg);
		});

        this.on("close", function() {
			mailin.stop();
        });
    }

    // Register the node by name. This must be called before overriding any of the
    // Node functions.
    RED.nodes.registerType("Mailin SMTP",MailinSMTP);

}


text:
This sample shows how to implement a proxy service that re-implements the out-of-the-box SharePoint **GetGroupCollectionsOfUser** ASMX endpoint. In SharePoint Online InfoPath forms [can only call 10 OOB ASMX operations](https://support.microsoft.com/en-us/kb/2674193), all other out-of-the-box ASMX calls will fail. A workaround for this is to host mimic the ASMX service behavior using a custom service.

### Applies to ###
-  Office 365 Multi Tenant (MT)
-  Office 365 Dedicated (D)
-  SharePoint 2013 on-premises

### Solution ###
Solution | Author(s)
---------|----------
Proxy.InfoPath | Ron Tielke, Bert Jansen (**Microsoft**)

### Version history ###
Version  | Date | Comments
---------| -----| --------
1.0 | January 21st 2016 | Initial release

### Disclaimer ###
**THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.**

----------

# Introduction #
In SharePoint Online InfoPath Forms Services cannot call into out-of-the-box ASMX services due to the security setup of SharePoint Online. The [10 most frequently called ASMX service operations](https://support.microsoft.com/en-us/kb/2674193) have been "fixed" by a change in InfoPath Forms Services, but what if your form is calling into an ASMX service which is not in the list of 10? Since InfoPath Forms Services can still call external services the solution is to host a custom service externally and call that one. That custom service then can use the SharePoint CSOM to connect back to SharePoint and return the needed information. In order to use this sample one needs to decide on two topics:
- How does the proxy service access SharePoint
- How to verify the service caller

Next chapters give some more context on these topics.

## Choose a method to access SharePoint ##
The Proxy must be able to access SharePoint to obtain the information (group information in this case). You can choose either of the following approaches, but regardless of your choice, it is best to follow the principal of least privilege.

### Use app-only (preferred) ###
Register and trust an app-only principal via:
- Use AppRegNew to create an App Registration (and App ID)
- Use AppInv to grant AT LEAST the following permission on the target site collection(s) that host the form:

```XML
<AppPermissionRequests AllowAppOnlyPolicy="true">
      <AppPermissionRequest Scope="http://sharepoint/content/sitecollection" Right="Read" />
</AppPermissionRequests>
```

### Use a service account ###
The Service Account needs to be granted AT LEAST the following permissions on the target site collection(s) that host the form:
- Site Permissions:**Browse User Information**  *View information about users of the Web site*
- Site Permissions:**Use Remote Interfaces**  *Use SOAP, Web DAV, the Client Object Model or SharePoint Designer interfaces to access the Web site*
- Site Permissions:**Open**  *Allows users to open a Web site, list, or folder in order to access items inside that container*

You can create a custom permission level with only these permissions and grant that level to the service account or choose for an simpler approach by simply adding the Service Account to the Owners security group.

### Update the samples web.config ###
The appSettings section in web.config from this sample is well documented. Please make the needed changes depending on the chosen setup and target platform

```XML
<appSettings>

    <!-- Set to "true" if the target SharePoint environment is v15 (either on-prem or SPO-D) -->
    <!-- Set to "false" if the target SharePoint environment is v16 (either SPO-MT or SPO-vNext) -->
    <add key="TargetFarmIsSPOD" value="false" />

    <!-- Configure the following Client keys if you wish to use App Registration Mode -->
    <!--
    Minimum App Permissions required on target site collection that hosts the InfoPath form:
    <AppPermissionRequests AllowAppOnlyPolicy="true">
      <AppPermissionRequest Scope="http://sharepoint/content/sitecollection" Right="Read" />
    </AppPermissionRequests>

    <add key="ClientId" value="obtain from AppRegNew.aspx" />
    <add key="ClientSecret" value="obtain from AppRegNew.aspx" />
    -->
    <add key="ClientId" value="" />
    <add key="ClientSecret" value="" />

    <!-- Configure the following Client keys if you wish to use Service Account Mode -->
    <!--
    minimum permissions required on target site collection that hosts the InfoPath form:
    Site Permissions:Browse User Information  -  View information about users of the Web site.
    Site Permissions:Use Remote Interfaces    -  Use SOAP, Web DAV, the Client Object Model or SharePoint Designer interfaces to access the Web site.
    Site Permissions:Open                     -  Allows users to open a Web site, list, or folder in order to access items inside that container.

    *******************************************************************************************************
    NOTE:
     This Sample simply stores the service account password as cleartext for demo purposes
     Passwords should never be stored as cleartext in configuration files
     For security purposes, your implementation should take steps to encrypt the password as necessary
    *******************************************************************************************************

    Format for v15 (TargetFarmIsSPOD=true)
    <add key="ServiceAccountDomain" value="domain" />
    <add key="ServiceAccountUsername" value="username" />
    <add key="ServiceAccountPassword" value="********" />

    Format for v16 (TargetFarmIsSPOD=false)
    <add key="ServiceAccountDomain" value="" />
    <add key="ServiceAccountUsername" value="username@contoso.onMicrosoft.com" />
    <add key="ServiceAccountPassword" value="********" />
    -->
    <add key="ServiceAccountDomain" value="" />
    <add key="ServiceAccountUsername" value="" />
    <add key="ServiceAccountPassword" value="" />

    <!--
      The client (i.e., the InfoPath form) must pass this value as the ClientValidationKey in order to be considered a "valid" client.
      Note: This is a sample value for demo purposes

    <add key="ClientValidationKey" value="ourSharedSecret" />
    -->
    <add key="ClientValidationKey" value="" />

    <!--
    Sample values used by the Testing Interface ...

    Format for v15 (TargetFarmIsSPOD=true)
    <add key="TestSiteCollectionUrl" value="https://portal.contoso.com" />
    <add key="TestUsername" value="domain\\user" />

    Format for v16 (TargetFarmIsSPOD=false)
    <add key="TestSiteCollectionUrl" value="https://contoso.sharepoint.com/sites/test" />
    <add key="TestUsername" value="user@contoso.onMicrosoft.com" />
    -->
    <add key="TestSiteCollectionUrl" value="" />
    <add key="TestUsername" value="" />

  </appSettings>
```

## Choose a method to verify the caller ##
The proxy must support anonymous access and be internet accessible. It is important that the proxy validate the caller. The SharePoint Add-in Model provides this ability natively when OAuth is used; however, the client in this case (InfoPath Form Services) does not support OAuth. For the proxy sample a shared validation key approach was choosen. The form simply passes the key to the proxy when calling the web method(s). We choose to pass a shared key instead of credentials (e.g., the ServiceAccount/Password or AppID/Secret) in order limit exposure/risk:
- If the key falls into the wrong hands, all the hacker can do is call the Proxy API.
- If the credentials fall into the wrong hands, the hacker could write an app to do whatever the credentials would allow.

Furthermore, the validation key model allows one to enhance the client validation logic to implement a form-specific, or site-specific, validation keys if necessary.

<img src="https://telemetry.sharepointpnp.com/pnp-transformation/infopath/samples/Proxy.InfoPath" />


text:
namespace DLaB.Xrm.Entities
{

	[System.Runtime.Serialization.DataContractAttribute()]
	[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "9.0.0.9154")]
	public enum Letter_StatusCode
	{

		[System.Runtime.Serialization.EnumMemberAttribute()]
		Canceled = 5,

		[System.Runtime.Serialization.EnumMemberAttribute()]
		Draft = 2,

		[System.Runtime.Serialization.EnumMemberAttribute()]
		Open = 1,

		[System.Runtime.Serialization.EnumMemberAttribute()]
		Received = 3,

		[System.Runtime.Serialization.EnumMemberAttribute()]
		Sent = 4,
	}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>src/constraints/Constraint.js - cannon</title>
    <link rel="stylesheet" href="http://yui.yahooapis.com/3.9.1/build/cssgrids/cssgrids-min.css">
    <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
    <link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
    <link rel="icon" href="../assets/favicon.ico">

            API Docs for: 0.6.1

APIs

Classes

Modules

                            <input type="search" id="api-filter" placeholder="Type to filter APIs">

AABB

ArrayCollisionMatrix

Body

Box

Broadphase

ConeEquation

ConeTwistConstraint

Constraint

ContactEquation

ContactMaterial

ConvexPolyhedron

Cylinder

Demo

DistanceConstraint

Equation

EventTarget

FrictionEquation

GridBroadphase

GSSolver

Heightfield

HingeConstraint

JacobianElement

LockConstraint

Mat3

Material

NaiveBroadphase

Narrowphase

ObjectCollisionMatrix

Octree

OctreeNode

Particle

Plane

PointToPointConstraint

Pool

Quaternion

Ray

RaycastResult

RaycastVehicle

RigidVehicle

RotationalEquation

RotationalMotorEquation

SAPBroadphase

Shape

Solver

Sphere

SPHSystem

SplitSolver

Spring

Transform

Trimesh

TupleDictionary

Vec3

Vec3Pool

WheelInfo

World

                    Show:

                        <input type="checkbox" id="api-show-inherited" checked>
                        Inherited

                        <input type="checkbox" id="api-show-protected">
                        Protected

                        <input type="checkbox" id="api-show-private">
                        Private

                        <input type="checkbox" id="api-show-deprecated">
                        Deprecated

File: src/constraints/Constraint.js

module.exports = Constraint;

var Utils = require('../utils/Utils');

/**
 * Constraint base class
 * @class Constraint
 * @author schteppe
 * @constructor
 * @param {Body} bodyA
 * @param {Body} bodyB
 * @param {object} [options]
 * @param {boolean} [options.collideConnected=true]
 * @param {boolean} [options.wakeUpBodies=true]
 */
function Constraint(bodyA, bodyB, options){
    options = Utils.defaults(options,{
        collideConnected : true,
        wakeUpBodies : true,
    });

    /**
     * Equations to be solved in this constraint
     * @property equations
     * @type {Array}
     */
    this.equations = [];

    /**
     * @property {Body} bodyA
     */
    this.bodyA = bodyA;

    /**
     * @property {Body} bodyB
     */
    this.bodyB = bodyB;

    /**
     * @property {Number} id
     */
    this.id = Constraint.idCounter++;

    /**
     * Set to true if you want the bodies to collide when they are connected.
     * @property collideConnected
     * @type {boolean}
     */
    this.collideConnected = options.collideConnected;

    if(options.wakeUpBodies){
        if(bodyA){
            bodyA.wakeUp();
        }
        if(bodyB){
            bodyB.wakeUp();
        }
    }
}

/**
 * Update all the equations with data.
 * @method update
 */
Constraint.prototype.update = function(){
    throw new Error("method update() not implmemented in this Constraint subclass!");
};

/**
 * Enables all equations in the constraint.
 * @method enable
 */
Constraint.prototype.enable = function(){
    var eqs = this.equations;
    for(var i=0; i<eqs.length; i++){
        eqs[i].enabled = true;
    }
};

/**
 * Disables all equations in the constraint.
 * @method disable
 */
Constraint.prototype.disable = function(){
    var eqs = this.equations;
    for(var i=0; i<eqs.length; i++){
        eqs[i].enabled = false;
    }
};

Constraint.idCounter = 0;


text:
'use strict';

function CustomByteArraySerializable(int, float) {
    this.int = int;
    this.float = float;
}

function CustomStreamSerializable(int, float) {
    this.int = int;
    this.float = float;
}

exports.CustomByteArraySerializable = CustomByteArraySerializable;
exports.CustomStreamSerializable = CustomStreamSerializable;


text:
<?php
/**
 * SAML 2.0 remote SP metadata for simpleSAMLphp.
 *
 * See: http://simplesamlphp.org/docs/trunk/simplesamlphp-reference-sp-remote
 */

$metadata['demo-app'] = array(
	'AssertionConsumerService' => 'http://local.app:8080/simplesaml/module.php/saml/sp/saml2-acs.php/default-sp',
	'SingleLogoutService' => 'http://local.app:8080/simplesaml/module.php/saml/sp/saml2-logout.php/default-sp',
);


text:
package com.uwetrottmann.tmdb2.services;

import com.uwetrottmann.tmdb2.entities.Network;
import com.uwetrottmann.tmdb2.entities.NetworkImages;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;

public interface NetworksService {

    /**
     * Get the details of a network.
     *
     * @param id The Network TMDb id.
     */
    @GET("network/{id}")
    Call<Network> summary(
            @Path("id") Integer id
    );

    /**
     * Get the logos of a network.
     *
     * @param id The Network TMDb id.
     */
    @GET("network/{id}/images")
    Call<NetworkImages> images(
            @Path("id") Integer id
    );

}


text:
ActiveRecord::Schema.define(version: 20161002211015) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "listings", force: :cascade do |t|
    t.string   "address"
    t.boolean  "favorite"
    t.float    "latitude"
    t.float    "list_price"
    t.float    "longitude"
    t.float    "apx_acreage"
    t.integer  "mls_number"
    t.integer  "apx_total_sqft"
    t.string   "cover_photo_remote_url"
    t.integer  "status"
    t.datetime "created_at",                      null: false
    t.datetime "updated_at",                      null: false
    t.string   "unit"
    t.string   "county"
    t.string   "subdivision"
    t.string   "elementary_school"
    t.string   "middle_school"
    t.string   "high_school"
    t.string   "style"
    t.integer  "total_bedrooms"
    t.integer  "total_full_baths"
    t.integer  "total_baths"
    t.integer  "apx_year_built"
    t.string   "garage_stalls_type"
    t.integer  "taxes"
    t.string   "tax_year"
    t.string   "sold_price"
    t.string   "sold_date"
    t.string   "construction_status"
    t.string   "exterior_primary"
    t.string   "exterior_secondary"
    t.string   "heat_source_type"
    t.string   "air_conditioning"
    t.string   "foundation"
    t.string   "roof"
    t.string   "water"
    t.string   "sewer"
    t.string   "irrigation"
    t.string   "provider_other_info"
    t.string   "basement"
    t.string   "other_rooms"
    t.string   "laundry"
    t.string   "appliances_included"
    t.string   "fireplace"
    t.string   "interior_features"
    t.string   "exterior_features"
    t.string   "patio_deck"
    t.string   "fence_type_info"
    t.string   "landscaping"
    t.string   "view"
    t.string   "driveway_type"
    t.string   "inclusions"
    t.string   "exclusions"
    t.string   "public_info"
    t.string   "driving_directions_beginning_at"
    t.string   "navica_url"
    t.string   "zillow_url"
    t.float    "list_price_change_amount"
    t.string   "cover_photo_file_name"
    t.string   "cover_photo_content_type"
    t.integer  "cover_photo_file_size"
    t.datetime "cover_photo_updated_at"
    t.index ["mls_number"], name: "index_listings_on_mls_number", unique: true, using: :btree
  end

end


text:
// Copyright (C) 2014 Yasuhiro Matsumoto <mattn.jp@gmail.com>.
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.

package sqlite3

/*
#cgo CFLAGS: -std=gnu99
#cgo CFLAGS: -DSQLITE_ENABLE_RTREE -DSQLITE_THREADSAFE
#cgo CFLAGS: -DSQLITE_ENABLE_FTS3 -DSQLITE_ENABLE_FTS3_PARENTHESIS -DSQLITE_ENABLE_FTS4_UNICODE61
#cgo CFLAGS: -DSQLITE_TRACE_SIZE_LIMIT=15
#cgo CFLAGS: -DSQLITE_DISABLE_INTRINSIC
#cgo CFLAGS: -Wno-deprecated-declarations
#ifndef USE_LIBSQLITE3
#include <sqlite3-binding.h>
#else
#include <sqlite3.h>
#endif
#include <stdlib.h>
#include <string.h>

#ifdef __CYGWIN__
# include <errno.h>
#endif

#ifndef SQLITE_OPEN_READWRITE
# define SQLITE_OPEN_READWRITE 0
#endif

#ifndef SQLITE_OPEN_FULLMUTEX
# define SQLITE_OPEN_FULLMUTEX 0
#endif

#ifndef SQLITE_DETERMINISTIC
# define SQLITE_DETERMINISTIC 0
#endif

static int
_sqlite3_open_v2(const char *filename, sqlite3 **ppDb, int flags, const char *zVfs) {
#ifdef SQLITE_OPEN_URI
  return sqlite3_open_v2(filename, ppDb, flags | SQLITE_OPEN_URI, zVfs);
#else
  return sqlite3_open_v2(filename, ppDb, flags, zVfs);
#endif
}

static int
_sqlite3_bind_text(sqlite3_stmt *stmt, int n, char *p, int np) {
  return sqlite3_bind_text(stmt, n, p, np, SQLITE_TRANSIENT);
}

static int
_sqlite3_bind_blob(sqlite3_stmt *stmt, int n, void *p, int np) {
  return sqlite3_bind_blob(stmt, n, p, np, SQLITE_TRANSIENT);
}

#include <stdio.h>
#include <stdint.h>

static int
_sqlite3_exec(sqlite3* db, const char* pcmd, long long* rowid, long long* changes)
{
  int rv = sqlite3_exec(db, pcmd, 0, 0, 0);
  *rowid = (long long) sqlite3_last_insert_rowid(db);
  *changes = (long long) sqlite3_changes(db);
  return rv;
}

static int
_sqlite3_step(sqlite3_stmt* stmt, long long* rowid, long long* changes)
{
  int rv = sqlite3_step(stmt);
  sqlite3* db = sqlite3_db_handle(stmt);
  *rowid = (long long) sqlite3_last_insert_rowid(db);
  *changes = (long long) sqlite3_changes(db);
  return rv;
}

void _sqlite3_result_text(sqlite3_context* ctx, const char* s) {
  sqlite3_result_text(ctx, s, -1, &free);
}

void _sqlite3_result_blob(sqlite3_context* ctx, const void* b, int l) {
  sqlite3_result_blob(ctx, b, l, SQLITE_TRANSIENT);
}

int _sqlite3_create_function(
  sqlite3 *db,
  const char *zFunctionName,
  int nArg,
  int eTextRep,
  uintptr_t pApp,
  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  void (*xFinal)(sqlite3_context*)
) {
  return sqlite3_create_function(db, zFunctionName, nArg, eTextRep, (void*) pApp, xFunc, xStep, xFinal);
}

void callbackTrampoline(sqlite3_context*, int, sqlite3_value**);
*/
import "C"
import (
	"database/sql"
	"database/sql/driver"
	"errors"
	"fmt"
	"io"
	"net/url"
	"reflect"
	"runtime"
	"strconv"
	"strings"
	"time"
	"unsafe"

	"golang.org/x/net/context"
)

// SQLiteTimestampFormats is timestamp formats understood by both this module
// and SQLite.  The first format in the slice will be used when saving time
// values into the database. When parsing a string from a timestamp or datetime
// column, the formats are tried in order.
var SQLiteTimestampFormats = []string{
	// By default, store timestamps with whatever timezone they come with.
	// When parsed, they will be returned with the same timezone.
	"2006-01-02 15:04:05.999999999-07:00",
	"2006-01-02T15:04:05.999999999-07:00",
	"2006-01-02 15:04:05.999999999",
	"2006-01-02T15:04:05.999999999",
	"2006-01-02 15:04:05",
	"2006-01-02T15:04:05",
	"2006-01-02 15:04",
	"2006-01-02T15:04",
	"2006-01-02",
}

func init() {
	sql.Register("sqlite3", &SQLiteDriver{})
}

// Version returns SQLite library version information.
func Version() (libVersion string, libVersionNumber int, sourceID string) {
	libVersion = C.GoString(C.sqlite3_libversion())
	libVersionNumber = int(C.sqlite3_libversion_number())
	sourceID = C.GoString(C.sqlite3_sourceid())
	return libVersion, libVersionNumber, sourceID
}

// SQLiteDriver implement sql.Driver.
type SQLiteDriver struct {
	Extensions  []string
	ConnectHook func(*SQLiteConn) error
}

// SQLiteConn implement sql.Conn.
type SQLiteConn struct {
	db          *C.sqlite3
	loc         *time.Location
	txlock      string
	funcs       []*functionInfo
	aggregators []*aggInfo
}

// SQLiteTx implemen sql.Tx.
type SQLiteTx struct {
	c *SQLiteConn
}

// SQLiteStmt implement sql.Stmt.
type SQLiteStmt struct {
	c      *SQLiteConn
	s      *C.sqlite3_stmt
	t      string
	closed bool
	cls    bool
}

// SQLiteResult implement sql.Result.
type SQLiteResult struct {
	id      int64
	changes int64
}

// SQLiteRows implement sql.Rows.
type SQLiteRows struct {
	s        *SQLiteStmt
	nc       int
	cols     []string
	decltype []string
	cls      bool
	done     chan struct{}
}

type functionInfo struct {
	f                 reflect.Value
	argConverters     []callbackArgConverter
	variadicConverter callbackArgConverter
	retConverter      callbackRetConverter
}

func (fi *functionInfo) Call(ctx *C.sqlite3_context, argv []*C.sqlite3_value) {
	args, err := callbackConvertArgs(argv, fi.argConverters, fi.variadicConverter)
	if err != nil {
		callbackError(ctx, err)
		return
	}

	ret := fi.f.Call(args)

	if len(ret) == 2 && ret[1].Interface() != nil {
		callbackError(ctx, ret[1].Interface().(error))
		return
	}

	err = fi.retConverter(ctx, ret[0])
	if err != nil {
		callbackError(ctx, err)
		return
	}
}

type aggInfo struct {
	constructor reflect.Value

	// Active aggregator objects for aggregations in flight. The
	// aggregators are indexed by a counter stored in the aggregation
	// user data space provided by sqlite.
	active map[int64]reflect.Value
	next   int64

	stepArgConverters     []callbackArgConverter
	stepVariadicConverter callbackArgConverter

	doneRetConverter callbackRetConverter
}

func (ai *aggInfo) agg(ctx *C.sqlite3_context) (int64, reflect.Value, error) {
	aggIdx := (*int64)(C.sqlite3_aggregate_context(ctx, C.int(8)))
	if *aggIdx == 0 {
		*aggIdx = ai.next
		ret := ai.constructor.Call(nil)
		if len(ret) == 2 && ret[1].Interface() != nil {
			return 0, reflect.Value{}, ret[1].Interface().(error)
		}
		if ret[0].IsNil() {
			return 0, reflect.Value{}, errors.New("aggregator constructor returned nil state")
		}
		ai.next++
		ai.active[*aggIdx] = ret[0]
	}
	return *aggIdx, ai.active[*aggIdx], nil
}

func (ai *aggInfo) Step(ctx *C.sqlite3_context, argv []*C.sqlite3_value) {
	_, agg, err := ai.agg(ctx)
	if err != nil {
		callbackError(ctx, err)
		return
	}

	args, err := callbackConvertArgs(argv, ai.stepArgConverters, ai.stepVariadicConverter)
	if err != nil {
		callbackError(ctx, err)
		return
	}

	ret := agg.MethodByName("Step").Call(args)
	if len(ret) == 1 && ret[0].Interface() != nil {
		callbackError(ctx, ret[0].Interface().(error))
		return
	}
}

func (ai *aggInfo) Done(ctx *C.sqlite3_context) {
	idx, agg, err := ai.agg(ctx)
	if err != nil {
		callbackError(ctx, err)
		return
	}
	defer func() { delete(ai.active, idx) }()

	ret := agg.MethodByName("Done").Call(nil)
	if len(ret) == 2 && ret[1].Interface() != nil {
		callbackError(ctx, ret[1].Interface().(error))
		return
	}

	err = ai.doneRetConverter(ctx, ret[0])
	if err != nil {
		callbackError(ctx, err)
		return
	}
}

// Commit transaction.
func (tx *SQLiteTx) Commit() error {
	_, err := tx.c.exec(context.Background(), "COMMIT", nil)
	if err != nil && err.(Error).Code == C.SQLITE_BUSY {
		// sqlite3 will leave the transaction open in this scenario.
		// However, database/sql considers the transaction complete once we
		// return from Commit() - we must clean up to honour its semantics.
		tx.c.exec(context.Background(), "ROLLBACK", nil)
	}
	return err
}

// Rollback transaction.
func (tx *SQLiteTx) Rollback() error {
	_, err := tx.c.exec(context.Background(), "ROLLBACK", nil)
	return err
}

// RegisterFunc makes a Go function available as a SQLite function.
//
// The Go function can have arguments of the following types: any
// numeric type except complex, bool, []byte, string and
// interface{}. interface{} arguments are given the direct translation
// of the SQLite data type: int64 for INTEGER, float64 for FLOAT,
// []byte for BLOB, string for TEXT.
//
// The function can additionally be variadic, as long as the type of
// the variadic argument is one of the above.
//
// If pure is true. SQLite will assume that the function's return
// value depends only on its inputs, and make more aggressive
// optimizations in its queries.
//
// See _example/go_custom_funcs for a detailed example.
func (c *SQLiteConn) RegisterFunc(name string, impl interface{}, pure bool) error {
	var fi functionInfo
	fi.f = reflect.ValueOf(impl)
	t := fi.f.Type()
	if t.Kind() != reflect.Func {
		return errors.New("Non-function passed to RegisterFunc")
	}
	if t.NumOut() != 1 && t.NumOut() != 2 {
		return errors.New("SQLite functions must return 1 or 2 values")
	}
	if t.NumOut() == 2 && !t.Out(1).Implements(reflect.TypeOf((*error)(nil)).Elem()) {
		return errors.New("Second return value of SQLite function must be error")
	}

	numArgs := t.NumIn()
	if t.IsVariadic() {
		numArgs--
	}

	for i := 0; i < numArgs; i++ {
		conv, err := callbackArg(t.In(i))
		if err != nil {
			return err
		}
		fi.argConverters = append(fi.argConverters, conv)
	}

	if t.IsVariadic() {
		conv, err := callbackArg(t.In(numArgs).Elem())
		if err != nil {
			return err
		}
		fi.variadicConverter = conv
		// Pass -1 to sqlite so that it allows any number of
		// arguments. The call helper verifies that the minimum number
		// of arguments is present for variadic functions.
		numArgs = -1
	}

	conv, err := callbackRet(t.Out(0))
	if err != nil {
		return err
	}
	fi.retConverter = conv

	// fi must outlast the database connection, or we'll have dangling pointers.
	c.funcs = append(c.funcs, &fi)

	cname := C.CString(name)
	defer C.free(unsafe.Pointer(cname))
	opts := C.SQLITE_UTF8
	if pure {
		opts |= C.SQLITE_DETERMINISTIC
	}
	rv := sqlite3CreateFunction(c.db, cname, C.int(numArgs), C.int(opts), newHandle(c, &fi), C.callbackTrampoline, nil, nil)
	if rv != C.SQLITE_OK {
		return c.lastError()
	}
	return nil
}

func sqlite3CreateFunction(db *C.sqlite3, zFunctionName *C.char, nArg C.int, eTextRep C.int, pApp uintptr, xFunc unsafe.Pointer, xStep unsafe.Pointer, xFinal unsafe.Pointer) C.int {
	return C._sqlite3_create_function(db, zFunctionName, nArg, eTextRep, C.uintptr_t(pApp), (*[0]byte)(unsafe.Pointer(xFunc)), (*[0]byte)(unsafe.Pointer(xStep)), (*[0]byte)(unsafe.Pointer(xFinal)))
}

// AutoCommit return which currently auto commit or not.
func (c *SQLiteConn) AutoCommit() bool {
	return int(C.sqlite3_get_autocommit(c.db)) != 0
}

func (c *SQLiteConn) lastError() Error {
	return Error{
		Code:         ErrNo(C.sqlite3_errcode(c.db)),
		ExtendedCode: ErrNoExtended(C.sqlite3_extended_errcode(c.db)),
		err:          C.GoString(C.sqlite3_errmsg(c.db)),
	}
}

// Exec implements Execer.
func (c *SQLiteConn) Exec(query string, args []driver.Value) (driver.Result, error) {
	list := make([]namedValue, len(args))
	for i, v := range args {
		list[i] = namedValue{
			Ordinal: i + 1,
			Value:   v,
		}
	}
	return c.exec(context.Background(), query, list)
}

func (c *SQLiteConn) exec(ctx context.Context, query string, args []namedValue) (driver.Result, error) {
	start := 0
	for {
		s, err := c.prepare(ctx, query)
		if err != nil {
			return nil, err
		}
		var res driver.Result
		if s.(*SQLiteStmt).s != nil {
			na := s.NumInput()
			if len(args) < na {
				s.Close()
				return nil, fmt.Errorf("not enough args to execute query: want %d got %d", na, len(args))
			}
			for i := 0; i < na; i++ {
				args[i].Ordinal -= start
			}
			res, err = s.(*SQLiteStmt).exec(ctx, args[:na])
			if err != nil && err != driver.ErrSkip {
				s.Close()
				return nil, err
			}
			args = args[na:]
			start += na
		}
		tail := s.(*SQLiteStmt).t
		s.Close()
		if tail == "" {
			return res, nil
		}
		query = tail
	}
}

type namedValue struct {
	Name    string
	Ordinal int
	Value   driver.Value
}

// Query implements Queryer.
func (c *SQLiteConn) Query(query string, args []driver.Value) (driver.Rows, error) {
	list := make([]namedValue, len(args))
	for i, v := range args {
		list[i] = namedValue{
			Ordinal: i + 1,
			Value:   v,
		}
	}
	return c.query(context.Background(), query, list)
}

func (c *SQLiteConn) query(ctx context.Context, query string, args []namedValue) (driver.Rows, error) {
	start := 0
	for {
		s, err := c.prepare(ctx, query)
		if err != nil {
			return nil, err
		}
		s.(*SQLiteStmt).cls = true
		na := s.NumInput()
		if len(args) < na {
			return nil, fmt.Errorf("not enough args to execute query: want %d got %d", na, len(args))
		}
		for i := 0; i < na; i++ {
			args[i].Ordinal -= start
		}
		rows, err := s.(*SQLiteStmt).query(ctx, args[:na])
		if err != nil && err != driver.ErrSkip {
			s.Close()
			return rows, err
		}
		args = args[na:]
		start += na
		tail := s.(*SQLiteStmt).t
		if tail == "" {
			return rows, nil
		}
		rows.Close()
		s.Close()
		query = tail
	}
}

// Begin transaction.
func (c *SQLiteConn) Begin() (driver.Tx, error) {
	return c.begin(context.Background())
}

func (c *SQLiteConn) begin(ctx context.Context) (driver.Tx, error) {
	if _, err := c.exec(ctx, c.txlock, nil); err != nil {
		return nil, err
	}
	return &SQLiteTx{c}, nil
}

func errorString(err Error) string {
	return C.GoString(C.sqlite3_errstr(C.int(err.Code)))
}

// Open database and return a new connection.
// You can specify a DSN string using a URI as the filename.
//   test.db
//   file:test.db?cache=shared&mode=memory
//   :memory:
//   file::memory:
// go-sqlite3 adds the following query parameters to those used by SQLite:
//   _loc=XXX
//     Specify location of time format. It's possible to specify "auto".
//   _busy_timeout=XXX
//     Specify value for sqlite3_busy_timeout.
//   _txlock=XXX
//     Specify locking behavior for transactions.  XXX can be "immediate",
//     "deferred", "exclusive".
func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
	if C.sqlite3_threadsafe() == 0 {
		return nil, errors.New("sqlite library was not compiled for thread-safe operation")
	}

	var loc *time.Location
	txlock := "BEGIN"
	busyTimeout := 5000
	pos := strings.IndexRune(dsn, '?')
	if pos >= 1 {
		params, err := url.ParseQuery(dsn[pos+1:])
		if err != nil {
			return nil, err
		}

		// _loc
		if val := params.Get("_loc"); val != "" {
			if val == "auto" {
				loc = time.Local
			} else {
				loc, err = time.LoadLocation(val)
				if err != nil {
					return nil, fmt.Errorf("Invalid _loc: %v: %v", val, err)
				}
			}
		}

		// _busy_timeout
		if val := params.Get("_busy_timeout"); val != "" {
			iv, err := strconv.ParseInt(val, 10, 64)
			if err != nil {
				return nil, fmt.Errorf("Invalid _busy_timeout: %v: %v", val, err)
			}
			busyTimeout = int(iv)
		}

		// _txlock
		if val := params.Get("_txlock"); val != "" {
			switch val {
			case "immediate":
				txlock = "BEGIN IMMEDIATE"
			case "exclusive":
				txlock = "BEGIN EXCLUSIVE"
			case "deferred":
				txlock = "BEGIN"
			default:
				return nil, fmt.Errorf("Invalid _txlock: %v", val)
			}
		}

		if !strings.HasPrefix(dsn, "file:") {
			dsn = dsn[:pos]
		}
	}

	var db *C.sqlite3
	name := C.CString(dsn)
	defer C.free(unsafe.Pointer(name))
	rv := C._sqlite3_open_v2(name, &db,
		C.SQLITE_OPEN_FULLMUTEX|
			C.SQLITE_OPEN_READWRITE|
			C.SQLITE_OPEN_CREATE,
		nil)
	if rv != 0 {
		return nil, Error{Code: ErrNo(rv)}
	}
	if db == nil {
		return nil, errors.New("sqlite succeeded without returning a database")
	}

	rv = C.sqlite3_busy_timeout(db, C.int(busyTimeout))
	if rv != C.SQLITE_OK {
		return nil, Error{Code: ErrNo(rv)}
	}

	conn := &SQLiteConn{db: db, loc: loc, txlock: txlock}

	if len(d.Extensions) > 0 {
		if err := conn.loadExtensions(d.Extensions); err != nil {
			return nil, err
		}
	}

	if d.ConnectHook != nil {
		if err := d.ConnectHook(conn); err != nil {
			return nil, err
		}
	}
	runtime.SetFinalizer(conn, (*SQLiteConn).Close)
	return conn, nil
}

// Close the connection.
func (c *SQLiteConn) Close() error {
	rv := C.sqlite3_close_v2(c.db)
	if rv != C.SQLITE_OK {
		return c.lastError()
	}
	deleteHandles(c)
	c.db = nil
	runtime.SetFinalizer(c, nil)
	return nil
}

// Prepare the query string. Return a new statement.
func (c *SQLiteConn) Prepare(query string) (driver.Stmt, error) {
	return c.prepare(context.Background(), query)
}

func (c *SQLiteConn) prepare(ctx context.Context, query string) (driver.Stmt, error) {
	pquery := C.CString(query)
	defer C.free(unsafe.Pointer(pquery))
	var s *C.sqlite3_stmt
	var tail *C.char
	rv := C.sqlite3_prepare_v2(c.db, pquery, -1, &s, &tail)
	if rv != C.SQLITE_OK {
		return nil, c.lastError()
	}
	var t string
	if tail != nil && *tail != '\000' {
		t = strings.TrimSpace(C.GoString(tail))
	}
	ss := &SQLiteStmt{c: c, s: s, t: t}
	runtime.SetFinalizer(ss, (*SQLiteStmt).Close)
	return ss, nil
}

// Close the statement.
func (s *SQLiteStmt) Close() error {
	if s.closed {
		return nil
	}
	s.closed = true
	if s.c == nil || s.c.db == nil {
		return errors.New("sqlite statement with already closed database connection")
	}
	rv := C.sqlite3_finalize(s.s)
	if rv != C.SQLITE_OK {
		return s.c.lastError()
	}
	runtime.SetFinalizer(s, nil)
	return nil
}

// NumInput return a number of parameters.
func (s *SQLiteStmt) NumInput() int {
	return int(C.sqlite3_bind_parameter_count(s.s))
}

type bindArg struct {
	n int
	v driver.Value
}

func (s *SQLiteStmt) bind(args []namedValue) error {
	rv := C.sqlite3_reset(s.s)
	if rv != C.SQLITE_ROW && rv != C.SQLITE_OK && rv != C.SQLITE_DONE {
		return s.c.lastError()
	}

	for i, v := range args {
		if v.Name != "" {
			cname := C.CString(":" + v.Name)
			args[i].Ordinal = int(C.sqlite3_bind_parameter_index(s.s, cname))
			C.free(unsafe.Pointer(cname))
		}
	}

	for _, arg := range args {
		n := C.int(arg.Ordinal)
		switch v := arg.Value.(type) {
		case nil:
			rv = C.sqlite3_bind_null(s.s, n)
		case string:
			if len(v) == 0 {
				b := []byte{0}
				rv = C._sqlite3_bind_text(s.s, n, (*C.char)(unsafe.Pointer(&b[0])), C.int(0))
			} else {
				b := []byte(v)
				rv = C._sqlite3_bind_text(s.s, n, (*C.char)(unsafe.Pointer(&b[0])), C.int(len(b)))
			}
		case int64:
			rv = C.sqlite3_bind_int64(s.s, n, C.sqlite3_int64(v))
		case bool:
			if bool(v) {
				rv = C.sqlite3_bind_int(s.s, n, 1)
			} else {
				rv = C.sqlite3_bind_int(s.s, n, 0)
			}
		case float64:
			rv = C.sqlite3_bind_double(s.s, n, C.double(v))
		case []byte:
			if len(v) == 0 {
				rv = C._sqlite3_bind_blob(s.s, n, nil, 0)
			} else {
				rv = C._sqlite3_bind_blob(s.s, n, unsafe.Pointer(&v[0]), C.int(len(v)))
			}
		case time.Time:
			b := []byte(v.Format(SQLiteTimestampFormats[0]))
			rv = C._sqlite3_bind_text(s.s, n, (*C.char)(unsafe.Pointer(&b[0])), C.int(len(b)))
		}
		if rv != C.SQLITE_OK {
			return s.c.lastError()
		}
	}
	return nil
}

// Query the statement with arguments. Return records.
func (s *SQLiteStmt) Query(args []driver.Value) (driver.Rows, error) {
	list := make([]namedValue, len(args))
	for i, v := range args {
		list[i] = namedValue{
			Ordinal: i + 1,
			Value:   v,
		}
	}
	return s.query(context.Background(), list)
}

func (s *SQLiteStmt) query(ctx context.Context, args []namedValue) (driver.Rows, error) {
	if err := s.bind(args); err != nil {
		return nil, err
	}

	rows := &SQLiteRows{
		s:        s,
		nc:       int(C.sqlite3_column_count(s.s)),
		cols:     nil,
		decltype: nil,
		cls:      s.cls,
		done:     make(chan struct{}),
	}

	go func(db *C.sqlite3) {
		select {
		case <-ctx.Done():
			select {
			case <-rows.done:
			default:
				C.sqlite3_interrupt(db)
				rows.Close()
			}
		case <-rows.done:
		}
	}(s.c.db)

	return rows, nil
}

// LastInsertId teturn last inserted ID.
func (r *SQLiteResult) LastInsertId() (int64, error) {
	return r.id, nil
}

// RowsAffected return how many rows affected.
func (r *SQLiteResult) RowsAffected() (int64, error) {
	return r.changes, nil
}

// Exec execute the statement with arguments. Return result object.
func (s *SQLiteStmt) Exec(args []driver.Value) (driver.Result, error) {
	list := make([]namedValue, len(args))
	for i, v := range args {
		list[i] = namedValue{
			Ordinal: i + 1,
			Value:   v,
		}
	}
	return s.exec(context.Background(), list)
}

func (s *SQLiteStmt) exec(ctx context.Context, args []namedValue) (driver.Result, error) {
	if err := s.bind(args); err != nil {
		C.sqlite3_reset(s.s)
		C.sqlite3_clear_bindings(s.s)
		return nil, err
	}

	done := make(chan struct{})
	defer close(done)
	go func(db *C.sqlite3) {
		select {
		case <-ctx.Done():
			C.sqlite3_interrupt(db)
		case <-done:
		}
	}(s.c.db)

	var rowid, changes C.longlong
	rv := C._sqlite3_step(s.s, &rowid, &changes)
	if rv != C.SQLITE_ROW && rv != C.SQLITE_OK && rv != C.SQLITE_DONE {
		err := s.c.lastError()
		C.sqlite3_reset(s.s)
		C.sqlite3_clear_bindings(s.s)
		return nil, err
	}

	return &SQLiteResult{id: int64(rowid), changes: int64(changes)}, nil
}

// Close the rows.
func (rc *SQLiteRows) Close() error {
	if rc.s.closed {
		return nil
	}
	if rc.done != nil {
		close(rc.done)
	}
	if rc.cls {
		return rc.s.Close()
	}
	rv := C.sqlite3_reset(rc.s.s)
	if rv != C.SQLITE_OK {
		return rc.s.c.lastError()
	}
	return nil
}

// Columns return column names.
func (rc *SQLiteRows) Columns() []string {
	if rc.nc != len(rc.cols) {
		rc.cols = make([]string, rc.nc)
		for i := 0; i < rc.nc; i++ {
			rc.cols[i] = C.GoString(C.sqlite3_column_name(rc.s.s, C.int(i)))
		}
	}
	return rc.cols
}

// DeclTypes return column types.
func (rc *SQLiteRows) DeclTypes() []string {
	if rc.decltype == nil {
		rc.decltype = make([]string, rc.nc)
		for i := 0; i < rc.nc; i++ {
			rc.decltype[i] = strings.ToLower(C.GoString(C.sqlite3_column_decltype(rc.s.s, C.int(i))))
		}
	}
	return rc.decltype
}

// Next move cursor to next.
func (rc *SQLiteRows) Next(dest []driver.Value) error {
	rv := C.sqlite3_step(rc.s.s)
	if rv == C.SQLITE_DONE {
		return io.EOF
	}
	if rv != C.SQLITE_ROW {
		rv = C.sqlite3_reset(rc.s.s)
		if rv != C.SQLITE_OK {
			return rc.s.c.lastError()
		}
		return nil
	}

	rc.DeclTypes()

	for i := range dest {
		switch C.sqlite3_column_type(rc.s.s, C.int(i)) {
		case C.SQLITE_INTEGER:
			val := int64(C.sqlite3_column_int64(rc.s.s, C.int(i)))
			switch rc.decltype[i] {
			case "timestamp", "datetime", "date":
				var t time.Time
				// Assume a millisecond unix timestamp if it's 13 digits -- too
				// large to be a reasonable timestamp in seconds.
				if val > 1e12 || val < -1e12 {
					val *= int64(time.Millisecond) // convert ms to nsec
				} else {
					val *= int64(time.Second) // convert sec to nsec
				}
				t = time.Unix(0, val).UTC()
				if rc.s.c.loc != nil {
					t = t.In(rc.s.c.loc)
				}
				dest[i] = t
			case "boolean":
				dest[i] = val > 0
			default:
				dest[i] = val
			}
		case C.SQLITE_FLOAT:
			dest[i] = float64(C.sqlite3_column_double(rc.s.s, C.int(i)))
		case C.SQLITE_BLOB:
			p := C.sqlite3_column_blob(rc.s.s, C.int(i))
			if p == nil {
				dest[i] = nil
				continue
			}
			n := int(C.sqlite3_column_bytes(rc.s.s, C.int(i)))
			switch dest[i].(type) {
			case sql.RawBytes:
				dest[i] = (*[1 << 30]byte)(unsafe.Pointer(p))[0:n]
			default:
				slice := make([]byte, n)
				copy(slice[:], (*[1 << 30]byte)(unsafe.Pointer(p))[0:n])
				dest[i] = slice
			}
		case C.SQLITE_NULL:
			dest[i] = nil
		case C.SQLITE_TEXT:
			var err error
			var timeVal time.Time

			n := int(C.sqlite3_column_bytes(rc.s.s, C.int(i)))
			s := C.GoStringN((*C.char)(unsafe.Pointer(C.sqlite3_column_text(rc.s.s, C.int(i)))), C.int(n))

			switch rc.decltype[i] {
			case "timestamp", "datetime", "date":
				var t time.Time
				s = strings.TrimSuffix(s, "Z")
				for _, format := range SQLiteTimestampFormats {
					if timeVal, err = time.ParseInLocation(format, s, time.UTC); err == nil {
						t = timeVal
						break
					}
				}
				if err != nil {
					// The column is a time value, so return the zero time on parse failure.
					t = time.Time{}
				}
				if rc.s.c.loc != nil {
					t = t.In(rc.s.c.loc)
				}
				dest[i] = t
			default:
				dest[i] = []byte(s)
			}

		}
	}
	return nil
}