export function MatchingPartsFromJSON(json: any): MatchingParts {
    return MatchingPartsFromJSONTyped(json, false);
}


export function MatchingPartsFromJSONTyped(json: any, ignoreDiscriminator: boolean): MatchingParts {
    if ((json === undefined) || (json === null)) {
        return json;
    }
    return {

        'connected': ((json['connected'] as Array<any>).map(PartFromJSON)),
        'related': ((json['related'] as Array<any>).map(PartFromJSON)),
    };
}


export function MatchingPartsToJSON(value?: MatchingParts | null): any {
    if (value === undefined) {
        return undefined;
    }
    if (value === null) {
        return null;
    }
    return {

        'connected': ((value.connected as Array<any>).map(PartToJSON)),
        'related': ((value.related as Array<any>).map(PartToJSON)),
    };
}


/**
 * Contains all the matching parts
 * @export
 * @interface MatchingParts
 */
export interface MatchingParts {
    /**
     * List of all the connected parts
     * @type {Array<Part>}
     * @memberof MatchingParts
     */
    connected: Array<Part>;
    /**
     * List of all the related parts
     * @type {Array<Part>}
     * @memberof MatchingParts
     */
    related: Array<Part>;
}


/**
 * Searches for a TSLint configuration and returns the data from the config.
 * @param configFile A path to a config file, this can be null if the location of a config is not known
 * @param inputFileLocation A path to the current file being linted. This is the starting location
 * of the search for a configuration.
 * @returns A TSLint configuration object
 */
export function findConfiguration(configFile: string, inputFilePath: string): IConfigurationFile {
    const configPath = findConfigurationPath(configFile, inputFilePath);
    return loadConfigurationFromPath(configPath);
}


/**
 * Searches for a TSLint configuration and returns the path to it.
 * Could return undefined if not configuration is found.
 * @param suppliedConfigFilePath A path to an known config file supplied by a user. Pass null here if
 * the location of the config file is not known and you want to search for one.
 * @param inputFilePath A path to the current file being linted. This is the starting location
 * of the search for a configuration.
 * @returns An absolute path to a tslint.json file, a path to a package.json file with a tslintConfig field
 * or undefined if neither can be found.
 */
export function findConfigurationPath(suppliedConfigFilePath: string, inputFilePath: string) {
    if (suppliedConfigFilePath != null) {
        if (!fs.existsSync(suppliedConfigFilePath)) {
            throw new Error(`Could not find config file at: ${path.resolve(suppliedConfigFilePath)}`);
        } else {
            return path.resolve(suppliedConfigFilePath);
        }
    } else {
        // search for tslint.json from input file location
        let configFilePath = findup(CONFIG_FILENAME, { cwd: inputFilePath, nocase: true });
        if (configFilePath != null && fs.existsSync(configFilePath)) {
            return path.resolve(configFilePath);
        }

        // search for package.json with tslintConfig property
        configFilePath = findup("package.json", { cwd: inputFilePath, nocase: true });
        if (configFilePath != null && require(configFilePath).tslintConfig != null) {
            return path.resolve(configFilePath);
        }

        // search for tslint.json in home directory
        const homeDir = getHomeDir();
        if (homeDir != null) {
            configFilePath = path.join(homeDir, CONFIG_FILENAME);
            if (fs.existsSync(configFilePath)) {
                return path.resolve(configFilePath);
            }
        }

        // no path could be found
        return undefined;
    }
}


/**
 * Used Node semantics to load a configuration file given configFilePath.
 * For example:
 * '/path/to/config' will be treated as an absolute path
 * './path/to/config' will be treated as a relative path
 * 'path/to/config' will attempt to load a to/config file inside a node module named path
 * @returns a configuration object for TSLint loaded from the file at configFilePath
 */
export function loadConfigurationFromPath(configFilePath: string): IConfigurationFile {
    if (configFilePath == null) {
        return DEFAULT_CONFIG;
    } else if (path.basename(configFilePath) === "package.json") {
        console.warn(PACKAGE_DEPRECATION_MSG);
        return require(configFilePath).tslintConfig;
    } else {
        const resolvedConfigFilePath = resolveConfigurationPath(configFilePath);
        let configFile: IConfigurationFile;
        if (path.extname(resolvedConfigFilePath) === ".json") {
            const fileContent = stripComments(fs.readFileSync(resolvedConfigFilePath)
            .toString()
            .replace(/^\uFEFF/, ""));
            configFile = JSON.parse(fileContent);
        } else {
            configFile = require(resolvedConfigFilePath);
            delete require.cache[resolvedConfigFilePath];
        }

        const configFileDir = path.dirname(resolvedConfigFilePath);

        configFile.rulesDirectory = getRulesDirectories(configFile.rulesDirectory, configFileDir);
        configFile.extends = arrayify(configFile.extends);

        for (const name of configFile.extends) {
            const baseConfigFilePath = resolveConfigurationPath(name, configFileDir);
            const baseConfigFile = loadConfigurationFromPath(baseConfigFilePath);
            configFile = extendConfigurationFile(configFile, baseConfigFile);
        }
        return configFile;
    }
}


/**
 * Resolve configuration file path or node_module reference
 * @param filePath Relative ("./path"), absolute ("/path"), node module ("path"), or built-in ("tslint:path")
 */
function resolveConfigurationPath(filePath: string, relativeTo?: string) {
    const matches = filePath.match(BUILT_IN_CONFIG);
    const isBuiltInConfig = matches != null;
    if (isBuiltInConfig) {
        const configName = matches[1];
        try {
            return require.resolve(`./configs/${configName}`);
        } catch (err) {
            throw new Error(`${filePath} is not a built-in config, try "tslint:recommended" instead.`);
        }
    }

    const basedir = relativeTo || process.cwd();
    try {
        return resolve.sync(filePath, { basedir });
    } catch (err) {
        try {
            return require.resolve(filePath);
        } catch (err) {
            throw new Error(`Invalid "extends" configuration value - could not require "${filePath}". ` +
                "Review the Node lookup algorithm (https://nodejs.org/api/modules.html#modules_all_together) " +
                "for the approximate method TSLint uses to find the referenced configuration file.");
        }
    }
}


export function extendConfigurationFile(config: IConfigurationFile, baseConfig: IConfigurationFile): IConfigurationFile {
    let combinedConfig: IConfigurationFile = {};

    const baseRulesDirectory = arrayify(baseConfig.rulesDirectory);
    const configRulesDirectory = arrayify(config.rulesDirectory);
    combinedConfig.rulesDirectory = configRulesDirectory.concat(baseRulesDirectory);

    combinedConfig.rules = {};
    for (const name of Object.keys(objectify(baseConfig.rules))) {
        combinedConfig.rules[name] = baseConfig.rules[name];
    }
    for (const name of Object.keys(objectify(config.rules))) {
        combinedConfig.rules[name] = config.rules[name];
    }

    return combinedConfig;
}


function getHomeDir() {
    const environment = global.process.env;
    const paths = [
        environment.USERPROFILE,
        environment.HOME,
        environment.HOMEPATH,
        environment.HOMEDRIVE + environment.HOMEPATH,
    ];

    for (const homePath of paths) {
        if (homePath != null && fs.existsSync(homePath)) {
            return homePath;
        }
    }
}


export function getRelativePath(directory: string, relativeTo?: string): string {
    if (directory != null) {
        const basePath = relativeTo || process.cwd();
        return path.resolve(basePath, directory);
    }
}


/**
 * @param directories A path(s) to a directory of custom rules
 * @param relativeTo A path that directories provided are relative to.
 * For example, if the directories come from a tslint.json file, this path
 * should be the path to the tslint.json file.
 * @return An array of absolute paths to directories potentially containing rules
 */
export function getRulesDirectories(directories: string | string[], relativeTo?: string): string[] {
    const rulesDirectories = arrayify(directories).map((dir) => getRelativePath(dir, relativeTo));

    for (const directory of rulesDirectories) {
        if (!fs.existsSync(directory)) {
            throw new Error(`Could not find custom rule directory: ${directory}`);
        }
    }

    return rulesDirectories;
}


(dir) => getRelativePath(dir, relativeTo)


export interface IConfigurationFile {
    extends?: string | string[];
    linterOptions?: {
        typeCheck?: boolean,
    };
    rulesDirectory?: string | string[];
    rules?: any;
}


({ privilegesEndpoint, children }: Props) => {
  const { isLoading, error, data: privilegesData } = useRequest({
    path: privilegesEndpoint,
    method: 'get',
  });

  const value = {
    isLoading,
    privileges: isLoading ? { ...initialValue.privileges } : privilegesData,
    capabilities: { ...initialCapabalities },
    apiError: error ? (error as Error) : null,
  };

  const hasPrivilege = hasPrivilegeFactory(value.privileges);

  value.capabilities.canGetTransform =
    hasPrivilege(['cluster', 'cluster:monitor/transform/get']) &&
    hasPrivilege(['cluster', 'cluster:monitor/transform/stats/get']);

  value.capabilities.canCreateTransform = hasPrivilege(['cluster', 'cluster:admin/transform/put']);

  value.capabilities.canDeleteTransform = hasPrivilege([
    'cluster',
    'cluster:admin/transform/delete',
  ]);

  value.capabilities.canPreviewTransform = hasPrivilege([
    'cluster',
    'cluster:admin/transform/preview',
  ]);

  value.capabilities.canStartStopTransform =
    hasPrivilege(['cluster', 'cluster:admin/transform/start']) &&
    hasPrivilege(['cluster', 'cluster:admin/transform/start_task']) &&
    hasPrivilege(['cluster', 'cluster:admin/transform/stop']);

  return (
    <AuthorizationContext.Provider value={{ ...value }}


interface Authorization {
  isLoading: boolean;
  apiError: Error | null;
  privileges: Privileges;
  capabilities: Capabilities;
}


interface Props {
  privilegesEndpoint: string;
  children: React.ReactNode;
}


(props, ref) => (
  <ClustersOverviewNavFooter
    total={props.total || 0}


(props: ClustersOverviewFooterProps) => {
  const router = useRouter()

  const pressEnter = (e: React.KeyboardEvent<HTMLInputElement>) => {
    let el = e.target as HTMLInputElement
    router.query.page = el.value
    if (e.key == 'Enter' && parseInt(el.value) != props.currentPage) {
      if (parseInt(el.value) <= props.qtyPages) {
        router.push({
          query: { page: el.value }
        })
      }
    }
  }

  const onBlur = (e: React.FocusEvent<HTMLInputElement>) => {
    let el = e.target as HTMLInputElement
    if (parseInt(el.value) <= props.qtyPages && parseInt(el.value) != props.currentPage) {
      router.push({
        query: { page: el.value }
      })
    }
  }

  return (

            {props.total} {props.total > 1 ? 'Results' : 'Result'}

        {props.qtyPages > 1 && (
          <>

              Jump to page

              <input
                onKeyPress={e => pressEnter(e)}
                onBlur={e


(e: React.KeyboardEvent<HTMLInputElement>) => {
    let el = e.target as HTMLInputElement
    router.query.page = el.value
    if (e.key == 'Enter' && parseInt(el.value) != props.currentPage) {
      if (parseInt(el.value) <= props.qtyPages) {
        router.push({
          query: { page: el.value }
        })
      }
    }
  }


(e: React.FocusEvent<HTMLInputElement>) => {
    let el = e.target as HTMLInputElement
    if (parseInt(el.value) <= props.qtyPages && parseInt(el.value) != props.currentPage) {
      router.push({
        query: { page: el.value }
      })
    }
  }


e => pressEnter(e)


type ClustersOverviewFooterProps = {
  total: number
  currentPage: number
  pageSize: number
  qtyPages: number
  refer?: React.ForwardedRef<HTMLDivElement>
}


function BlogPost({post}) {
  const classes = useStyles();

  const disqusConfig = {
    shortname: 'world-of-tg',
    config:
    {
      url: window.location.href,
      identifier: post.guid,
      title: post.title,
    },
}

const input = Base64.atob(post.body)

  return (
    <Fragment>
    <SEO title={"TG Blog Post " + post.title}/>
    <Card className={classes.root}>
    <CardActionArea>
      <CardMedia
        className={classes.media}
        image={wotgImage}
        title={post.title}
      />
      <CardContent>
        <ReactMarkdown source={input}/>
        <DiscussionEmbed {...disqusConfig} />
      </CardContent>
    </CardActionArea>
  </Card>
  </Fragment>
  )
}


export default function AuthorBlogPost({guid}) {
  const classes = useStyles();
  const { loading, error, data } = useQuery(GET_POST, {
    variables: {
      guid: guid,
    },
  })

  return (
    <Fragment>
      <Grid container style={{ justifyContent: 'center' }}


loading ? (
            <CircularProgress style={{ color: 'white' }


export default class Line<T> extends React.Component<ProgressLineProp<T>> {
  public static defaultProps: ProgressLineProp<{}> = {
    prefixCls: 'w-progress',
    showText: true, // 是否显示进度条文字内容
    percent: 0, // 百分比（必填）
    width: 126, // 圆圈进度条画布宽度
    strokeWidth: 6, // 进度条大小设置
  }
  render() {
    const { prefixCls, style, className, showText, percent, format, strokeWidth, width, status, ...resetProps } = this.props;
    const cls = classnames(prefixCls, className, `${prefixCls}-line`, {
      [`${prefixCls}-show-text`]: showText,
      [`${prefixCls}-status-${status}`]: status,
      [`${prefixCls}-status-success`]: parseInt((percent as number).toString(), 10) >= 100,
    });
    let progressInfo;
    if (showText) {
      const progressStatus = parseInt((percent as number).toString(), 10) >= 100 && !('status' in this.props) ? 'success' : status;
      let percentView: React.ReactNode = `${percent}%`;
      if (progressStatus === 'exception') {
        percentView = <IconProgress type="circle-close" />;
      } else if (progressStatus === 'success') {
        percentView = <IconProgress type="circle-check" />;
      }
      progressInfo = <span className={`${prefixCls}-text`}>{format ? format(percent as number) : percentView};
    }
    const percentStyle = {
      width: `${percent}%`,
      height: strokeWidth,
    };
    return (

        <div className={`${prefixCls}-bar`}>
          <div className={`${prefixCls}-inner`}>
            <div className={`${prefixCls}-bg`} style={percentStyle} />

        {progressInfo}

    );
  }
}


export interface ProgressLineProp<T> extends ProgressCircleProps<T> {}


render() {
    const { prefixCls, style, className, showText, percent, format, strokeWidth, width, status, ...resetProps } = this.props;
    const cls = classnames(prefixCls, className, `${prefixCls}-line`, {
      [`${prefixCls}-show-text`]: showText,
      [`${prefixCls}-status-${status}`]: status,
      [`${prefixCls}-status-success`]: parseInt((percent as number).toString(), 10) >= 100,
    });
    let progressInfo;
    if (showText) {
      const progressStatus = parseInt((percent as number).toString(), 10) >= 100 && !('status' in this.props) ? 'success' : status;
      let percentView: React.ReactNode = `${percent}%`;
      if (progressStatus === 'exception') {
        percentView = <IconProgress type="circle-close" />;
      } else if (progressStatus === 'success') {
        percentView = <IconProgress type="circle-check" />;
      }
      progressInfo = <span className={`${prefixCls}-text`}>{format ? format(percent as number) : percentView};
    }
    const percentStyle = {
      width: `${percent}%`,
      height: strokeWidth,
    };
    return (

        <div className={`${prefixCls}-bar`}>
          <div className={`${prefixCls}-inner`}>
            <div className={`${prefixCls}-bg`} style={percentStyle} />

        {progressInfo}

    );
  }


format(percent as number) : percentView


(state: any) => {
    state.validators = {};

    return {
        ...state
    };
}


@Component
  export class Popover extends Vue {
    visible: boolean
    positionClass: string
    position: {
      left: number
      top: number
    }
  }


export const enum SuggestActionTypes {
  SUGGEST,
  FETCH_SUGGEST,
  SET_SUGGEST,
}


(part) => {
            let child: Node;
            switch (part.type) {
                case ParsedMessagePartType.TEXT:
                    child = this.createXmlRepresentationOfTextPart(<ParsedMessagePartText> part, rootElem);
                    break;
                case ParsedMessagePartType.START_TAG:
                    child = this.createXmlRepresentationOfStartTagPart((<ParsedMessagePartStartTag>part), rootElem);
                    break;
                case ParsedMessagePartType.END_TAG:
                    child = this.createXmlRepresentationOfEndTagPart((<ParsedMessagePartEndTag>part), rootElem);
                    break;
                case ParsedMessagePartType.EMPTY_TAG:
                    child = this.createXmlRepresentationOfEmptyTagPart((<ParsedMessagePartEmptyTag>part), rootElem);
                    break;
                case ParsedMessagePartType.PLACEHOLDER:
                    child = this.createXmlRepresentationOfPlaceholderPart((<ParsedMessagePartPlaceholder>part), rootElem);
                    break;
                case ParsedMessagePartType.ICU_MESSAGE_REF:
                    child = this.createXmlRepresentationOfICUMessageRefPart((<ParsedMessagePartICUMessageRef>part), rootElem);
                    break;
            }
            if (child) {
                rootElem.appendChild(child);
            }
        }


/**
     * Handle this element node.
     * This is called before the children are done.
     * @param elementNode elementNode
     * @param message message to be altered
     * @return true, if children should be processed too, false otherwise (children ignored then)
     */
protected processStartElement(elementNode: Element, message: ParsedMessage): boolean {
        const tagName = elementNode.tagName;
        const tagMapping = new TagMapping();
        if (tagName === 'x') {
            // placeholder are like <x id="INTERPOLATION"/> or <x id="INTERPOLATION_1">
            const id = elementNode.getAttribute('id');
            if (!id) {
                return; // should not happen
            }
            if (id.startsWith('INTERPOLATION')) {
                const index = this.parsePlaceholderIndexFromId(id);
                const displayValue = elementNode.getAttribute('equiv-text');
                message.addPlaceholder(index, displayValue);
            } else if (id.startsWith('ICU')) {
                const index = this.parseICUMessageRefIndexFromId(id);
                message.addICUMessageRef(index, null);
            } else if (id.startsWith('START_')) {
                const normalizedTagName = tagMapping.getTagnameFromStartTagPlaceholderName(id);
                if (normalizedTagName) {
                    const idcount = this.parseIdCountFromName(id);
                    message.addStartTag(normalizedTagName, idcount);
                }
            } else if (id.startsWith('CLOSE_')) {
                const normalizedTagName = tagMapping.getTagnameFromCloseTagPlaceholderName(id);
                if (normalizedTagName) {
                    message.addEndTag(normalizedTagName);
                }
            } else if (tagMapping.isEmptyTagPlaceholderName(id)) {
                const normalizedTagName = tagMapping.getTagnameFromEmptyTagPlaceholderName(id);
                if (normalizedTagName) {
                    const idcount = this.parseIdCountFromName(id);
                    message.addEmptyTag(normalizedTagName, idcount);
                }
            }
        }
        return true;
    }


/**
     * Handle end of this element node.
     * This is called after all children are processed.
     * @param elementNode elementNode
     * @param message message to be altered
     */
protected processEndElement(elementNode: Element, message: ParsedMessage) {
    }


/**
     * Parse id attribute of x element as placeholder index.
     * id can be "INTERPOLATION" or "INTERPOLATION_n"
     * @param id id
     * @return index
     */
private parsePlaceholderIndexFromId(id: string): number {
        let indexString = '';

        if (id === 'INTERPOLATION') {
            indexString = '0';
        } else {
            indexString = id.substring('INTERPOLATION_'.length);
        }
        return Number.parseInt(indexString, 10);
    }


/**
     * Parse id attribute of x element as placeholder index.
     * id can be "INTERPOLATION" or "INTERPOLATION_n"
     * @param id id
     * @return id as number
     */
private parseICUMessageRefIndexFromId(id: string): number {
        let indexString = '';

        if (id === 'ICU') {
            indexString = '0';
        } else {
            indexString = id.substring('ICU_'.length);
        }
        return Number.parseInt(indexString, 10);
    }


protected addXmlRepresentationToRoot(message: ParsedMessage, rootElem: Element) {
        message.parts().forEach((part) => {
            let child: Node;
            switch (part.type) {
                case ParsedMessagePartType.TEXT:
                    child = this.createXmlRepresentationOfTextPart(<ParsedMessagePartText> part, rootElem);
                    break;
                case ParsedMessagePartType.START_TAG:
                    child = this.createXmlRepresentationOfStartTagPart((<ParsedMessagePartStartTag>part), rootElem);
                    break;
                case ParsedMessagePartType.END_TAG:
                    child = this.createXmlRepresentationOfEndTagPart((<ParsedMessagePartEndTag>part), rootElem);
                    break;
                case ParsedMessagePartType.EMPTY_TAG:
                    child = this.createXmlRepresentationOfEmptyTagPart((<ParsedMessagePartEmptyTag>part), rootElem);
                    break;
                case ParsedMessagePartType.PLACEHOLDER:
                    child = this.createXmlRepresentationOfPlaceholderPart((<ParsedMessagePartPlaceholder>part), rootElem);
                    break;
                case ParsedMessagePartType.ICU_MESSAGE_REF:
                    child = this.createXmlRepresentationOfICUMessageRefPart((<ParsedMessagePartICUMessageRef>part), rootElem);
                    break;
            }
            if (child) {
                rootElem.appendChild(child);
            }
        });
    }


/**
     * the xml used for start tag in the message.
     * Returns an empty <x/>-Element with attributes id and ctype
     * @param part part
     * @param rootElem rootElem
     */
protected createXmlRepresentationOfStartTagPart(part: ParsedMessagePartStartTag, rootElem: Element): Node {
        const xElem = rootElem.ownerDocument.createElement('x');
        const tagMapping = new TagMapping();
        const idAttrib = tagMapping.getStartTagPlaceholderName(part.tagName(), part.idCounter());
        const ctypeAttrib = tagMapping.getCtypeForTag(part.tagName());
        const equivTextAttr = '<' + part.tagName() + '>';
        xElem.setAttribute('id', idAttrib);
        xElem.setAttribute('ctype', ctypeAttrib);
        xElem.setAttribute('equiv-text', equivTextAttr);
        return xElem;
    }


/**
     * the xml used for end tag in the message.
     * Returns an empty <x/>-Element with attributes id and ctype
     * @param part part
     * @param rootElem rootElem
     */
protected createXmlRepresentationOfEndTagPart(part: ParsedMessagePartEndTag, rootElem: Element): Node {
        const xElem = rootElem.ownerDocument.createElement('x');
        const tagMapping = new TagMapping();
        const idAttrib = tagMapping.getCloseTagPlaceholderName(part.tagName());
        const ctypeAttrib = 'x-' + part.tagName();
        xElem.setAttribute('id', idAttrib);
        xElem.setAttribute('ctype', ctypeAttrib);
        return xElem;
    }


/**
     * the xml used for empty tag in the message.
     * Returns an empty <x/>-Element with attributes id and ctype
     * @param part part
     * @param rootElem rootElem
     */
protected createXmlRepresentationOfEmptyTagPart(part: ParsedMessagePartEmptyTag, rootElem: Element): Node {
        const xElem = rootElem.ownerDocument.createElement('x');
        const tagMapping = new TagMapping();
        const idAttrib = tagMapping.getEmptyTagPlaceholderName(part.tagName(), part.idCounter());
        const ctypeAttrib = tagMapping.getCtypeForTag(part.tagName());
        const equivTextAttr = '<' + part.tagName() + '/>';
        xElem.setAttribute('id', idAttrib);
        xElem.setAttribute('ctype', ctypeAttrib);
        xElem.setAttribute('equiv-text', equivTextAttr);
        return xElem;
    }


/**
     * the xml used for placeholder in the message.
     * Returns an empty <x/>-Element with attribute id="INTERPOLATION" or id="INTERPOLATION_n"
     * @param part part
     * @param rootElem rootElem
     */
protected createXmlRepresentationOfPlaceholderPart(part: ParsedMessagePartPlaceholder, rootElem: Element): Node {
        const xElem = rootElem.ownerDocument.createElement('x');
        let idAttrib = 'INTERPOLATION';
        if (part.index() > 0) {
            idAttrib = 'INTERPOLATION_' + part.index().toString(10);
        }
        const equivTextAttr = part.disp();
        xElem.setAttribute('id', idAttrib);
        if (equivTextAttr) {
            xElem.setAttribute('equiv-text', equivTextAttr);
        }
        return xElem;
    }


/**
     * the xml used for icu message refs in the message.
     * @param part part
     * @param rootElem rootElem
     */
protected createXmlRepresentationOfICUMessageRefPart(part: ParsedMessagePartICUMessageRef, rootElem: Element): Node {
        const xElem = rootElem.ownerDocument.createElement('x');
        let idAttrib = 'ICU';
        if (part.index() > 0) {
            idAttrib = 'ICU_' + part.index().toString(10);
        }
        xElem.setAttribute('id', idAttrib);
        return xElem;
    }


(socket: Socket, resolve: (data: Buffer) => void) => (data: Buffer) => {
  socket.removeListener(DATA, handleData);
  resolve(data);
}


(data: Buffer) => {
  socket.removeListener(DATA, handleData);
  resolve(data);
}


async (
  socket: Socket,
  message: number[],
  includeChecksum = true,
  waitForResponse = true,
): Promise<Buffer> => {
  // prep the message
  if (includeChecksum) {
    let sum = 0;
    for (let index = 0; index < message.length; index++) {
      sum += message[index];
    }
    message.push(sum & 0xff);
  }

  return new Promise<Buffer>((resolve) => {
    if (waitForResponse) {
      socket.on(DATA, handleData(socket, resolve));
    }

    socket.write(Buffer.from(message));

    if (!waitForResponse) {
      resolve(null);
    }
  });
}


(resolve) => {
    if (waitForResponse) {
      socket.on(DATA, handleData(socket, resolve));
    }

    socket.write(Buffer.from(message));

    if (!waitForResponse) {
      resolve(null);
    }
  }


/**
 * 提交按钮
 */
export default function FormSubmitButton({ children }: { children: React.ReactNode }) {
    const context = useContext(FormContext);
    const [loading, setLoading] = useState(null);

    function clickHande(e: React.MouseEvent<HTMLButtonElement>) {
        setLoading(true);
        context.formMethods
            .submit(true)
            .then(() => {
                setLoading(false);
            })
            .catch(() => {
                setLoading(false);
            });
        e.stopPropagation();
        e.preventDefault();
    }

    return React.cloneElement(children as any, { onClick: clickHande, loading });
}


function clickHande(e: React.MouseEvent<HTMLButtonElement>) {
        setLoading(true);
        context.formMethods
            .submit(true)
            .then(() => {
                setLoading(false);
            })
            .catch(() => {
                setLoading(false);
            });
        e.stopPropagation();
        e.preventDefault();
    }


() => {
                setLoading(false);
            }


/**
 * Created by martin on 23.05.2017.
 * A Translation Unit in an XTB file.
 */
export declare class XtbTransUnit extends AbstractTransUnit implements ITransUnit {
    private _sourceTransUnitFromMaster;
    constructor(_element: Element, _id: string, _translationMessagesFile: ITranslationMessagesFile, _sourceTransUnitFromMaster: AbstractTransUnit);
    /**
     * Get content to translate.
     * Source parts are excluded here.
     * @return content to translate.
     */
    sourceContent(): string;
    /**
     * Test, wether setting of source content is supported.
     * If not, setSourceContent in trans-unit will do nothing.
     * xtb does not support this, all other formats do.
     */
    supportsSetSourceContent(): boolean;
    /**
     * Set new source content in the transunit.
     * Normally, this is done by ng-extract.
     * Method only exists to allow xliffmerge to merge missing changed source content.
     * @param newContent the new content.
     */
    setSourceContent(newContent: string): void;
    /**
     * Return a parser used for normalized messages.
     */
    protected messageParser(): AbstractMessageParser;
    /**
     * The original text value, that is to be translated, as normalized message.
     */
    createSourceContentNormalized(): ParsedMessage;
    /**
     * the translated value (containing all markup, depends on the concrete format used).
     */
    targetContent(): string;
    /**
     * the translated value, but all placeholders are replaced with {{n}} (starting at 0)
     * and all embedded html is replaced by direct html markup.
     */
    targetContentNormalized(): INormalizedMessage;
    /**
     * State of the translation.
     * (not supported in xmb)
     * If we have a master, we assumed it is translated if the content is not the same as the masters one.
     */
    nativeTargetState(): string;
    /**
     * Map an abstract state (new, translated, final) to a concrete state used in the xml.
     * Returns the state to be used in the xml.
     * @param state one of Constants.STATE...
     * @returns a native state (depends on concrete format)
     * @throws error, if state is invalid.
     */
    protected mapStateToNativeState(state: string): string;
    /**
     * Map a native state (found in the document) to an abstract state (new, translated, final).
     * Returns the abstract state.
     * @param nativeState nativeState
     */
    protected mapNativeStateToState(nativeState: string): string;
    /**
     * set state in xml.
     * (not supported in xmb)
     * @param nativeState nativeState
     */
    protected setNativeTargetState(nativeState: string): void;
    /**
     * All the source elements in the trans unit.
     * The source element is a reference to the original template.
     * It contains the name of the template file and a line number with the position inside the template.
     * It is just a help for translators to find the context for the translation.
     * This is set when using Angular 4.0 or greater.
     * Otherwise it just returns an empty array.
     */
    sourceReferences(): {
        sourcefile: string;
        linenumber: number;
    }[];
    /**
     * Test, wether setting of source refs is supported.
     * If not, setSourceReferences will do nothing.
     * xtb does not support this, all other formats do.
     */
    supportsSetSourceReferences(): boolean;
    /**
     * Set source ref elements in the transunit.
     * Normally, this is done by ng-extract.
     * Method only exists to allow xliffmerge to merge missing source refs.
     * @param sourceRefs the sourcerefs to set. Old ones are removed.
     */
    setSourceReferences(sourceRefs: {
        sourcefile: string;
        linenumber: number;
    }[]): void;
    /**
     * The description set in the template as value of the i18n-attribute.
     * e.g. i18n="mydescription".
     * In xtb only the master stores it.
     */
    description(): string;
    /**
     * The meaning (intent) set in the template as value of the i18n-attribute.
     * This is the part in front of the | symbol.
     * e.g. i18n="meaning|mydescription".
     * In xtb only the master stores it.
     */
    meaning(): string;
    /**
     * Test, wether setting of description and meaning is supported.
     * If not, setDescription and setMeaning will do nothing.
     * xtb does not support this, all other formats do.
     */
    supportsSetDescriptionAndMeaning(): boolean;
    /**
     * Change description property of trans-unit.
     * @param description description
     */
    setDescription(description: string): void;
    /**
     * Change meaning property of trans-unit.
     * @param meaning meaning
     */
    setMeaning(meaning: string): void;
    /**
     * Get all notes of the trans-unit.
     * There are NO notes in xmb/xtb
     */
    notes(): INote[];
    /**
     * Test, wether setting of notes is supported.
     * If not, setNotes will do nothing.
     * xtb does not support this, all other formats do.
     */
    supportsSetNotes(): boolean;
    /**
     * Add notes to trans unit.
     * @param newNotes the notes to add.
     * NOT Supported in xmb/xtb
     */
    setNotes(newNotes: INote[]): void;
    /**
     * Copy source to target to use it as dummy translation.
     * Returns a changed copy of this trans unit.
     * receiver is not changed.
     * (internal usage only, a client should call importNewTransUnit on ITranslationMessageFile)
     * In xtb there is nothing to do, because there is only a target, no source.
     */
    cloneWithSourceAsTarget(isDefaultLang: boolean, copyContent: boolean, targetFile: ITranslationMessagesFile): AbstractTransUnit;
    /**
     * Copy source to target to use it as dummy translation.
     * (internal usage only, a client should call createTranslationFileForLang on ITranslationMessageFile)
     */
    useSourceAsTarget(isDefaultLang: boolean, copyContent: boolean): void;
    /**
     * Set the translation to a given string (including markup).
     * @param translation translation
     */
    protected translateNative(translation: string): void;
}


/**
     * Get content to translate.
     * Source parts are excluded here.
     * @return content to translate.
     */
sourceContent(): string;


/**
     * Test, wether setting of source content is supported.
     * If not, setSourceContent in trans-unit will do nothing.
     * xtb does not support this, all other formats do.
     */
supportsSetSourceContent(): boolean;


/**
     * Set new source content in the transunit.
     * Normally, this is done by ng-extract.
     * Method only exists to allow xliffmerge to merge missing changed source content.
     * @param newContent the new content.
     */
setSourceContent(newContent: string): void;


/**
     * Return a parser used for normalized messages.
     */
protected messageParser(): AbstractMessageParser;


/**
     * The original text value, that is to be translated, as normalized message.
     */
createSourceContentNormalized(): ParsedMessage;


/**
     * the translated value (containing all markup, depends on the concrete format used).
     */
targetContent(): string;


/**
     * the translated value, but all placeholders are replaced with {{n}} (starting at 0)
     * and all embedded html is replaced by direct html markup.
     */
targetContentNormalized(): INormalizedMessage;


/**
     * State of the translation.
     * (not supported in xmb)
     * If we have a master, we assumed it is translated if the content is not the same as the masters one.
     */
nativeTargetState(): string;


/**
     * Map an abstract state (new, translated, final) to a concrete state used in the xml.
     * Returns the state to be used in the xml.
     * @param state one of Constants.STATE...
     * @returns a native state (depends on concrete format)
     * @throws error, if state is invalid.
     */
protected mapStateToNativeState(state: string): string;


/**
     * Map a native state (found in the document) to an abstract state (new, translated, final).
     * Returns the abstract state.
     * @param nativeState nativeState
     */
protected mapNativeStateToState(nativeState: string): string;


/**
     * set state in xml.
     * (not supported in xmb)
     * @param nativeState nativeState
     */
protected setNativeTargetState(nativeState: string): void;


/**
     * All the source elements in the trans unit.
     * The source element is a reference to the original template.
     * It contains the name of the template file and a line number with the position inside the template.
     * It is just a help for translators to find the context for the translation.
     * This is set when using Angular 4.0 or greater.
     * Otherwise it just returns an empty array.
     */
sourceReferences(): {
        sourcefile: string;
        linenumber: number;
    }[];


/**
     * Test, wether setting of source refs is supported.
     * If not, setSourceReferences will do nothing.
     * xtb does not support this, all other formats do.
     */
supportsSetSourceReferences(): boolean;


/**
     * Set source ref elements in the transunit.
     * Normally, this is done by ng-extract.
     * Method only exists to allow xliffmerge to merge missing source refs.
     * @param sourceRefs the sourcerefs to set. Old ones are removed.
     */
setSourceReferences(sourceRefs: {
        sourcefile: string;
        linenumber: number;
    }[]): void;


/**
     * The description set in the template as value of the i18n-attribute.
     * e.g. i18n="mydescription".
     * In xtb only the master stores it.
     */
description(): string;


/**
     * The meaning (intent) set in the template as value of the i18n-attribute.
     * This is the part in front of the | symbol.
     * e.g. i18n="meaning|mydescription".
     * In xtb only the master stores it.
     */
meaning(): string;


/**
     * Test, wether setting of description and meaning is supported.
     * If not, setDescription and setMeaning will do nothing.
     * xtb does not support this, all other formats do.
     */
supportsSetDescriptionAndMeaning(): boolean;


/**
     * Change description property of trans-unit.
     * @param description description
     */
setDescription(description: string): void;


/**
     * Change meaning property of trans-unit.
     * @param meaning meaning
     */
setMeaning(meaning: string): void;


/**
     * Get all notes of the trans-unit.
     * There are NO notes in xmb/xtb
     */
notes(): INote[];


/**
     * Test, wether setting of notes is supported.
     * If not, setNotes will do nothing.
     * xtb does not support this, all other formats do.
     */
supportsSetNotes(): boolean;


/**
     * Add notes to trans unit.
     * @param newNotes the notes to add.
     * NOT Supported in xmb/xtb
     */
setNotes(newNotes: INote[]): void;


/**
     * Copy source to target to use it as dummy translation.
     * Returns a changed copy of this trans unit.
     * receiver is not changed.
     * (internal usage only, a client should call importNewTransUnit on ITranslationMessageFile)
     * In xtb there is nothing to do, because there is only a target, no source.
     */
cloneWithSourceAsTarget(isDefaultLang: boolean, copyContent: boolean, targetFile: ITranslationMessagesFile): AbstractTransUnit;


/**
     * Copy source to target to use it as dummy translation.
     * (internal usage only, a client should call createTranslationFileForLang on ITranslationMessageFile)
     */
useSourceAsTarget(isDefaultLang: boolean, copyContent: boolean): void;


/**
     * Set the translation to a given string (including markup).
     * @param translation translation
     */
protected translateNative(translation: string): void;


(app: Application): any => {
  return {
    service: config.authentication.service,
    identifyUserProps: ['token', 'type'],
    sanitizeUserForClient: async (identityProvider: any): Promise<any> => {
      const authService = app.service('authentication')
      const accessToken = await (authService as any).createAccessToken({}, { subject: identityProvider.id.toString() })

      return {
        accessToken
      }
    },
    notifier: async (type: string, identityProvider: any): Promise<void> => {
      if (identityProvider.type !== 'password') {
        return
      }

      const appPath = path.dirname(requireMainFilename())
      const emailAccountTemplatesPath = path.join(appPath, '..', '..', 'server-core', 'email-templates', 'account')
      let hashLink
      let email
      let templatePath
      let compiledHTML
      const mailSender = config.email.from

      switch (type) {
        case 'resendVerifySignup': // sending the identityProvider the verification email
          hashLink = getLink('verify', identityProvider.verifyToken)
          templatePath = path.join(emailAccountTemplatesPath, 'verify-email.pug')
          compiledHTML = pug.compileFile(templatePath)({
            logo: '',
            name: identityProvider.token,
            hashLink
          })

          email = {
            from: mailSender,
            to: identityProvider.token,
            subject: 'Confirm Signup',
            html: compiledHTML
          }

          return await sendEmail(app, email)

        case 'verifySignup': // confirming verification
          hashLink = getLink('verify', identityProvider.verifyToken)
          templatePath = path.join(emailAccountTemplatesPath, 'email-verified.pug')
          compiledHTML = pug.compileFile(templatePath)({
            logo: '',
            name: identityProvider.token,
            hashLink
          })

          email = {
            from: mailSender,
            to: identityProvider.token,
            subject: 'Thank you, your email has been verified',
            html: compiledHTML
          }
          return await sendEmail(app, email)

        case 'sendResetPwd':
          hashLink = getLink('reset', identityProvider.resetToken)
          templatePath = path.join(emailAccountTemplatesPath, 'reset-password.pug')

          compiledHTML = pug.compileFile(templatePath)({
            logo: '',
            name: identityProvider.token,
            hashLink
          })

          email = {
            from: mailSender,
            to: identityProvider.token,
            subject: 'Reset Password',
            html: compiledHTML
          }

          return await sendEmail(app, email)

        case 'resetPwd':
          hashLink = getLink('reset', identityProvider.resetToken)
          templatePath = path.join(emailAccountTemplatesPath, 'password-was-reset.pug')

          compiledHTML = pug.compileFile(templatePath)({
            logo: '',
            name: identityProvider.token,
            hashLink
          })

          email = {
            from: mailSender,
            to: identityProvider.token,
            subject: 'Your password was reset',
            html: compiledHTML
          }

          return await sendEmail(app, email)

        case 'passwordChange':
          templatePath = path.join(emailAccountTemplatesPath, 'password-change.pug')

          compiledHTML = pug.compileFile(templatePath)({
            logo: '',
            name: identityProvider.token
          })

          email = {
            from: mailSender,
            to: identityProvider.email,
            subject: 'Your password was changed',
            html: compiledHTML
          }

          return await sendEmail(app, email)

        case 'identityChange':
          hashLink = getLink('verifyChanges', identityProvider.verifyToken)

          templatePath = path.join(emailAccountTemplatesPath, 'identity-change.pug')

          compiledHTML = pug.compileFile(templatePath)({
            logo: '',
            name: identityProvider.token,
            hashLink,
            changes: identityProvider.verifyChanges
          })

          email = {
            from: mailSender,
            to: identityProvider.token,
            subject: 'Your account was changed. Please verify the changes',
            html: compiledHTML
          }
          return await sendEmail(app, email)

        default:
          break
      }
    }
  }
}


async (identityProvider: any): Promise<any> => {
      const authService = app.service('authentication')
      const accessToken = await (authService as any).createAccessToken({}, { subject: identityProvider.id.toString() })

      return {
        accessToken
      }
    }


async (type: string, identityProvider: any): Promise<void> => {
      if (identityProvider.type !== 'password') {
        return
      }

      const appPath = path.dirname(requireMainFilename())
      const emailAccountTemplatesPath = path.join(appPath, '..', '..', 'server-core', 'email-templates', 'account')
      let hashLink
      let email
      let templatePath
      let compiledHTML
      const mailSender = config.email.from

      switch (type) {
        case 'resendVerifySignup': // sending the identityProvider the verification email
          hashLink = getLink('verify', identityProvider.verifyToken)
          templatePath = path.join(emailAccountTemplatesPath, 'verify-email.pug')
          compiledHTML = pug.compileFile(templatePath)({
            logo: '',
            name: identityProvider.token,
            hashLink
          })

          email = {
            from: mailSender,
            to: identityProvider.token,
            subject: 'Confirm Signup',
            html: compiledHTML
          }

          return await sendEmail(app, email)

        case 'verifySignup': // confirming verification
          hashLink = getLink('verify', identityProvider.verifyToken)
          templatePath = path.join(emailAccountTemplatesPath, 'email-verified.pug')
          compiledHTML = pug.compileFile(templatePath)({
            logo: '',
            name: identityProvider.token,
            hashLink
          })

          email = {
            from: mailSender,
            to: identityProvider.token,
            subject: 'Thank you, your email has been verified',
            html: compiledHTML
          }
          return await sendEmail(app, email)

        case 'sendResetPwd':
          hashLink = getLink('reset', identityProvider.resetToken)
          templatePath = path.join(emailAccountTemplatesPath, 'reset-password.pug')

          compiledHTML = pug.compileFile(templatePath)({
            logo: '',
            name: identityProvider.token,
            hashLink
          })

          email = {
            from: mailSender,
            to: identityProvider.token,
            subject: 'Reset Password',
            html: compiledHTML
          }

          return await sendEmail(app, email)

        case 'resetPwd':
          hashLink = getLink('reset', identityProvider.resetToken)
          templatePath = path.join(emailAccountTemplatesPath, 'password-was-reset.pug')

          compiledHTML = pug.compileFile(templatePath)({
            logo: '',
            name: identityProvider.token,
            hashLink
          })

          email = {
            from: mailSender,
            to: identityProvider.token,
            subject: 'Your password was reset',
            html: compiledHTML
          }

          return await sendEmail(app, email)

        case 'passwordChange':
          templatePath = path.join(emailAccountTemplatesPath, 'password-change.pug')

          compiledHTML = pug.compileFile(templatePath)({
            logo: '',
            name: identityProvider.token
          })

          email = {
            from: mailSender,
            to: identityProvider.email,
            subject: 'Your password was changed',
            html: compiledHTML
          }

          return await sendEmail(app, email)

        case 'identityChange':
          hashLink = getLink('verifyChanges', identityProvider.verifyToken)

          templatePath = path.join(emailAccountTemplatesPath, 'identity-change.pug')

          compiledHTML = pug.compileFile(templatePath)({
            logo: '',
            name: identityProvider.token,
            hashLink,
            changes: identityProvider.verifyChanges
          })

          email = {
            from: mailSender,
            to: identityProvider.token,
            subject: 'Your account was changed. Please verify the changes',
            html: compiledHTML
          }
          return await sendEmail(app, email)

        default:
          break
      }
    }


function save() {
      if (previousValues && Object.keys(previousValues).length && !isEqual(previousValues, values)) {
        onSave(values)
      }
    }


(value, ref) => {
  return () => {
    ref.current = value
  }
}


() => {
    ref.current = value
  }


(value) => {
  const ref = React.useRef()
  React.useEffect(handleUseEffectToSetValueToCurrentRef(value, ref))
  return ref.current
}


(previousValues, values, onSave) => {
  return () => {
    function save() {
      if (previousValues && Object.keys(previousValues).length && !isEqual(previousValues, values)) {
        onSave(values)
      }
    }
    save()
  }
}


() => {
    function save() {
      if (previousValues && Object.keys(previousValues).length && !isEqual(previousValues, values)) {
        onSave(values)
      }
    }
    save()
  }


({ formik: { values }, onSave }) => {
  const previousValues = usePrevious(values) || {}
  React.useEffect(handleUseEffectToTriggerAutoSave(previousValues, values, onSave), [onSave, previousValues, values])
  return null
}


export interface FormikContext {
  formik: FormikContextType<any>
}


export interface OwnProps {
  onSave: (values: any) => void
}


export type FormikAutoSaveProps = FormikContext & OwnProps


export type Context = {
  bot: Probot
  github: {
    getInstallationOctokit: (
      logger: Logger,
      installationId: number | undefined,
    ) => ExtendedOctokit
  }
  logger: Logger
  database: {
    wrap: <T>(wrap: WithDatabaseClient<T>) => Promise<T>
    wrapForDynamicQuery: <T>(
      ...args: Parameters<WithDatabaseClientForDynamicQuery<T>>
    ) => ReturnType<WithDatabaseClientForDynamicQuery<T>>
  }
}


type IssueToProjectFieldRuleCreationInput = {
  project_number: number
  project_field: string | null
  project_field_value: string | null
  filter?: string | null
}


type IssueToProjectFieldRuleUpdateInput =
  IssueToProjectFieldRuleCreationInput & {
    github_owner: string
    github_name: string
  }


export type IssueToProjectFieldRule = IssueToProjectFieldRuleUpdateInput & {
  id: number
}


(count) =>
    count > 1 ? `${count} actieve filters` : `${count} filter actief`


(count) =>
    count > 1
      ? `${count.toLocaleString()} rijen geselecteerd`
      : `${count.toLocaleString()} rij geselecteerd`


(visibleCount, totalCount) =>
    `${visibleCount.toLocaleString()} van ${totalCount.toLocaleString()}`


async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.setGlobalPrefix('api')
  await app.listen(5000);
}


(type, i) => (
            <div key={i}>
                {i === 0 ? "=" : "|"


export class TypeAliasTable extends React.PureComponent<ITypeAliasTableProps> {
    public static contextTypes = DocumentationContextTypes;

    public static displayName = "Docs2.TypeAliasTable";

    public context: IDocumentationContext;

    public render() {
        const { data } = this.props;
        const { renderBlock, renderType } = this.context;
        const aliases = data.type.split(" | ").map((type, i) => (
            <div key={i}>
                {i === 0 ? "=" : "|"}


export interface ITypeAliasTableProps extends IProps {
    data: ITsTypeAlias;
}


public render() {
        const { data } = this.props;
        const { renderBlock, renderType } = this.context;
        const aliases = data.type.split(" | ").map((type, i) => (
            <div key={i}>
                {i === 0 ? "=" : "|"}


classNames("docs-modifiers", this


renderBlock(data


() => client


({ fs, jsonRPCLocalProviderManager, builderManager, createJSONRPCLocalProviderManager }) => {
      const browserLocalClient = new BrowserLocalClient(builderManager, jsonRPCLocalProviderManager);

      return {
        getFileSystem: () => fs,
        getJSONRPCLocalProviderManager: () => jsonRPCLocalProviderManager,
        getBrowserLocalClient: () => browserLocalClient,
        createJSONRPCLocalProviderManager,
      };
    }


() => fs


() => jsonRPCLocalProviderManager


() => browserLocalClient


(options: ExportsOptions, packagesIn = packages) =>
  packagesIn.reduce<ReadonlyArray<PathWithExports>>(
    (acc, { name, path, exports }) =>
      acc.concat({
        name,
        path,
        exports: exports(options),
      }),
    [],
  )


(acc, { name, path, exports }) =>
      acc.concat({
        name,
        path,
        exports: exports(options),
      })


export interface ExportsOptions {
  readonly fs: FileSystem;
  readonly jsonRPCLocalProviderManager: WorkerManager<typeof JSONRPCLocalProvider>;
  readonly builderManager: WorkerManager<typeof Builder>;
  readonly createJSONRPCLocalProviderManager: () => Promise<WorkerManager<typeof JSONRPCLocalProvider>>;
}


export interface PackageConfig {
  readonly name: string;
  readonly path: string;
  readonly exports: (options: ExportsOptions) => Exports;
}


export interface PathWithExports {
  readonly name: string;
  readonly path: string;
  readonly exports: Exports;
}


() => {
  const files = useSelector((state: RootState) => state.file.files);
  const step = useSelector((state: RootState) => state.ui.movingStep);

  let render;

  if (!files.length) {
    render = (
      <div className={styles.dropFiles}>
        <FileDropzone />
      </div>


(state: RootState) => state.file.files


(state: RootState) => state.ui.movingStep


(f: FileManager) => !f.edited


(f: FileManager) => f.edited


() => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ],
    });
  });

  it('should create the app', async(() => {
    let fixture = TestBed.createComponent(AppComponent);
    let app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  }));

  /*
  it(`should have as title 'app works!'`, async(() => {
    let fixture = TestBed.createComponent(AppComponent);
    let app = fixture.debugElement.componentInstance;
    expect(app.title).toEqual('app works!');
  }));

  it('should render title in a h1 tag', async(() => {
    let fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    let compiled = fixture.debugElement.nativeElement;
    expect(compiled.querySelector('h1').textContent).toContain('app works!');
  }));
  */
}


() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ],
    });
  }


() => {
    let fixture = TestBed.createComponent(AppComponent);
    let app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  }


async (ctx, next) => {
            const win = BrowserWindow.getFocusedWindow();
            if (win) {
                win.webContents.openDevTools({
                    mode: 'detach'
                });

                setTimeout(() => win.focus(), 2000);
            }

            ctx.body = {
                message: 'success'
            };
        }


() => win.focus()


async (ctx, next) => {
            const json = require('../../../package.json');
            ctx.body = json.version;
        }


async (ctx, next) => {
            ctx.body = os.platform();
        }


async (ctx, next) => {
            ctx.body = this.webServer.address;
        }


async (ctx, next) => {
            ctx.body = Settings.OpenedFile;
        }


async (ctx, next) => {
            Settings.OpenedFile = ctx.request.body.value;

            ctx.body = {
                message: 'success'
            };
        }


export default class ToolsRouter {
    // Public members
    public router: KoaRouter;
    public webServer: WebServer;

    /**
     * Constructor
     * @param application: the KOA application
     */
    constructor (webServer: WebServer) {
        this.webServer = webServer;
        this.router = new KoaRouter();

        // Create routes
        this.openDevTools();
        this.getVersion();
        this.getOsPlatform();
        this.getAddress();

        this.getOpenedFile();
        this.setOpenedFile();

        webServer.localApplication.use(this.router.routes());
        webServer.externApplication.use(this.router.routes());
    }

    /**
     * Opens the devtools for the current focused window
     */
    protected openDevTools (): void {
        this.router.get('/devTools', async (ctx, next) => {
            const win = BrowserWindow.getFocusedWindow();
            if (win) {
                win.webContents.openDevTools({
                    mode: 'detach'
                });

                setTimeout(() => win.focus(), 2000);
            }

            ctx.body = {
                message: 'success'
            };
        });
    }

    /**
     * Returns the editor's version set from the package.json
     */
    protected getVersion (): void {
        this.router.get('/version', async (ctx, next) => {
            const json = require('../../../package.json');
            ctx.body = json.version;
        });
    }

    /**
     * Returns the installer path according to the current platform
     */
    protected getOsPlatform (): void {
        this.router.get('/osplatform', async (ctx, next) => {
            ctx.body = os.platform();
        });
    }

    /**
     * Gets the current server address
     */
    protected getAddress (): void {
        this.router.get('/address', async (ctx, next) => {
            ctx.body = this.webServer.address;
        });
    }

    /**
     * Returns the opened file path
     */
    protected getOpenedFile (): void {
        this.router.get('/openedFile', async (ctx, next) => {
            ctx.body = Settings.OpenedFile;
        })
    }

    /**
     * Sets the opened file path
     */
    protected setOpenedFile (): void {
        this.router.post('/openedFile', async (ctx, next) => {
            Settings.OpenedFile = ctx.request.body.value;

            ctx.body = {
                message: 'success'
            };
        });
    }
}


/**
     * Opens the devtools for the current focused window
     */
protected openDevTools (): void {
        this.router.get('/devTools', async (ctx, next) => {
            const win = BrowserWindow.getFocusedWindow();
            if (win) {
                win.webContents.openDevTools({
                    mode: 'detach'
                });

                setTimeout(() => win.focus(), 2000);
            }

            ctx.body = {
                message: 'success'
            };
        });
    }


/**
     * Returns the editor's version set from the package.json
     */
protected getVersion (): void {
        this.router.get('/version', async (ctx, next) => {
            const json = require('../../../package.json');
            ctx.body = json.version;
        });
    }


/**
     * Returns the installer path according to the current platform
     */
protected getOsPlatform (): void {
        this.router.get('/osplatform', async (ctx, next) => {
            ctx.body = os.platform();
        });
    }


/**
     * Gets the current server address
     */
protected getAddress (): void {
        this.router.get('/address', async (ctx, next) => {
            ctx.body = this.webServer.address;
        });
    }


/**
     * Returns the opened file path
     */
protected getOpenedFile (): void {
        this.router.get('/openedFile', async (ctx, next) => {
            ctx.body = Settings.OpenedFile;
        })
    }


/**
     * Sets the opened file path
     */
protected setOpenedFile (): void {
        this.router.post('/openedFile', async (ctx, next) => {
            Settings.OpenedFile = ctx.request.body.value;

            ctx.body = {
                message: 'success'
            };
        });
    }


() => {
    afterEach(() => {
      sandbox.restore()
    })

    before(async () => {
      await db.reinitialize()
      await GeographyServer.start()
    })

    after(async () => {
      await GeographyServer.stop()
      await db.shutdown()
    })

    // Geography endpoints
    it('cannot POST one current geography (no auth)', done => {
      const geography = { geography_id: GEOGRAPHY_UUID, geography_json: LA_CITY_BOUNDARY }
      request
        .post(pathPrefix(`/geographies`))
        .set('Authorization', EMPTY_SCOPE)
        .send(geography)
        .expect(403)
        .end(err => {
          done(err)
        })
    })

    it('creates one current geography', done => {
      const geography = { name: 'LA', geography_id: GEOGRAPHY_UUID, geography_json: LA_CITY_BOUNDARY }

      request
        .post(pathPrefix(`/geographies`))
        .set('Authorization', GEOGRAPHIES_WRITE_SCOPE)
        .send(geography)
        .expect(201)
        .end(err => {
          done(err)
        })
    })

    it('cannot update one geography (no auth)', done => {
      const geography = { geography_id: GEOGRAPHY_UUID, geography_json: DISTRICT_SEVEN }
      request
        .put(pathPrefix(`/geographies/${GEOGRAPHY_UUID}`))
        .set('Authorization', EMPTY_SCOPE)
        .send(geography)
        .expect(403)
        .end(err => {
          done(err)
        })
    })

    it('verifies updating one geography', done => {
      const geography = { name: 'LA', geography_id: GEOGRAPHY_UUID, geography_json: DISTRICT_SEVEN }
      request
        .put(pathPrefix(`/geographies/${GEOGRAPHY_UUID}`))
        .set('Authorization', GEOGRAPHIES_WRITE_SCOPE)
        .send(geography)
        .expect(201)
        .end((err, result) => {
          test.value(result).hasHeader('content-type', APP_JSON)
          done(err)
        })
    })

    it('verifies cannot PUT bad geography', done => {
      const geography = { name: 'LA', geography_id: GEOGRAPHY_UUID, geography_json: 'garbage_json' }
      request
        .put(pathPrefix(`/geographies/${GEOGRAPHY_UUID}`))
        .set('Authorization', GEOGRAPHIES_WRITE_SCOPE)
        .send(geography)
        .expect(400)
        .end((err, result) => {
          test.value(result).hasHeader('content-type', APP_JSON)
          done(err)
        })
    })

    it('verifies cannot PUT non-existent geography', done => {
      const geography = { name: 'LA', geography_id: POLICY_UUID, geography_json: DISTRICT_SEVEN }
      request
        .put(pathPrefix(`/geographies/${POLICY_UUID}`))
        .set('Authorization', GEOGRAPHIES_WRITE_SCOPE)
        .send(geography)
        .expect(404)
        .end((err, result) => {
          test.value(result).hasHeader('content-type', APP_JSON)
          done(err)
        })
    })

    it('verifies cannot POST invalid geography', done => {
      const geography = { name: 'LA', geography_id: GEOGRAPHY_UUID, geography_json: 'garbage_json' }
      request
        .post(pathPrefix(`/geographies`))
        .set('Authorization', GEOGRAPHIES_WRITE_SCOPE)
        .send(geography)
        .expect(400)
        .end((err, result) => {
          test.value(result).hasHeader('content-type', APP_JSON)
          done(err)
        })
    })

    it('cannot POST duplicate geography', done => {
      const geography = { name: 'LA', geography_id: GEOGRAPHY_UUID, geography_json: LA_CITY_BOUNDARY }
      request
        .post(pathPrefix(`/geographies`))
        .set('Authorization', GEOGRAPHIES_WRITE_SCOPE)
        .send(geography)
        .expect(409)
        .end((err, result) => {
          test.value(result).hasHeader('content-type', APP_JSON)
          done(err)
        })
    })

    it('can publish a geography (correct auth)', async () => {
      await db.writeGeography({ name: 'Geography 2', geography_id: GEOGRAPHY2_UUID, geography_json: DISTRICT_SEVEN })
      const result = await request
        .put(pathPrefix(`/geographies/${GEOGRAPHY2_UUID}/publish`))
        .set('Authorization', GEOGRAPHIES_PUBLISH_SCOPE)
        .expect(200)
      test.value(result).hasHeader('content-type', APP_JSON)
      test.assert(result.body.version === GEOGRAPHY_AUTHOR_API_DEFAULT_VERSION)
      test.assert(result.body.data.geography.geography_id === GEOGRAPHY2_UUID)
      test.assert(result.body.data.geography.publish_date)
    })

    it('cannot publish a geography (wrong auth)', async () => {
      await request
        .put(pathPrefix(`/geographies/${GEOGRAPHY2_UUID}/publish`))
        .set('Authorization', EMPTY_SCOPE)
        .expect(403)
    })

    it('cannot delete a geography (incorrect auth)', async () => {
      await request
        .delete(pathPrefix(`/geographies/${GEOGRAPHY2_UUID}`))
        .set('Authorization', EMPTY_SCOPE)
        .expect(403)
    })

    it('can delete a geography (correct auth)', async () => {
      const testUUID = uuid()
      await db.writeGeography({ geography_id: testUUID, geography_json: LA_CITY_BOUNDARY, name: 'testafoo' })
      await db.writeGeographyMetadata({ geography_id: testUUID, geography_metadata: { foo: 'afoo' } })
      await request
        .delete(pathPrefix(`/geographies/${testUUID}`))
        .set('Authorization', GEOGRAPHIES_WRITE_SCOPE)
        .expect(200)
      await assert.rejects(
        async () => {
          await db.readSingleGeography(testUUID)
        },
        { name: 'NotFoundError' }
      )
      await assert.rejects(
        async () => {
          await db.readSingleGeographyMetadata(testUUID)
        },
        { name: 'NotFoundError' }
      )
    })

    it('cannot delete a published geography (correct auth)', async () => {
      await request
        .delete(pathPrefix(`/geographies/${GEOGRAPHY2_UUID}`))
        .set('Authorization', GEOGRAPHIES_WRITE_SCOPE)
        .expect(405)
    })

    it('sends the correct error code if something blows up on the backend during delete', async () => {
      sandbox.stub(db, 'deleteGeography').callsFake(function stubAThrow() {
        throw new Error('random backend err')
      })
      await request
        .delete(pathPrefix(`/geographies/${GEOGRAPHY_UUID}`))
        .set('Authorization', GEOGRAPHIES_WRITE_SCOPE)
        .expect(500)
    })
  }


() => {
      sandbox.restore()
    }


async () => {
      await db.reinitialize()
      await GeographyServer.start()
    }


async () => {
      await GeographyServer.stop()
      await db.shutdown()
    }


done => {
      const geography = { geography_id: GEOGRAPHY_UUID, geography_json: LA_CITY_BOUNDARY }
      request
        .post(pathPrefix(`/geographies`))
        .set('Authorization', EMPTY_SCOPE)
        .send(geography)
        .expect(403)
        .end(err => {
          done(err)
        })
    }


err => {
          done(err)
        }


done => {
      const geography = { name: 'LA', geography_id: GEOGRAPHY_UUID, geography_json: LA_CITY_BOUNDARY }

      request
        .post(pathPrefix(`/geographies`))
        .set('Authorization', GEOGRAPHIES_WRITE_SCOPE)
        .send(geography)
        .expect(201)
        .end(err => {
          done(err)
        })
    }


done => {
      const geography = { geography_id: GEOGRAPHY_UUID, geography_json: DISTRICT_SEVEN }
      request
        .put(pathPrefix(`/geographies/${GEOGRAPHY_UUID}`))
        .set('Authorization', EMPTY_SCOPE)
        .send(geography)
        .expect(403)
        .end(err => {
          done(err)
        })
    }


done => {
      const geography = { name: 'LA', geography_id: GEOGRAPHY_UUID, geography_json: DISTRICT_SEVEN }
      request
        .put(pathPrefix(`/geographies/${GEOGRAPHY_UUID}`))
        .set('Authorization', GEOGRAPHIES_WRITE_SCOPE)
        .send(geography)
        .expect(201)
        .end((err, result) => {
          test.value(result).hasHeader('content-type', APP_JSON)
          done(err)
        })
    }


(err, result) => {
          test.value(result).hasHeader('content-type', APP_JSON)
          done(err)
        }


done => {
      const geography = { name: 'LA', geography_id: GEOGRAPHY_UUID, geography_json: 'garbage_json' }
      request
        .put(pathPrefix(`/geographies/${GEOGRAPHY_UUID}`))
        .set('Authorization', GEOGRAPHIES_WRITE_SCOPE)
        .send(geography)
        .expect(400)
        .end((err, result) => {
          test.value(result).hasHeader('content-type', APP_JSON)
          done(err)
        })
    }


done => {
      const geography = { name: 'LA', geography_id: POLICY_UUID, geography_json: DISTRICT_SEVEN }
      request
        .put(pathPrefix(`/geographies/${POLICY_UUID}`))
        .set('Authorization', GEOGRAPHIES_WRITE_SCOPE)
        .send(geography)
        .expect(404)
        .end((err, result) => {
          test.value(result).hasHeader('content-type', APP_JSON)
          done(err)
        })
    }


done => {
      const geography = { name: 'LA', geography_id: GEOGRAPHY_UUID, geography_json: 'garbage_json' }
      request
        .post(pathPrefix(`/geographies`))
        .set('Authorization', GEOGRAPHIES_WRITE_SCOPE)
        .send(geography)
        .expect(400)
        .end((err, result) => {
          test.value(result).hasHeader('content-type', APP_JSON)
          done(err)
        })
    }


done => {
      const geography = { name: 'LA', geography_id: GEOGRAPHY_UUID, geography_json: LA_CITY_BOUNDARY }
      request
        .post(pathPrefix(`/geographies`))
        .set('Authorization', GEOGRAPHIES_WRITE_SCOPE)
        .send(geography)
        .expect(409)
        .end((err, result) => {
          test.value(result).hasHeader('content-type', APP_JSON)
          done(err)
        })
    }


async () => {
      await db.writeGeography({ name: 'Geography 2', geography_id: GEOGRAPHY2_UUID, geography_json: DISTRICT_SEVEN })
      const result = await request
        .put(pathPrefix(`/geographies/${GEOGRAPHY2_UUID}/publish`))
        .set('Authorization', GEOGRAPHIES_PUBLISH_SCOPE)
        .expect(200)
      test.value(result).hasHeader('content-type', APP_JSON)
      test.assert(result.body.version === GEOGRAPHY_AUTHOR_API_DEFAULT_VERSION)
      test.assert(result.body.data.geography.geography_id === GEOGRAPHY2_UUID)
      test.assert(result.body.data.geography.publish_date)
    }


async () => {
      await request
        .put(pathPrefix(`/geographies/${GEOGRAPHY2_UUID}/publish`))
        .set('Authorization', EMPTY_SCOPE)
        .expect(403)
    }


async () => {
      await request
        .delete(pathPrefix(`/geographies/${GEOGRAPHY2_UUID}`))
        .set('Authorization', EMPTY_SCOPE)
        .expect(403)
    }


async () => {
      const testUUID = uuid()
      await db.writeGeography({ geography_id: testUUID, geography_json: LA_CITY_BOUNDARY, name: 'testafoo' })
      await db.writeGeographyMetadata({ geography_id: testUUID, geography_metadata: { foo: 'afoo' } })
      await request
        .delete(pathPrefix(`/geographies/${testUUID}`))
        .set('Authorization', GEOGRAPHIES_WRITE_SCOPE)
        .expect(200)
      await assert.rejects(
        async () => {
          await db.readSingleGeography(testUUID)
        },
        { name: 'NotFoundError' }
      )
      await assert.rejects(
        async () => {
          await db.readSingleGeographyMetadata(testUUID)
        },
        { name: 'NotFoundError' }
      )
    }


async () => {
          await db.readSingleGeography(testUUID)
        }


async () => {
          await db.readSingleGeographyMetadata(testUUID)
        }


async () => {
      await request
        .delete(pathPrefix(`/geographies/${GEOGRAPHY2_UUID}`))
        .set('Authorization', GEOGRAPHIES_WRITE_SCOPE)
        .expect(405)
    }


async () => {
      sandbox.stub(db, 'deleteGeography').callsFake(function stubAThrow() {
        throw new Error('random backend err')
      })
      await request
        .delete(pathPrefix(`/geographies/${GEOGRAPHY_UUID}`))
        .set('Authorization', GEOGRAPHIES_WRITE_SCOPE)
        .expect(500)
    }


async () => {
      await db.reinitialize()
      await GeographyServer.start()
      await db.writeGeography({ name: 'Geography 1', geography_id: GEOGRAPHY_UUID, geography_json: LA_CITY_BOUNDARY })
      await db.writeGeography({ name: 'Geography 2', geography_id: GEOGRAPHY2_UUID, geography_json: DISTRICT_SEVEN })
      await db.publishGeography({ geography_id: GEOGRAPHY2_UUID })
    }


done => {
      request
        .get(pathPrefix(`/geographies/${GEOGRAPHY_UUID}/meta`))
        .set('Authorization', EMPTY_SCOPE)
        .expect(403)
        .end(err => {
          done(err)
        })
    }


done => {
      request
        .get(pathPrefix(`/geographies/${GEOGRAPHY_UUID}/meta`))
        .set('Authorization', EVENTS_READ_SCOPE)
        .expect(403)
        .end(err => {
          done(err)
        })
    }


async () => {
      const metadata = { some_arbitrary_thing: 'boop' }
      await request
        .put(pathPrefix(`/geographies/${GEOGRAPHY_UUID}/meta`))
        .set('Authorization', EMPTY_SCOPE)
        .send({ geography_id: GEOGRAPHY_UUID, geography_metadata: metadata })
        .expect(403)
    }


async () => {
      const metadata = { some_arbitrary_thing: 'boop' }
      await request
        .put(pathPrefix(`/geographies/${GEOGRAPHY_UUID}/meta`))
        .set('Authorization', EVENTS_READ_SCOPE)
        .send({ geography_id: GEOGRAPHY_UUID, geography_metadata: metadata })
        .expect(403)
    }


async () => {
      sandbox.stub(db, 'readBulkGeographyMetadata').callsFake(function stubAThrow() {
        throw new Error('err')
      })
      await request
        .get(pathPrefix(`/geographies/${GEOGRAPHY_UUID}/meta`))
        .set('Authorization', GEOGRAPHIES_READ_PUBLISHED_SCOPE)
        .expect(404)
    }


async () => {
      const metadata = { some_arbitrary_thing: 'boop' }
      const requestResult = await request
        .put(pathPrefix(`/geographies/${GEOGRAPHY_UUID}/meta`))
        .set('Authorization', GEOGRAPHIES_WRITE_SCOPE)
        .send({ geography_id: GEOGRAPHY_UUID, geography_metadata: metadata })
        .expect(201)
      test.assert(requestResult.body.version === GEOGRAPHY_AUTHOR_API_DEFAULT_VERSION)
      const result = await db.readSingleGeographyMetadata(GEOGRAPHY_UUID)
      test.assert(result.geography_metadata.some_arbitrary_thing === 'boop')
    }


async () => {
      const metadata = { some_arbitrary_thing: 'beep' }
      await request
        .put(pathPrefix(`/geographies/${GEOGRAPHY_UUID}/meta`))
        .set('Authorization', GEOGRAPHIES_WRITE_SCOPE)
        .send({ geography_id: GEOGRAPHY_UUID, geography_metadata: metadata })
        .expect(200)
      const result = await db.readSingleGeographyMetadata(GEOGRAPHY_UUID)
      test.assert(result.geography_metadata.some_arbitrary_thing === 'beep')
    }


async () => {
      const metadata = { some_arbitrary_thing: 'beep' }
      const nonexistentGeoUUID = uuid()
      await request
        .put(pathPrefix(`/geographies/${nonexistentGeoUUID}/meta`))
        .set('Authorization', GEOGRAPHIES_WRITE_SCOPE)
        .send({ geography_id: nonexistentGeoUUID, geography_metadata: metadata })
        .expect(404)
    }


async () => {
      await db.writeGeographyMetadata({ geography_id: GEOGRAPHY2_UUID, geography_metadata: { earth: 'isround' } })

      const result = await request
        .get(pathPrefix(`/geographies/meta`))
        .set('Authorization', GEOGRAPHIES_READ_UNPUBLISHED_SCOPE)
        .expect(200)
      test.assert(result.body.data.geography_metadata.length === 2)
      test.assert(result.body.version === GEOGRAPHY_AUTHOR_API_DEFAULT_VERSION)
      test.value(result).hasHeader('content-type', APP_JSON)
    }


async () => {
      const result = await request
        .get(pathPrefix(`/geographies/meta?get_published=true`))
        .set('Authorization', GEOGRAPHIES_READ_UNPUBLISHED_SCOPE)
        .expect(200)
      test.assert(result.body.data.geography_metadata.length === 1)
      test.assert(result.body.version === GEOGRAPHY_AUTHOR_API_DEFAULT_VERSION)
      test.value(result).hasHeader('content-type', APP_JSON)
    }


async () => {
      const result = await request
        .get(pathPrefix(`/geographies/meta?get_unpublished=true`))
        .set('Authorization', GEOGRAPHIES_READ_UNPUBLISHED_SCOPE)
        .expect(200)
      test.assert(result.body.data.geography_metadata.length === 1)
      test.assert(result.body.version === GEOGRAPHY_AUTHOR_API_DEFAULT_VERSION)
      test.value(result).hasHeader('content-type', APP_JSON)
    }


async () => {
      const result = await request
        .get(pathPrefix(`/geographies/meta`))
        .set('Authorization', GEOGRAPHIES_BOTH_READ_SCOPES)
        .expect(200)
      test.assert(result.body.data.geography_metadata.length === 2)
      test.assert(result.body.version === GEOGRAPHY_AUTHOR_API_DEFAULT_VERSION)
      test.value(result).hasHeader('content-type', APP_JSON)
    }


async () => {
      const result = await request
        .get(pathPrefix(`/geographies/meta?get_published=true`))
        .set('Authorization', GEOGRAPHIES_BOTH_READ_SCOPES)
        .expect(200)
      test.assert(result.body.data.geography_metadata.length === 1)
      test.assert(result.body.version === GEOGRAPHY_AUTHOR_API_DEFAULT_VERSION)
      test.value(result).hasHeader('content-type', APP_JSON)
    }


async () => {
      const result = await request
        .get(pathPrefix(`/geographies/meta`))
        .set('Authorization', GEOGRAPHIES_READ_PUBLISHED_SCOPE)
        .expect(200)
      test.assert(result.body.version === GEOGRAPHY_AUTHOR_API_DEFAULT_VERSION)
      test.assert(result.body.data.geography_metadata.length === 1)
      test.value(result).hasHeader('content-type', APP_JSON)
    }


async () => {
      await request
        .get(pathPrefix(`/geographies/meta?get_unpublished=true`))
        .set('Authorization', GEOGRAPHIES_READ_PUBLISHED_SCOPE)
        .expect(403)
    }


async () => {
      await request
        .get(pathPrefix(`/geographies/meta?get_unpublished=false`))
        .set('Authorization', EVENTS_READ_SCOPE)
        .expect(403)
    }


async () => {
      await request
        .get(pathPrefix(`/geographies/meta?get_published=false`))
        .set('Authorization', EMPTY_SCOPE)
        .expect(403)
    }


done => {
      request
        .get(pathPrefix(`/geographies/${GEOGRAPHY_UUID}/meta`))
        .set('Authorization', GEOGRAPHIES_READ_PUBLISHED_SCOPE)
        .expect(403)
        .end(err => {
          done(err)
        })
    }


done => {
      request
        .get(pathPrefix(`/geographies/${GEOGRAPHY_UUID}/meta`))
        .set('Authorization', GEOGRAPHIES_READ_UNPUBLISHED_SCOPE)
        .expect(200)
        .end((err, result) => {
          done(err)
        })
    }


(err, result) => {
          done(err)
        }


done => {
      const nonexistentID = uuid()
      request
        .get(pathPrefix(`/geographies/${nonexistentID}/meta`))
        .set('Authorization', GEOGRAPHIES_READ_PUBLISHED_SCOPE)
        .expect(404)
        .end((err, result) => {
          test.assert(result.body.error.name === `NotFoundError`)
          test.value(result).hasHeader('content-type', APP_JSON)
          done(err)
        })
    }


(err, result) => {
          test.assert(result.body.error.name === `NotFoundError`)
          test.value(result).hasHeader('content-type', APP_JSON)
          done(err)
        }


done => {
      const geography = {
        name: 'foo',
        geography_id: GEOGRAPHY_UUID,
        publish_date: 1589817834000,
        geography_json: LA_CITY_BOUNDARY
      }
      request
        .put(pathPrefix(`/geographies/${geography.geography_id}`))
        .set('Authorization', GEOGRAPHIES_WRITE_SCOPE)
        .send(geography)
        .expect(400)
        .end((err, result) => {
          test.assert(result.body.error.type === `ValidationError`)
          test.value(result).hasHeader('content-type', APP_JSON)
          done(err)
        })
    }


(err, result) => {
          test.assert(result.body.error.type === `ValidationError`)
          test.value(result).hasHeader('content-type', APP_JSON)
          done(err)
        }


done => {
      const geography = {
        name: 'foo',
        geography_id: GEOGRAPHY_UUID,
        publish_date: 1589817834000,
        geography_json: LA_CITY_BOUNDARY
      }
      request
        .post(pathPrefix(`/geographies`))
        .set('Authorization', GEOGRAPHIES_WRITE_SCOPE)
        .send(geography)
        .expect(400)
        .end((err, result) => {
          test.assert(result.body.error.type === `ValidationError`)
          test.value(result).hasHeader('content-type', APP_JSON)
          done(err)
        })
    }


done => {
      request
        .get(pathPrefix(`/foobar`))
        .set('Authorization', GEOGRAPHIES_WRITE_SCOPE)
        .expect(404)
        .end(err => {
          done(err)
        })
    }


response => {

                    tempresponse = response;
                    this.directories = tempresponse;
                }


response => {
                    console.log("Failure " + response);
                }


export class DocumentLibrary {
    name: string;
    title: string;
    selected: boolean;
    path: string;
    expanded: boolean;
    directories: Array<Directory>;
    relpath: string;
    dataService: DataService;
    parent: SiteCollection;
    static targetTitle: string;
    static targetName : string;
    static srcListUrl: string;
    listUrl:string;
    visible:boolean;

    constructor(name, title,path, parent) {
        this.name = name;
        this.title = title;
        this.selected = false;
        this.parent = parent;
     //   this.relpath = path;
        this.relpath = name;
       // this.cutPath(path);
        this.expanded = false;
        this.dataService = new DataService();
        this.directories = [];
        this.visible=true;
        this.listUrl="";
      //  this.directories = [new Directory("thisname",[new Directory("thisbla",[new Directory("thisbla")])])];

    }

   /* cutPath(path) {
        this.relpath = path.match("(?=" + this.parent.path + ").*?(?=/Form)").toString();
        this.relpath = this.relpath.substring(this.relpath.lastIndexOf('/') + 1);

    }*/

    getStyle() {
        if (this.selected) {
            return "rgba(156, 206, 240, 0.5)";
        } else {
            return "white";
        }
    }

    toggle() {
        this.expanded = !this.expanded;
        var tempresponse;
        if (this.expanded) {
            this.dataService.searchDirectories(this.parent.path,this.relpath,this).then(
                response => {

                    tempresponse = response;
                    this.directories = tempresponse;
                }, response => {
                    console.log("Failure " + response);
                });
        }
    }

    select(input=null) {
        if (input == "--1") {
            Directory.selectedPath = "";
        }
        this.parent.unsetAll();
        this.selected = true;
        DocumentLibrary.targetTitle = this.title;
        DocumentLibrary.targetName = this.name;
        DocumentLibrary.srcListUrl = this.listUrl;

    }

    unsetAll() {
        this.parent.unsetAll();
    }
}


/* cutPath(path) {
        this.relpath = path.match("(?=" + this.parent.path + ").*?(?=/Form)").toString();
        this.relpath = this.relpath.substring(this.relpath.lastIndexOf('/') + 1);

    }*/
getStyle() {
        if (this.selected) {
            return "rgba(156, 206, 240, 0.5)";
        } else {
            return "white";
        }
    }


toggle() {
        this.expanded = !this.expanded;
        var tempresponse;
        if (this.expanded) {
            this.dataService.searchDirectories(this.parent.path,this.relpath,this).then(
                response => {

                    tempresponse = response;
                    this.directories = tempresponse;
                }, response => {
                    console.log("Failure " + response);
                });
        }
    }


select(input=null) {
        if (input == "--1") {
            Directory.selectedPath = "";
        }
        this.parent.unsetAll();
        this.selected = true;
        DocumentLibrary.targetTitle = this.title;
        DocumentLibrary.targetName = this.name;
        DocumentLibrary.srcListUrl = this.listUrl;

    }


unsetAll() {
        this.parent.unsetAll();
    }


@Module({
  imports: [
    UsersModule,
    PassportModule,
    JwtModule.register({
      secret: jwtConstants.secret,
      signOptions: {
        expiresIn: jwtConstants.expirationTime,
      },
    }),
  ],
  controllers: [AuthController],
  providers: [AuthService, LocalStrategy, JwtStrategy],
})
export class AuthModule {}


// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type NetworkEventHandler = (socket: WebSocket, payload: any, player: Player) => void


async (t: tape.Test) => {
  const project = prepareEmpty(t)

  await install({
    dependencies: {
      'is-positive': '1.0.0',
    },
  }, await testDefaults({ modulesDir: 'pnpm_modules' }))

  await project.has('is-positive', 'pnpm_modules')

  await rimraf('pnpm_modules')
  await project.hasNot('is-positive', 'pnpm_modules')

  await install({
    dependencies: {
      'is-positive': '1.0.0',
    },
  }, await testDefaults({ frozenLockfile: true, modulesDir: 'pnpm_modules' }))

  await project.has('is-positive', 'pnpm_modules')
}


async (t) => {
  const projects = preparePackages(t, [
    {
      location: 'project-1',
      package: {
        name: 'project-1',

        dependencies: { 'is-positive': '1.0.0' },
      },
    },
    {
      location: 'project-2',
      package: {
        name: 'project-2',

        dependencies: { 'is-positive': '1.0.0' },
      },
    },
  ])

  const importers: MutatedProject[] = [
    {
      buildIndex: 0,
      manifest: {
        name: 'project-1',
        version: '1.0.0',

        dependencies: {
          'is-positive': '1.0.0',
        },
      },
      modulesDir: 'modules_1',
      mutation: 'install',
      rootDir: path.resolve('project-1'),
    },
    {
      buildIndex: 0,
      manifest: {
        name: 'project-2',
        version: '1.0.0',

        dependencies: {
          'is-positive': '1.0.0',
        },
      },
      modulesDir: 'modules_2',
      mutation: 'install',
      rootDir: path.resolve('project-2'),
    },
  ]
  await mutateModules(importers, await testDefaults())

  await projects['project-1'].has('is-positive', 'modules_1')
  await projects['project-2'].has('is-positive', 'modules_2')
}


user => {
                return !searchName || user.name.toLowerCase().indexOf(searchName) !== -1;
            }


user => {
                return !searchAge || user.age == searchAge;
            }


users => {
                this.users = users;
                this.filteredUsers = this.users;
            }


err => {
                console.log(err);
            }


@Component({
    selector: 'user-list-component',
    templateUrl: 'user-list.component.html',
    providers: []
})

export class UserListComponent implements OnInit {
    //These are public so that tests can reference them (.spec.ts)
    userName: string;
    userAge: number;
    public users: User[];
    public filteredUsers: User[];

    //Inject the UserListService into this component.
    //That's what happens in the following constructor.
    //
    //We can call upon the service for interacting
    //with the server.
    constructor(private userListService: UserListService) {

    }

    public filterUsers(searchName: string, searchAge: number): User[] {

        this.filteredUsers = this.users;

        //Filter by name
        if (searchName != null) {
            searchName = searchName.toLocaleLowerCase();

            this.filteredUsers = this.filteredUsers.filter(user => {
                return !searchName || user.name.toLowerCase().indexOf(searchName) !== -1;
            });
        }

        //Filter by age
        if (searchAge != null) {
            this.filteredUsers = this.filteredUsers.filter(user => {
                return !searchAge || user.age == searchAge;
            });
        }

        return this.filteredUsers;
    }

    ngOnInit(): void {
        //Get Users returns an Observable, basically a "promise" that
        //we will get the data from the server.
        //
        //Subscribe waits until the data is fully downloaded, then
        //performs an action on it (the first lambda)
        this.userListService.getUsers().subscribe(
            users => {
                this.users = users;
                this.filteredUsers = this.users;
            },
            err => {
                console.log(err);
            }
        );
    }
}


public filterUsers(searchName: string, searchAge: number): User[] {

        this.filteredUsers = this.users;

        //Filter by name
        if (searchName != null) {
            searchName = searchName.toLocaleLowerCase();

            this.filteredUsers = this.filteredUsers.filter(user => {
                return !searchName || user.name.toLowerCase().indexOf(searchName) !== -1;
            });
        }

        //Filter by age
        if (searchAge != null) {
            this.filteredUsers = this.filteredUsers.filter(user => {
                return !searchAge || user.age == searchAge;
            });
        }

        return this.filteredUsers;
    }


ngOnInit(): void {
        //Get Users returns an Observable, basically a "promise" that
        //we will get the data from the server.
        //
        //Subscribe waits until the data is fully downloaded, then
        //performs an action on it (the first lambda)
        this.userListService.getUsers().subscribe(
            users => {
                this.users = users;
                this.filteredUsers = this.users;
            },
            err => {
                console.log(err);
            }
        );
    }


function compileList(
  schema: Schema,
  name: "implicit" | "explicit",
  result: Type[],
): Type[] {
  const exclude: number[] = [];

  for (const includedSchema of schema.include) {
    result = compileList(includedSchema, name, result);
  }

  for (const currentType of schema[name]) {
    for (
      let previousIndex = 0;
      previousIndex < result.length;
      previousIndex++
    ) {
      const previousType = result[previousIndex];
      if (
        previousType.tag === currentType.tag &&
        previousType.kind === currentType.kind
      ) {
        exclude.push(previousIndex);
      }
    }

    result.push(currentType);
  }

  return result.filter((_type, index): unknown => !exclude.includes(index));
}


function compileMap(...typesList: Type[][]): TypeMap {
  const result: TypeMap = {
    fallback: {},
    mapping: {},
    scalar: {},
    sequence: {},
  };

  for (const types of typesList) {
    for (const type of types) {
      if (type.kind !== null) {
        result[type.kind][type.tag] = result["fallback"][type.tag] = type;
      }
    }
  }
  return result;
}


(_type, index): unknown => !exclude.includes(index)


export class Schema implements SchemaDefinition {
  public static SCHEMA_DEFAULT?: Schema;

  public implicit: Type[];
  public explicit: Type[];
  public include: Schema[];

  public compiledImplicit: Type[];
  public compiledExplicit: Type[];
  public compiledTypeMap: TypeMap;

  constructor(definition: SchemaDefinition) {
    this.explicit = definition.explicit || [];
    this.implicit = definition.implicit || [];
    this.include = definition.include || [];

    for (const type of this.implicit) {
      if (type.loadKind && type.loadKind !== "scalar") {
        throw new YAMLError(
          "There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.",
        );
      }
    }

    this.compiledImplicit = compileList(this, "implicit", []);
    this.compiledExplicit = compileList(this, "explicit", []);
    this.compiledTypeMap = compileMap(
      this.compiledImplicit,
      this.compiledExplicit,
    );
  }

  /* Returns a new extended schema from current schema */
  public extend(definition: SchemaDefinition) {
    return new Schema({
      implicit: [
        ...new Set([...this.implicit, ...(definition?.implicit ?? [])]),
      ],
      explicit: [
        ...new Set([...this.explicit, ...(definition?.explicit ?? [])]),
      ],
      include: [...new Set([...this.include, ...(definition?.include ?? [])])],
    });
  }

  public static create(): void {}
}


export interface SchemaDefinition {
  implicit?: Any[];
  explicit?: Type[];
  include?: Schema[];
}


export type TypeMap = { [k in KindType | "fallback"]: ArrayObject<Type> };


/* Returns a new extended schema from current schema */
public extend(definition: SchemaDefinition) {
    return new Schema({
      implicit: [
        ...new Set([...this.implicit, ...(definition?.implicit ?? [])]),
      ],
      explicit: [
        ...new Set([...this.explicit, ...(definition?.explicit ?? [])]),
      ],
      include: [...new Set([...this.include, ...(definition?.include ?? [])])],
    });
  }


public static create(): void {}


(a: number) => (b: number) => Math.abs(a - b)


(b: number) => Math.abs(a - b)


(d: number) => (n: number) => n > d


(n: number) => n > d


(arr2: number[], d: number) =>
  (count: number, n: number) =>
    arr2.map(toD(n)).every(gt(d)) ? count + 1 : count


(count: number, n: number) =>
    arr2.map(toD(n)).every(gt(d)) ? count + 1 : count


(
  arr1: number[],
  arr2: number[],
  d: number
): number => arr1.reduce(toCount(arr2, d), 0)


export function startup(configuration: IssueReporterConfiguration) {
	document.body.innerHTML = BaseHtml();
	const issueReporter = new IssueReporter(configuration);
	issueReporter.render();
	document.body.style.display = 'block';
}


// helper functions
function hide(el) {
	el.classList.add('hidden');
}


function show(el) {
	el.classList.remove('hidden');
}


(event, info) => {
			this.logService.trace('issueReporter: Received performance data');
			this.issueReporterModel.update(info);
			this.receivedPerformanceInfo = true;

			const state = this.issueReporterModel.getData();
			this.updateProcessInfo(state);
			this.updateWorkspaceInfo(state);
			this.updatePreviewButtonState();
		}


(event, info) => {
			this.logService.trace('issueReporter: Received system data');
			this.issueReporterModel.update({ systemInfo: info });
			this.receivedSystemInfo = true;

			this.updateSystemInfo(this.issueReporterModel.getData());
			this.updatePreviewButtonState();
		}


ext => {
			const manifestKeys = ext.manifest.contributes ? Object.keys(ext.manifest.contributes) : [];
			const onlyTheme = !ext.manifest.activationEvents && manifestKeys.length === 1 && manifestKeys[0] === 'themes';
			return onlyTheme ? 'themes' : 'nonThemes';
		}


setting => {
				table += `

						${setting.key}
						${setting.extensionId}
						${String(setting.score).slice(0, 5)}

`;
			}


() => connectNet(this.environmentService.sharedIPCHandle, `window:${configuration.windowId}`)


c => c.getChannel('telemetryAppender')


(event: Event) => {
			const issueType = parseInt((<HTMLInputElement>event.target).value);
			this.issueReporterModel.update({ issueType: issueType });
			if (issueType === IssueType.PerformanceIssue && !this.receivedPerformanceInfo) {
				ipcRenderer.send('vscode:issuePerformanceInfoRequest');
			}
			this.updatePreviewButtonState();
			this.render();
		}


elementId => {
			this.addEventListener(elementId, 'click', (event: Event) => {
				event.stopPropagation();
				this.issueReporterModel.update({ [elementId]: !this.issueReporterModel.getData()[elementId] });
			});
		}


(event: Event) => {
				event.stopPropagation();
				this.issueReporterModel.update({ [elementId]: !this.issueReporterModel.getData()[elementId] });
			}


(e) => {
				e.preventDefault();
				const label = (<HTMLDivElement>e.target);
				const containingElement = label.parentElement.parentElement;
				const info = containingElement.lastElementChild;
				if (info.classList.contains('hidden')) {
					show(info);
					label.textContent = localize('hide', "hide");
				} else {
					hide(info);
					label.textContent = localize('show', "show");
				}
			}


(event: Event) => {
			const fileOnExtension = JSON.parse((<HTMLInputElement>event.target).value);
			this.issueReporterModel.update({ fileOnExtension: fileOnExtension, includeExtensions: !fileOnExtension });
			this.render();

			const title = (<HTMLInputElement>document.getElementById('issue-title')).value;
			if (fileOnExtension) {
				this.searchExtensionIssues(title);
			} else {
				const description = this.issueReporterModel.getData().issueDescription;
				this.searchVSCodeIssues(title, description);
			}
		}


(event: Event) => {
			const issueDescription = (<HTMLInputElement>event.target).value;
			this.issueReporterModel.update({ issueDescription });

			// Only search for extension issues on title change
			if (!this.issueReporterModel.fileOnExtension()) {
				const title = (<HTMLInputElement>document.getElementById('issue-title')).value;
				this.searchVSCodeIssues(title, issueDescription);
			}
		}


(e) => {
			const title = (<HTMLInputElement>event.target).value;
			const lengthValidationMessage = document.getElementById('issue-title-length-validation-error');
			if (title && this.getIssueUrlWithTitle(title).length > MAX_URL_LENGTH) {
				show(lengthValidationMessage);
			} else {
				hide(lengthValidationMessage);
			}

			if (this.issueReporterModel.fileOnExtension()) {
				this.searchExtensionIssues(title);
			} else {
				const description = this.issueReporterModel.getData().issueDescription;
				this.searchVSCodeIssues(title, description);
			}
		}


() => this.createIssue()


() => {
			ipcRenderer.send('vscode:workbenchCommand', 'workbench.action.reloadWindowWithExtensionsDisabled');
		}


(e: KeyboardEvent) => {
			e.stopPropagation();
			if (e.keyCode === 13 || e.keyCode === 32) {
				ipcRenderer.send('vscode:workbenchCommand', 'workbench.extensions.action.disableAll');
				ipcRenderer.send('vscode:workbenchCommand', 'workbench.action.reloadWindow');
			}
		}


(e: KeyboardEvent) => {
			const cmdOrCtrlKey = platform.isMacintosh ? e.metaKey : e.ctrlKey;
			// Cmd/Ctrl+Enter previews issue and closes window
			if (cmdOrCtrlKey && e.keyCode === 13) {
				if (this.createIssue()) {
					ipcRenderer.send('vscode:closeIssueReporter');
				}
			}

			// Cmd/Ctrl + zooms in
			if (cmdOrCtrlKey && e.keyCode === 187) {
				this.applyZoom(webFrame.getZoomLevel() + 1);
			}

			// Cmd/Ctrl - zooms out
			if (cmdOrCtrlKey && e.keyCode === 189) {
				this.applyZoom(webFrame.getZoomLevel() - 1);
			}

			// With latest electron upgrade, cmd+a is no longer propagating correctly for inputs in this window on mac
			// Manually perform the selection
			if (platform.isMacintosh) {
				if (cmdOrCtrlKey && e.keyCode === 65 && e.target) {
					if (e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement) {
						(<HTMLInputElement>e.target).select();
					}
				}
			}
		}