text:
import React from 'react';
import './OpenESOP.scss';
import {web3} from '../web3'

import TextField from 'material-ui/TextField';
import RaisedButton from 'material-ui/RaisedButton';
import FontIcon from 'material-ui/FontIcon';
import IconButton from 'material-ui/IconButton';
import FlatButton from 'material-ui/FlatButton'

import {validateDoc}from '../utils'
import IPFSDialog from '../components/IPFSDialog';
import Texting from '../texting'
import ContractUtils from '../ContractUtils'

export default class Init extends React.Component {

    constructor(props) {
        super(props);
        this.store = props.store;
        this.services = props.services;

        this.state = {
            allowValidation: false,
            totalPoolOptions: '',
            totalPoolOptionsValidation: '',
            cliffPeriod: '',
            cliffPeriodValidation: '',
            vestingPeriod: '',
            vestingPeriodValidation: '',
            residualAmount: '',
            residualAmountValidation: '',
            bonusOptions: '',
            bonusOptionsValidation: '',
            newEmployeePool: '',
            newEmployeePoolValidation: '',
            optionsPerShare: '',
            optionsPerShareValidation: '',
            ESOPLegalWrapperIPFSHash: '',
            ESOPLegalWrapperIPFSHashValidation: '',
            LegalDocument :'',
            showDocumentDialog:false
        };
    }

    validateTotalPoolOptions = (value) => {
        let validationOutcome = value === '' ? "please fill this field" : "";

        if (validationOutcome == "") {
            let num = parseInt(value);
            if (isNaN(num))
                validationOutcome = 'value is not a number';
            else if (num < 10000)
                validationOutcome = 'value must be > 10000';
            // else if (num > 1100000)
            //    validationOutcome = 'value must be less than 100';
        }
        this.setState({totalPoolOptionsValidation: validationOutcome});
        return validationOutcome;
    };

    validateCliffPeriod = (value) => {
        let validationOutcome = value === '' ? "please fill this field" : "";

        if (validationOutcome == "") {
            let num = Number.parseInt(value);
            if (isNaN(num))
                validationOutcome = 'value is not a number';
            else if (num <= 0)
                validationOutcome = 'time period must be bigger than zero';
        }
        this.setState({cliffPeriodValidation: validationOutcome});
        return validationOutcome;
    };

    validateVestingPeriod = (value) => {
        let validationOutcome = value === '' ? "please fill this field" : "";

        if (validationOutcome == "") {
            let num = Number.parseInt(value);
            if (isNaN(num))
                validationOutcome = 'value is not a number';
            else if (num <= 0)
                validationOutcome = 'time period must be bigger than zero';
        }
        this.setState({vestingPeriodValidation: validationOutcome});
        return validationOutcome;
    };

    validateResidualAmount = (value) => {
        let validationOutcome = value === '' ? "please fill this field" : "";

        if (validationOutcome == "") {
            let num = parseInt(value);
            if (isNaN(num))
                validationOutcome = 'value is not a number';
            else if (num <= 0)
                validationOutcome = 'value must be bigger than zero';
            else if (num > 100)
                validationOutcome = 'value must be less than 100';
        }
        this.setState({residualAmountValidation: validationOutcome});
        return validationOutcome;
    };

    validateBonusOptions = (value) => {
        let validationOutcome = value === '' ? "please fill this field" : "";

        if (validationOutcome == "") {
            let num = parseInt(value);
            if (isNaN(num))
                validationOutcome = 'value is not a number';
            else if (num <= 0)
                validationOutcome = 'value must be bigger than zero';
            else if (num > 100)
                validationOutcome = 'value must be less than 100';
        }
        this.setState({bonusOptionsValidation: validationOutcome});
        return validationOutcome;
    };

    validateNewEmployeePool = (value) => {
        let validationOutcome = value === '' ? "please fill this field" : "";

        if (validationOutcome == "") {
            let num = parseInt(value);
            if (isNaN(num))
                validationOutcome = 'value is not a number';
            else if (num <= 0)
                validationOutcome = 'value must be bigger than zero';
            else if (num > 100)
                validationOutcome = 'value must be less than 100';
        }
        this.setState({newEmployeePoolValidation: validationOutcome});
        return validationOutcome;
    };

    validateOptionsPerShare = (value) => {
        let validationOutcome = value === '' ? "please fill this field" : "";

        if (validationOutcome == "") {
            let num = parseInt(value);
            if (isNaN(num))
                validationOutcome = 'value is not a number';
            else if (num <= 0)
                validationOutcome = 'value must be bigger than zero';
            else if (this.state.totalPoolOptions % value > 0)
                validationOutcome = 'should be a divisor of total pool options';
        }
        this.setState({optionsPerShareValidation: validationOutcome});
        return validationOutcome;
    };

    validatESOPLegalWrapperIPFSHash = (value) => {
        let validationOutcome = value === "" ? "please fill this field" : "";
        this.setState({ESOPLegalWrapperIPFSHashValidation: validationOutcome});
        return validationOutcome;
    };

    handleTextFieldChange = (fieldName, validateFunction) =>
        (event, newValue) => {
            let obj = {};
            obj[fieldName] = newValue;
            this.setState(obj);
            if (this.state.allowValidation) {
                validateFunction(newValue);
            }
        };

    validateFields = () => {
        let validateTotalPoolOptions = this.validateTotalPoolOptions(this.state.totalPoolOptions) == '';
        let validateCliffPeriod = this.validateCliffPeriod(this.state.cliffPeriod) == '';
        let validateVestingPeriod = this.validateVestingPeriod(this.state.vestingPeriod) == '';
        let validateResidualAmount = this.validateResidualAmount(this.state.residualAmount) == '';
        let validateBonusOptions = this.validateBonusOptions(this.state.bonusOptions) == '';
        let validateNewEmployeePool = this.validateNewEmployeePool(this.state.newEmployeePool) == '';
        let validateOptionsPerShare = this.validateOptionsPerShare(this.state.optionsPerShare) == '';
        let validatESOPLegalWrapperIPFSHash = this.validatESOPLegalWrapperIPFSHash(this.state.ESOPLegalWrapperIPFSHash) == '';

        return validateTotalPoolOptions && validateCliffPeriod && validateVestingPeriod
            && validateResidualAmount && validateBonusOptions && validateNewEmployeePool && validateOptionsPerShare
            && validatESOPLegalWrapperIPFSHash;
    };

    handleValidateDoc = () =>{
        const ESOPLegalWrapperIPFSHash = this.state.ESOPLegalWrapperIPFSHash; //QmXq9u2GPyCv8q9XCMPYtSMBe1WVAjoZidnhjX6P1SbiRt

        validateDoc(ESOPLegalWrapperIPFSHash , (data)=>{
            this.setState({
                LegalDocument:data,
                showDocumentDialog:true
            });
        });
    };

    handleDialogRequestClose=()=>{
        this.setState({
            showDocumentDialog: false,
        });
    };

    handlePrint = () =>{
        let mywindow = window.open('', 'PRINT', 'height=400,width=600');

        mywindow.document.write('<title>' + document.title  + '</title>');
        mywindow.document.write('');
        mywindow.document.write(document.getElementById("ifmcontentstoprint").innerHTML);
        mywindow.document.write('');

        mywindow.document.close(); // necessary for IE >= 10
        mywindow.focus(); // necessary for IE >= 10*/

        mywindow.print();
        mywindow.close();
    };

    handleOpenEsopButton = () => {

        this.setState({allowValidation: true});
        if (!this.validateFields()) {
            return;
        }
        let year = 365 * 24 * 60 * 60;

        let totalPoolOptions = parseInt(this.state.totalPoolOptions);
        let ESOPLegalWrapperIPFSHash = web3.toBigNumber('0x' + new Buffer(this.state.ESOPLegalWrapperIPFSHash, 'ascii').toString('hex'));
        let cliffPeriod = Number.parseInt(this.state.cliffPeriod) * year;
        let vestingPeriod = Number.parseInt(this.state.vestingPeriod) * year;
        let residualAmount = parseInt(this.state.residualAmount) * 100;
        let bonusOptions = parseInt(this.state.bonusOptions) * 100;
        let newEmployeePool = parseInt(this.state.newEmployeePool) * 100;
        let optionsPerShare = parseInt(this.state.optionsPerShare);

        this.store.dispatch({
            type: "SHOW_CONFIRM_TRANSACTION_DIALOG",
            confirmTransactionDialog: true
        });

        let handle_error = function (that, error) {
            that.store.dispatch({
                type: "SHOW_CONFIRM_TRANSACTION_DIALOG",
                confirmTransactionDialog: false
            });

            that.store.dispatch({
                type: "SET_ERROR_DIALOG_MSG",
                errorDialogMsg: error.toString()
            });

            that.store.dispatch({
                type: "SHOW_ERROR_DIALOG",
                errorDialog: true
            });
            console.log(error);
        };

        let ESOPState = this.store.getState().ESOP;
        let hasSetParameters = ESOPState.optionsPerShare > 0;

        this.services.ESOPService.setParametersOptional(cliffPeriod, vestingPeriod,
            residualAmount, bonusOptions, newEmployeePool, optionsPerShare, hasSetParameters).then(
            success => this.services.ESOPService.openESOP(totalPoolOptions, ESOPLegalWrapperIPFSHash).then(
                success => {
                    this.services.ESOPService.getESOPDataFromContract();
                    this.services.ESOPService.obtainContractAddresses();
                    this.store.dispatch({
                        type: "SHOW_CONFIRM_TRANSACTION_DIALOG",
                        confirmTransactionDialog: false
                    });
                },
                error => handle_error(this, error)
            ),
            error => handle_error(this, error)
        );
    };

    render() {
        let tooltipStyles = {
            fontSize: "0.8rem",
            padding: "0.4rem"
        };

        let ESOPState = this.store.getState().ESOP;
        let UIstate = this.store.getState().UI;
        let userState = this.store.getState().user;

        let textFieldsProps = {};

        textFieldsProps.totalPoolOptionsProps = {
            floatingLabelText: "total pool options",
            className: "contract_parameter",
            value: this.state.totalPoolOptions,
            onChange: this.handleTextFieldChange("totalPoolOptions", this.validateTotalPoolOptions)
        };

        textFieldsProps.cliffPeriodProps = {
            floatingLabelText: "cliff period [years]",
            className: "contract_parameter",
            value: this.state.cliffPeriod,
            onChange: this.handleTextFieldChange("cliffPeriod", this.validateCliffPeriod)
        };

        textFieldsProps.vestingPeriodProps = {
            floatingLabelText: "vesting period [years]",
            className: "contract_parameter",
            value: this.state.vestingPeriod,
            onChange: this.handleTextFieldChange("vestingPeriod", this.validateVestingPeriod)
        };

        textFieldsProps.residualAmountProps = {
            floatingLabelText: "residual amount [%]",
            className: "contract_parameter",
            value: this.state.residualAmount,
            onChange: this.handleTextFieldChange("residualAmount", this.validateResidualAmount)
        };

        textFieldsProps.bonusOptionsProps = {
            floatingLabelText: "bonus options[%]",
            className: "contract_parameter",
            value: this.state.bonusOptions,
            onChange: this.handleTextFieldChange("bonusOptions", this.validateBonusOptions)
        };

        textFieldsProps.newEmployeePoolProps = {
            floatingLabelText: "new employee % of pool [%]",
            className: "contract_parameter",
            value: this.state.newEmployeePool,
            onChange: this.handleTextFieldChange("newEmployeePool", this.validateNewEmployeePool)
        };

        textFieldsProps.optionsPerShareProps = {
            floatingLabelText: "options per share",
            className: "contract_parameter",
            value: this.state.optionsPerShare,
            onChange: this.handleTextFieldChange("optionsPerShare", this.validateOptionsPerShare)
        };

        textFieldsProps.ESOPLegalWrapperIPFSHashProps = {
            floatingLabelText: "ESOP Terms & Conditions Document IPFS Hash",
            style: {width: "32.000rem"},
            value: this.state.ESOPLegalWrapperIPFSHash,
            onChange: this.handleTextFieldChange("ESOPLegalWrapperIPFSHash", this.validatESOPLegalWrapperIPFSHash)
        };

        if (this.state.allowValidation) {
            textFieldsProps.totalPoolOptionsProps.errorText = this.state.totalPoolOptionsValidation;
            textFieldsProps.cliffPeriodProps.errorText = this.state.cliffPeriodValidation;
            textFieldsProps.vestingPeriodProps.errorText = this.state.vestingPeriodValidation;
            textFieldsProps.residualAmountProps.errorText = this.state.residualAmountValidation;
            textFieldsProps.bonusOptionsProps.errorText = this.state.bonusOptionsValidation;
            textFieldsProps.newEmployeePoolProps.errorText = this.state.newEmployeePoolValidation;
            textFieldsProps.optionsPerShareProps.errorText = this.state.optionsPerShareValidation;
            textFieldsProps.ESOPLegalWrapperIPFSHashProps.errorText = this.state.ESOPLegalWrapperIPFSHashValidation;
        }

        console.log("OpenESOP", this.state)

        return (

                <IPFSDialog
                    IPFSDialog={this.state.ESOPLegalWrapperIPFSHash}
                    showDocumentDialog={this.state.showDocumentDialog}
                    handleDialogRequestClose ={this.handleDialogRequestClose}
                    handlePrint ={this.handlePrint}
                    documentHtml={this.state.LegalDocument}
                />

ESOP terms and conditions not set

ESOP contract addresses:

                            <FontIcon className="material-icons">link</FontIcon>

                        <TextField floatingLabelText="Root of Trust" value={ESOPState.RoTAddress}
                                   style={{width: "32.000rem"}} disabled={true}/>

                            <FontIcon className="material-icons">link</FontIcon>

                        <TextField floatingLabelText="ESOP smart contract" value={ESOPState.ESOPAddress}
                                   style={{width: "32.000rem"}} disabled={true}/>

                {userState.userType != "ceo" ?

To set the terms & conditions of ESOP please connect company manages's account {ESOPState.companyAddress} configured during deployment process

                    :

Please fill ESOP parameters before employees can be added

                                <TextField {...textFieldsProps.totalPoolOptionsProps}/>
                                <IconButton tooltip={Texting.definitions.totalPoolOptions} iconClassName="material-icons" tooltipStyles={tooltipStyles}>info_outline</IconButton>

                                <TextField {...textFieldsProps.cliffPeriodProps}/>
                                <IconButton tooltip={Texting.definitions.cliffPeriod} iconClassName="material-icons" tooltipStyles={tooltipStyles}>info_outline</IconButton>

                                    <TextField {...textFieldsProps.vestingPeriodProps}/>
                                    <IconButton tooltip={Texting.definitions.vestingPeriod} iconClassName="material-icons" tooltipStyles={tooltipStyles}>info_outline</IconButton>

                                    <TextField {...textFieldsProps.residualAmountProps}/>
                                    <IconButton tooltip={Texting.definitions.residualAmount} iconClassName="material-icons" tooltipStyles={tooltipStyles}>info_outline</IconButton>

                                    <TextField {...textFieldsProps.bonusOptionsProps}/>
                                    <IconButton tooltip={Texting.definitions.bonusOptions} iconClassName="material-icons" tooltipStyles={tooltipStyles}>info_outline</IconButton>

                                    <TextField {...textFieldsProps.newEmployeePoolProps}/>
                                    <IconButton tooltip={Texting.definitions.newEmployeePool} iconClassName="material-icons" tooltipStyles={tooltipStyles}>info_outline</IconButton>

                                <TextField {...textFieldsProps.optionsPerShareProps}/>
                                <IconButton tooltip={Texting.definitions.optionsPerShare} iconClassName="material-icons" tooltipStyles={tooltipStyles}>info_outline</IconButton>

                                <TextField {...textFieldsProps.ESOPLegalWrapperIPFSHashProps}/>
                                <IconButton tooltip={Texting.definitions.termsDocIPFSHash} iconClassName="material-icons" tooltipStyles={tooltipStyles}>info_outline</IconButton>
                                <RaisedButton label="preview document" className="preview_button"
                                              onTouchTap={this.handleValidateDoc} />

                                Read more on configuring ESOP Terms & Conditions

                                <RaisedButton label="Initialize ESOP" onClick={this.handleOpenEsopButton}
                                              className="start_button"/>

                }

        )
    }
};


text:
import React, { useState, useRef } from 'react';
import { Formik } from 'formik';
import { useIntl } from 'react-intl';
import { useRouteMatch } from 'react-router-dom';
import {
  useOverlayBlocker,
  SettingsPageTitle,
  LoadingIndicatorPage,
  Form,
  useNotification,
  Link,
} from '@strapi/helper-plugin';
import { ContentLayout, HeaderLayout } from '@strapi/design-system/Layout';
import { Main } from '@strapi/design-system/Main';
import { Button } from '@strapi/design-system/Button';
import { Stack } from '@strapi/design-system/Stack';
import { Box } from '@strapi/design-system/Box';
import { TextInput } from '@strapi/design-system/TextInput';
import { Textarea } from '@strapi/design-system/Textarea';
import { Typography } from '@strapi/design-system/Typography';
import ArrowLeft from '@strapi/icons/ArrowLeft';
import Check from '@strapi/icons/Check';
import { GridItem, Grid } from '@strapi/design-system/Grid';
import UsersPermissions from '../../../components/UsersPermissions';
import getTrad from '../../../utils/getTrad';
import pluginId from '../../../pluginId';
import { usePlugins, useFetchRole } from '../../../hooks';
import schema from './utils/schema';
import axiosInstance from '../../../utils/axiosInstance';

const EditPage = () => {
  const { formatMessage } = useIntl();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const toggleNotification = useNotification();
  const { lockApp, unlockApp } = useOverlayBlocker();
  const {
    params: { id },
  } = useRouteMatch(`/settings/${pluginId}/roles/:id`);
  const { isLoading: isLoadingPlugins, routes } = usePlugins();
  const { role, onSubmitSucceeded, isLoading: isLoadingRole } = useFetchRole(id);
  const permissionsRef = useRef();

  const handleEditRoleSubmit = async data => {
    // Set loading state
    lockApp();
    setIsSubmitting(true);
    try {
      const permissions = permissionsRef.current.getPermissions();
      // Update role in Strapi
      await axiosInstance.put(`/${pluginId}/roles/${id}`, { ...data, ...permissions, users: [] });
      // Notify success
      onSubmitSucceeded({ name: data.name, description: data.description });
      toggleNotification({
        type: 'success',
        message: {
          id: getTrad('Settings.roles.edited'),
          defaultMessage: 'Role edited',
        },
      });
    } catch (err) {
      console.error(err);
      toggleNotification({
        type: 'warning',
        message: {
          id: 'notification.error',
          defaultMessage: 'An error occurred',
        },
      });
    }
    // Unset loading state
    setIsSubmitting(false);
    unlockApp();
  };

  if (isLoadingRole) {
    return <LoadingIndicatorPage />;
  }

  return (
    <Main>
      <SettingsPageTitle name="Roles" />
      <Formik
        enableReinitialize
        initialValues={{ name: role.name, description: role.description }}
        onSubmit={handleEditRoleSubmit}
        validationSchema={schema}
      >
        {({ handleSubmit, values, handleChange, errors }) => (
          <Form noValidate onSubmit={handleSubmit}>
            <HeaderLayout
              primaryAction={
                !isLoadingPlugins && (
                  <Button
                    disabled={role.code === 'strapi-super-admin'}
                    type="submit"
                    loading={isSubmitting}
                    startIcon={<Check />}
                  >
                    {formatMessage({
                      id: 'global.save',
                      defaultMessage: 'Save',
                    })}
                  </Button>
                )
              }
              title={role.name}
              subtitle={role.description}
              navigationAction={
                <Link startIcon={<ArrowLeft />} to="/settings/users-permissions/roles">
                  {formatMessage({
                    id: 'global.back',
                    defaultMessage: 'Back',
                  })}
                </Link>
              }
            />
            <ContentLayout>
              <Stack spacing={7}>
                <Box
                  background="neutral0"
                  hasRadius
                  shadow="filterShadow"
                  paddingTop={6}
                  paddingBottom={6}
                  paddingLeft={7}
                  paddingRight={7}
                >
                  <Stack spacing={4}>
                    <Typography variant="delta" as="h2">
                      {formatMessage({
                        id: getTrad('EditPage.form.roles'),
                        defaultMessage: 'Role details',
                      })}
                    </Typography>
                    <Grid gap={4}>
                      <GridItem col={6}>
                        <TextInput
                          name="name"
                          value={values.name || ''}
                          onChange={handleChange}
                          label={formatMessage({
                            id: 'global.name',
                            defaultMessage: 'Name',
                          })}
                          error={
                            errors.name
                              ? formatMessage({ id: errors.name, defaultMessage: 'Invalid value' })
                              : null
                          }
                        />
                      </GridItem>
                      <GridItem col={6}>
                        <Textarea
                          name="description"
                          value={values.description || ''}
                          onChange={handleChange}
                          label={formatMessage({
                            id: 'global.description',
                            defaultMessage: 'Description',
                          })}
                          error={
                            errors.description
                              ? formatMessage({
                                  id: errors.description,
                                  defaultMessage: 'Invalid value',
                                })
                              : null
                          }
                        />
                      </GridItem>
                    </Grid>
                  </Stack>
                </Box>
                {!isLoadingPlugins && (
                  <UsersPermissions
                    ref={permissionsRef}
                    permissions={role.permissions}
                    routes={routes}
                  />
                )}
              </Stack>
            </ContentLayout>
          </Form>
        )}
      </Formik>
    </Main>
  );
};

export default EditPage;

redpajama_set_name: RedPajamaGithub


text:
var slackChannelController = require('./slackChannelController');

module.exports = function(router){
  router.post('/addNewOrganization', slackChannelController.addNewOrganization);
};


text:
export const isObject = (obj) => {
  return Object.prototype.toString.call(obj) === '[object Object]';
};


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.storage.blob.nio;

import com.azure.core.util.logging.ClientLogger;
import com.azure.storage.blob.specialized.BlobInputStream;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;

/**
 * Provides an InputStream to read a file stored as an Azure Blob.
 */
public final class NioBlobInputStream extends InputStream {
    private final ClientLogger logger = new ClientLogger(NioBlobInputStream.class);

    private final BlobInputStream blobInputStream;
    private final Path path;

    NioBlobInputStream(BlobInputStream blobInputStream, Path path) {
        this.blobInputStream = blobInputStream;
        this.path = path;
    }

    /**
     * Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without
     * blocking by the next invocation of a method for this input stream. The next invocation might be the same thread
     * or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes.
     *
     * @return An int which represents an estimate of the number of bytes that can be read (or skipped
     * over) from this input stream without blocking, or 0 when it reaches the end of the input stream.
     */
    @Override
    public synchronized int available() throws IOException {
        AzurePath.ensureFileSystemOpen(path);
        return this.blobInputStream.available();
    }

    /**
     * Closes this input stream and releases any system resources associated with the stream.
     */
    @Override
    public synchronized void close() throws IOException {
        AzurePath.ensureFileSystemOpen(path);
        this.blobInputStream.close();
    }

    /**
     * Marks the current position in this input stream. A subsequent call to the reset method repositions this stream at
     * the last marked position so that subsequent reads re-read the same bytes.
     *
     * @param readlimit An int which represents the maximum limit of bytes that can be read before the mark
     * position becomes invalid.
     */
    @Override
    public synchronized void mark(final int readlimit) {
        this.blobInputStream.mark(readlimit);
    }

    /**
     * Tests if this input stream supports the mark and reset methods.
     *
     * @return Returns {@code true}
     */
    @Override
    public boolean markSupported() {
        return this.blobInputStream.markSupported();
    }

    /**
     * Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If
     * no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks
     * until input data is available, the end of the stream is detected, or an exception is thrown.
     *
     * @return An int which represents the total number of bytes read into the buffer, or -1 if there is no
     * more data because the end of the stream has been reached.
     * @throws IOException If an I/O error occurs.
     */
    @Override
    public int read() throws IOException {
        AzurePath.ensureFileSystemOpen(path);
        try {
            return this.blobInputStream.read();
            /*
            BlobInputStream only throws RuntimeException, and it doesn't preserve the cause, it only takes the message,
            so we can't do any better than re-wrapping it in an IOException.
             */
        } catch (RuntimeException e) {
            throw LoggingUtility.logError(logger, new IOException(e));
        }
    }

    /**
     * Reads some number of bytes from the input stream and stores them into the buffer array b. The number
     * of bytes actually read is returned as an integer. This method blocks until input data is available, end of file
     * is detected, or an exception is thrown. If the length of b is zero, then no bytes are read and 0 is
     * returned; otherwise, there is an attempt to read at least one byte. If no byte is available because the stream is
     * at the end of the file, the value -1 is returned; otherwise, at least one byte is read and stored into
     * b.
     *
     * The first byte read is stored into element b[0], the next one into b[1], and so on. The
     * number of bytes read is, at most, equal to the length of b. Let k be the number of
     * bytes actually read; these bytes will be stored in elements b[0] through b[k-1],
     * leaving elements b[k] through
     * b[b.length-1] unaffected.
     *
     * The read(b) method for class {@link InputStream} has the same effect as:
     *
     * read(b, 0, b.length)
     *
     * @param b A byte array which represents the buffer into which the data is read.
     * @throws IOException If the first byte cannot be read for any reason other than the end of the file, if the input
     * stream has been closed, or if some other I/O error occurs.
     * @throws NullPointerException If the byte array b is null.
     */
    @Override
    public int read(final byte[] b) throws IOException {
        AzurePath.ensureFileSystemOpen(path);
        try {
            return this.blobInputStream.read(b);
        } catch (RuntimeException e) {
            throw LoggingUtility.logError(logger, new IOException(e));
        }
    }

    /**
     * Reads up to len bytes of data from the input stream into an array of bytes. An attempt is made to
     * read as many as len bytes, but a smaller number may be read. The number of bytes actually read is
     * returned as an integer. This method blocks until input data is available, end of file is detected, or an
     * exception is thrown.
     *
     * If len is zero, then no bytes are read and 0 is returned; otherwise, there is an attempt to read at
     * least one byte. If no byte is available because the stream is at end of file, the value -1 is returned;
     * otherwise, at least one byte is read and stored into b.
     *
     * The first byte read is stored into element b[off], the next one into b[off+1], and so
     * on. The number of bytes read is, at most, equal to len. Let k be the number of bytes
     * actually read; these bytes will be stored in elements b[off] through b[off+k-1],
     * leaving elements b[off+k] through
     * b[off+len-1] unaffected.
     *
     * In every case, elements b[0] through b[off] and elements b[off+len]
     * through b[b.length-1] are unaffected.
     *
     * @param b A byte array which represents the buffer into which the data is read.
     * @param off An int which represents the start offset in the byte array at which the data
     * is written.
     * @param len An int which represents the maximum number of bytes to read.
     * @return An int which represents the total number of bytes read into the buffer, or -1 if there is no
     * more data because the end of the stream has been reached.
     * @throws IOException If the first byte cannot be read for any reason other than end of file, or if the input
     * stream has been closed, or if some other I/O error occurs.
     * @throws NullPointerException If the byte array b is null.
     * @throws IndexOutOfBoundsException If off is negative, len is negative, or
     * len is greater than
     * b.length - off.
     */
    @Override
    public int read(final byte[] b, final int off, final int len) throws IOException {
        AzurePath.ensureFileSystemOpen(path);
        if (off < 0 || len < 0 || len > b.length - off) {
            throw logger.logExceptionAsError(new IndexOutOfBoundsException());
        }
        try {
            return this.blobInputStream.read(b, off, len);
        } catch (RuntimeException e) {
            throw LoggingUtility.logError(logger, new IOException(e));
        }
    }

    /**
     * Repositions this stream to the position at the time the mark method was last called on this input stream. Note
     * repositioning the blob read stream will disable blob MD5 checking.
     *
     * @throws IOException If this stream has not been marked or if the mark has been invalidated.
     */
    @Override
    public synchronized void reset() throws IOException {
        AzurePath.ensureFileSystemOpen(path);
        try {
            this.blobInputStream.reset();
        } catch (RuntimeException e) {
            if (e.getMessage().equals("Stream mark expired.")) {
                throw LoggingUtility.logError(logger, new IOException(e));
            }
            throw LoggingUtility.logError(logger, e);
        }
    }

    /**
     * Skips over and discards n bytes of data from this input stream. The skip method may, for a variety of reasons,
     * end up skipping over some smaller number of bytes, possibly 0. This may result from any of a number of
     * conditions; reaching end of file before n bytes have been skipped is only one possibility. The actual number of
     * bytes skipped is returned. If n is negative, no bytes are skipped.
     *
     * Note repositioning the blob read stream will disable blob MD5 checking.
     *
     * @param n A long which represents the number of bytes to skip.
     */
    @Override
    public synchronized long skip(final long n) throws IOException {
        AzurePath.ensureFileSystemOpen(path);
        return this.blobInputStream.skip(n);
    }
}


text:
//- @+5pkg defines/binding Package
//- @+3ParametersAreNonnullByDefault ref Annotation

/** Classes used to verify the Kythe Java indexer and its output. */
@ParametersAreNonnullByDefault
package pkg;

//- Package annotatedby Annotation

//- PkgDoc documents Package
//- PkgDoc.node/kind doc
//- PkgDoc.text "Classes used to verify the Kythe Java indexer and its output. "

import javax.annotation.ParametersAreNonnullByDefault;


text:
/**
 * Utilities that may or may not be in use.
 *
 * @author John Collins
 */
package org.powertac.customer;


text:
from django.utils.http import urlquote_plus

def urlencode(query, doseq=0, safe=''):
    """Custom urlencode that leaves static map delimiters ("|", ",", ":") alone.

    Based on Django's unicode-safe version of urllib.quote_plus.

    """
    safe = safe + '|,:'
    if hasattr(query, 'items'):
        query = query.items()
    return '&'.join([urlquote_plus(k, safe) + '=' + urlquote_plus(v, safe)
                     for k, s in query
                     for v in ((isinstance(s, basestring) and [s])
                               or (doseq and hasattr(s, '__len__') and s)
                               or [s])])


text:
package org.openfact.common.finance.internal.languages.russian;

import org.openfact.common.finance.internal.BaseValues;
import org.openfact.common.finance.internal.languages.GenderForms;
import org.openfact.common.finance.internal.languages.GenderType;
import org.openfact.common.finance.internal.languages.PluralForms;
import org.openfact.common.finance.internal.languages.SlavonicPluralForms;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import static org.openfact.common.finance.internal.languages.GenderForms.genderForms;
import static org.openfact.common.finance.internal.support.BaseNumbersBuilder.baseNumbersBuilder;

public class RussianValues implements BaseValues {

    @Override
    public Map<Integer, GenderForms> baseNumbers() {
        return baseNumbersBuilder()
                .put(0, "ноль")
                .put(1, genderForms("один", "одна", "один"))
                .put(2, genderForms("два", "две", "два"))
                .put(3, "три")
                .put(4, "четыре")
                .put(5, "пять")
                .put(6, "шесть")
                .put(7, "семь")
                .put(8, "восемь")
                .put(9, "девять")
                .put(10, "десять")
                .put(11, "одиннадцать")
                .put(12, "двенадцать")
                .put(13, "тринадцать")
                .put(14, "четырнадцать")
                .put(15, "пятнадцать")
                .put(16, "шестнадцать")
                .put(17, "семнадцать")
                .put(18, "восемнадцать")
                .put(19, "девятнадцать")
                .put(20, "двадцать")
                .put(30, "тридцать")
                .put(40, "сорок")
                .put(50, "пятьдесят")
                .put(60, "шестьдесят")
                .put(70, "семьдесят")
                .put(80, "восемьдесят")
                .put(90, "девяносто")
                .put(100, "сто")
                .put(200, "двести")
                .put(300, "триста")
                .put(400, "четыреста")
                .put(500, "пятьсот")
                .put(600, "шестьсот")
                .put(700, "семьсот")
                .put(800, "восемьсот")
                .put(900, "девятьсот")
                .build();
    }

    @Override
    public List<PluralForms> pluralForms() {
        return Arrays.<PluralForms>asList(
                new SlavonicPluralForms("", "", "", GenderType.MASCULINE),
                new SlavonicPluralForms("тысяча", "тысячи", "тысяч", GenderType.FEMININE),
                new SlavonicPluralForms("миллион", "миллиона", "миллионов", GenderType.MASCULINE),
                new SlavonicPluralForms("миллиард", "миллиарда", "миллиардов", GenderType.MASCULINE));
    }

    @Override
    public String connector() {
        return "руб.";
    }

    @Override
    public String twoDigitsNumberSeparator() {
        return " ";
    }
}


text:
#include <cstring>

#include "util/format.hpp"

#include "android_logger.hpp"

using namespace realm;
using namespace realm::jni_util;
using namespace realm::jni_impl;
using namespace realm::util;

std::shared_ptr<AndroidLogger> AndroidLogger::shared()
{
    // Private constructor, make_shared is not available.
    static std::shared_ptr<AndroidLogger> android_logger(new AndroidLogger());
    return android_logger;
}

void AndroidLogger::log(Log::Level level, const char* tag, jthrowable, const char* message)
{
    android_LogPriority android_log_priority;
    switch (level) {
        case Log::Level::trace:
            android_log_priority = ANDROID_LOG_VERBOSE;
            break;
        case Log::Level::debug:
            android_log_priority = ANDROID_LOG_DEBUG;
            break;
        case Log::Level::info:
            android_log_priority = ANDROID_LOG_INFO;
            break;
        case Log::Level::warn:
            android_log_priority = ANDROID_LOG_WARN;
            break;
        case Log::Level::error:
            android_log_priority = ANDROID_LOG_ERROR;
            break;
        case Log::Level::fatal:
            android_log_priority = ANDROID_LOG_FATAL;
            break;
        default: // Cannot get here.
            throw std::invalid_argument(format("Invalid log level: %1.", level));
    }
    if (message) {
        print(android_log_priority, tag, message);
    }
}

void AndroidLogger::print(android_LogPriority priority, const char* tag, const char* log_string)
{
    size_t log_size = strlen(log_string);

    if (log_size > LOG_ENTRY_MAX_LENGTH) {
        size_t start = 0;

        while (start < log_size) {
            size_t count = log_size - start > LOG_ENTRY_MAX_LENGTH ? LOG_ENTRY_MAX_LENGTH : log_size - start;
            std::string tmp_str(log_string, start, count);
            __android_log_write(priority, tag, tmp_str.c_str());
            start += count;
        }
    }
    else {
        __android_log_write(priority, tag, log_string);
    }
}

namespace realm {
namespace jni_util {

std::shared_ptr<JniLogger> get_default_logger()
{
    return std::static_pointer_cast<JniLogger>(AndroidLogger::shared());
}
}
}


text:
@implementation PAAppStoreQuery

+(void) initialize
{

}

-(void) loadAppWithAppId:(NSString *)appId completionBlock:(PAAppResultBlock)block{
    PAApp *app = (PAApp*)[PAApp objectWithClassName:kAppClassName];
    app.appId = appId;
    [self loadApp:app completionBlock:block];
}

-(void) loadApp:(PAApp *)app completionBlock:(PAAppResultBlock)block{
    NSArray* apps = @[app];
    [self loadApps:apps completionBlock:^(NSArray * apps, NSError * error) {
        if (block)
        {
            block(app, error);
        }
    }];
}

-(void) loadApps:(NSArray *)apps completionBlock:(void (^)(NSArray* apps, NSError * error))block{
    NSString *countryCode = [PAPiTunesCountry getStoreCountryForCurrenUser];
    [self loadApps: apps withCountry:countryCode completionBlock:block];
}

-(void) loadApps:(NSArray *)apps withCountry:(NSString*)country completionBlock:(void (^)(NSArray* apps, NSError * error))block{
    _isLoading = YES;

    NSMutableArray *appIds = [[NSMutableArray alloc]initWithCapacity:apps.count];
    for (PAApp* app in apps) {
        if(app.appId)
            [appIds addObject:app.appId];
    }

    NSSet *appsIdSet = [NSSet setWithArray:appIds];
    NSString *appString = [[appsIdSet allObjects] componentsJoinedByString:@","];
    NSMutableString *requestUrlString = [[NSMutableString alloc] init];
    [requestUrlString appendFormat:@"https://itunes.apple.com/lookup"];
    [requestUrlString appendFormat:@"?id=%@", appString];
    [requestUrlString appendFormat:@"&country=%@", country];
    NSURL *requestURL = [[NSURL alloc] initWithString:requestUrlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestURL];
    request.cachePolicy = self.cachePolicy;

    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
                                        success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
                                         {
                                             [self parseDictionary:JSON withApps:apps countryCode:country];
                                             _isLoading = NO;
                                             if (block)
                                             {
                                                 block(apps, nil);
                                             }
                                         }

                                        failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON)
                                         {
                                             _isLoading = NO;
                                             if (block)
                                             {
                                                 block(apps, error);
                                             }
                                         }];
    [operation start];
}

-(void) loadAppsForTerm:(NSString*)searchTerm completionBlock:(void (^)(NSArray* apps, NSError * error))block{
    NSString *countryCode = [PAPiTunesCountry getStoreCountryForCurrenUser];
    [self loadAppsForTerm:searchTerm withCountry:countryCode completionBlock:block];
}

-(void) loadAppsForTerm:(NSString*)searchTerm withCountry:(NSString*)countryCode completionBlock:(void (^)(NSArray* apps, NSError * error))block{

    _isLoading = YES;
    NSMutableString *requestUrlString = [[NSMutableString alloc] init];
    [requestUrlString appendFormat:@"https://itunes.apple.com/search"];
    [requestUrlString appendFormat:@"?term=%@", searchTerm];
    [requestUrlString appendFormat:@"&country=%@", countryCode];
    [requestUrlString appendFormat:@"&entity=software"];
    NSURL *requestURL = [[NSURL alloc] initWithString:[requestUrlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestURL];
    request.cachePolicy = self.cachePolicy;

    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
                                            success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
                                         {
                                             NSArray* apps = [self parseDictionary:JSON countryCode:countryCode];
                                             _isLoading = NO;
                                             if (block)
                                             {
                                                 block(apps, nil);
                                             }
                                         }

                                            failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON)
                                         {
                                             _isLoading = NO;
                                             if (block)
                                             {
                                                 block([[NSArray alloc]init], error);
                                             }
                                         }];
    [operation start];
}

-(void) parseDictionary:(NSDictionary *) dictionary withApps:(NSArray*)apps countryCode:(NSString*)countryCode
{
    NSArray *array = dictionary[@"results"];
    if(array == nil){
        NSLog(@"Expected 'results' array");
        return;
    }
    for (PAApp* app in apps) {
        for (NSDictionary *resultDict in array) {
            if(app.appId && [app.appId isEqualToString:[resultDict[@"trackId"] stringValue]])
            {
                [self parseApp:resultDict withApp:app countryCode:countryCode];
                break;
            }
        }
    }
}

-(NSArray*) parseDictionary:(NSDictionary *) dictionary countryCode:(NSString*)countryCode
{
    NSMutableArray* results = [[NSMutableArray alloc]init];

    NSArray *array = dictionary[@"results"];
    if(array == nil){
        NSLog(@"Expected 'results' array");
        return results;
    }

    for (NSDictionary *resultDict in array) {
        PAApp* app = (PAApp*)[PAApp objectWithClassName:kPAPAppClassKey];
        [self parseApp:resultDict withApp:app countryCode:countryCode];
        [results addObject:app];
    }
    return results;
}

-(void)parseApp:(NSDictionary *)result withApp:(PAApp*)app countryCode:(NSString*)countryCode
{
    app.bundleId = result[@"bundleId"];
    app.name = result[@"trackName"];
    app.genre = NSLocalizedString(result[@"primaryGenreName"],nil);
    app.appId = [result[@"trackId"] stringValue];
    app.iconIsPrerendered = [result[@"icon-is-prerendered"] boolValue];

    NSArray *features = result[@"features"];
    app.isUniversal = [features containsObject:@"iosUniversal"];
    app.formattedPrice = NSLocalizedString([result[@"formattedPrice"] uppercaseString],nil);
    NSString *iconUrlString = result[@"artworkUrl512"];

    NSString *iconThumbnailUrlString = result[@"artworkUrl60"];
    app.iconThumbnailURL = iconThumbnailUrlString;

    app.iconURL = result[@"artworkUrl100"];
    app.userRatingAllVersions = [result[@"averageUserRating"] floatValue];
    app.userRatingCountAllVersions = [result[@"userRatingCount"] integerValue];
    app.userRating = [result[@"averageUserRatingForCurrentVersion"] floatValue];
    app.userRatingCount = [result[@"userRatingCountForCurrentVersion"] integerValue];
    app.loaded = YES;

    [app setObject:app.appId forKey:kPAPAppIDKey];
    [app setObject:[countryCode lowercaseString] forKey:kPAPAppCountryKey];

    app.artistName= result[@"artistName"];
    app.artworkURL60= result[@"artworkUrl60"];
    app.artworkURL100= result[@"artworkUrl100"];
    app.storeURL= result[@"trackViewUrl"];
    app.kind= result[@"kind"];
    app.price= result[@"price"];
    app.currency= result[@"currency"];

    app.screenshotUrls = result[@"screenshotUrls"];

    if(app.screenshotUrls.count == 0 && iconUrlString)
    {
        app.screenshotUrls = @[iconUrlString];
    }
}

@end


text:
type BHMCTune <: SamplerTune
  logf::Nullable{Function}
  traveltime::Float64
  position::Vector{Float64}
  velocity::Vector{Float64}
  wallhits::Int
  wallcrosses::Int

  BHMCTune() = new()

  function BHMCTune(x::Vector, traveltime::Real, logf::Nullable{Function})
    n = length(x)
    new(logf, traveltime, randn(n), randn(n), 0, 0)
  end
end

BHMCTune(x::Vector, traveltime::Real) =
  BHMCTune(x, traveltime, Nullable{Function}())

BHMCTune(x::Vector, traveltime::Real, logf::Function) =
  BHMCTune(x, traveltime, Nullable{Function}(logf))

typealias BHMCVariate SamplerVariate{BHMCTune}

validate(v::BHMCVariate) = validatebinary(v)

#################### Sampler Constructor ####################

function BHMC(params::ElementOrVector{Symbol}, traveltime::Real)
  samplerfx = function(model::Model, block::Integer)
    block = SamplingBlock(model, block)
    v = SamplerVariate(block, traveltime)
    sample!(v, x -> logpdf!(block, x))
    relist(block, v)
  end
  Sampler(params, samplerfx, BHMCTune())
end

#################### Sampling Functions ####################

sample!(v::BHMCVariate) = sample!(v, v.tune.logf)

function sample!(v::BHMCVariate, logf::Function)
  tune = v.tune
  flag = false
  nearzero = 1e4 * eps()
  j = 0
  totaltime = 0.0                     ## time the particle already moved

  n = length(v)                       ## length of binary vector
  S = sign(tune.position)

  while true
    a = tune.velocity[:]
    b = tune.position[:]
    phi = atan2(b, a)

    ## time to hit or cross wall
    walltime = -phi
    idx = find(x-> x > 0.0, phi)
    walltime[idx] = pi - phi[idx]

    ## if there was a previous reflection (j > 0) and there is a potential
    ## reflection at the sample plane make sure that a new reflection at j
    ## is not found because of numerical error
    if j > 0
      if abs(walltime[j]) < nearzero || abs(walltime[j] - 2.0 * pi) < nearzero
        walltime[j] = Inf
      end
    end

    ## time till particle j hits or crosses wall
    movetime, j = findmin(walltime)
    if movetime == 0.0
      error("walking length zero")
    elseif movetime == Inf
      movetime = pi
    end

    totaltime += movetime
    if totaltime >= tune.traveltime
      movetime -= totaltime - tune.traveltime
      flag = true
    else
      tune.wallhits += 1
    end

    ## move the particle a time mt
    tune.velocity[:] = a * cos(movetime) - b * sin(movetime)
    tune.position[:] = a * sin(movetime) + b * cos(movetime)

    flag && break

    tune.position[j] = 0

    S1 = (S + ones(n)) / 2.0
    S1[j] = 0.0
    S2 = (S + ones(n)) / 2.0
    S2[j] = 1.0

    v2_new = tune.velocity[j]^2 +
             sign(tune.velocity[j]) * 2.0 * (logf(S2) - logf(S1))
    if v2_new > 0.0
      tune.velocity[j] = sqrt(v2_new) * sign(tune.velocity[j])
      S[j] *= -1.0
      tune.wallcrosses += 1
    else
      tune.velocity[j] *= -1.0
    end
  end

  ## convert from (-/+1) to (0/1)
  v[:] = (sign(tune.position) + ones(n)) / 2.0
  v
end


text:
Public Class frmMain

    Private Sub btnGo_Click(sender As Object, e As EventArgs) Handles btnGo.Click
        Call navigate()
    End Sub

    Private Sub txtBrowser_KeyDown(sender As Object, e As KeyEventArgs) Handles txtBrowser.KeyDown
        If e.KeyCode = Keys.Return Then
            Call navigate()
        End If
    End Sub

    Function navigate()
        wb1.Navigate(txtBrowser.Text)

        Return Nothing
    End Function

    Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click
        End
    End Sub

    Private Sub AboutToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AboutToolStripMenuItem.Click
        frmAbout.ShowDialog()
    End Sub

    Private Sub wb1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles wb1.DocumentCompleted
        tc1.TabPages(tc1.SelectedIndex).Text = wb1.DocumentTitle
        Me.Text = "Moogila - " & wb1.DocumentTitle
        Dim iconURL = "http://" & wb1.Url.Host & "/favicon.ico"
        Dim request As System.Net.WebRequest = System.Net.HttpWebRequest.Create(iconURL)
        Dim response As System.Net.HttpWebResponse = request.GetResponse()
        Dim stream As System.IO.Stream = response.GetResponseStream()
        Dim favicon = Image.FromStream(stream)
        If stream.WriteTimeout Then
            'PictureBox1.Image = favicon
        Else
            'web_pic.Image =  <<RESOURCE>>
        End If
    End Sub

    Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        cmb1.Items.Add("http://")
        cmb1.Items.Add("https://")

        cmb1.SelectedIndex = 0

        txtBrowser.Text = My.Settings.setDefaultURL
    End Sub

    '/* generate new object everytime user create new tab */
    Private Sub NewTabToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles NewTabToolStripMenuItem1.Click
        Dim tabpage As New TabPage
        tabpage.Text = "(empty)"

        Dim web1 As New WebBrowser
        web1.Parent = tabpage
        web1.Anchor = AnchorStyles.Bottom Or AnchorStyles.Left Or AnchorStyles.Right Or AnchorStyles.Top

        tc1.TabPages.Add(tabpage)
    End Sub

    Private Sub NewTabToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles NewTabToolStripMenuItem.Click
        NewTabToolStripMenuItem1_Click(sender, e)
    End Sub

    Private Sub wb1_StatusTextChanged(sender As Object, e As EventArgs) Handles wb1.StatusTextChanged
        ToolStripStatusLabel1.Text = wb1.StatusText
    End Sub

    Private Sub CloseTabToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles CloseTabToolStripMenuItem.Click
        tc1.TabPages.Remove(tc1.SelectedTab)
    End Sub

    Private Sub SettingsToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SettingsToolStripMenuItem.Click
        frmSettings.ShowDialog()
    End Sub
End Class


text:
package command

import (
	"fmt"
	"sort"
	"strconv"
	"strings"

	"github.com/hashicorp/vault/meta"
	"github.com/ryanuber/columnize"
)

// MountsCommand is a Command that lists the mounts.
type MountsCommand struct {
	meta.Meta
}

func (c *MountsCommand) Run(args []string) int {
	flags := c.Meta.FlagSet("mounts", meta.FlagSetDefault)
	flags.Usage = func() { c.Ui.Error(c.Help()) }
	if err := flags.Parse(args); err != nil {
		return 1
	}

	client, err := c.Client()
	if err != nil {
		c.Ui.Error(fmt.Sprintf(
			"Error initializing client: %s", err))
		return 2
	}

	mounts, err := client.Sys().ListMounts()
	if err != nil {
		c.Ui.Error(fmt.Sprintf(
			"Error reading mounts: %s", err))
		return 2
	}

	paths := make([]string, 0, len(mounts))
	for path := range mounts {
		paths = append(paths, path)
	}
	sort.Strings(paths)

	columns := []string{"Path | Type | Default TTL | Max TTL | Description"}
	for _, path := range paths {
		mount := mounts[path]
		defTTL := "system"
		switch {
		case mount.Type == "system":
			defTTL = "n/a"
		case mount.Type == "cubbyhole":
			defTTL = "n/a"
		case mount.Config.DefaultLeaseTTL != 0:
			defTTL = strconv.Itoa(mount.Config.DefaultLeaseTTL)
		}
		maxTTL := "system"
		switch {
		case mount.Type == "system":
			maxTTL = "n/a"
		case mount.Type == "cubbyhole":
			maxTTL = "n/a"
		case mount.Config.MaxLeaseTTL != 0:
			maxTTL = strconv.Itoa(mount.Config.MaxLeaseTTL)
		}
		columns = append(columns, fmt.Sprintf(
			"%s | %s | %s | %s | %s", path, mount.Type, defTTL, maxTTL, mount.Description))
	}

	c.Ui.Output(columnize.SimpleFormat(columns))
	return 0
}

func (c *MountsCommand) Synopsis() string {
	return "Lists mounted backends in Vault"
}

func (c *MountsCommand) Help() string {
	helpText := `
Usage: vault mounts [options]

  Outputs information about the mounted backends.

  This command lists the mounted backends, their mount points, the
  configured TTLs, and a human-friendly description of the mount point.
  A TTL of 'system' indicates that the system default is being used.

General Options:
` + meta.GeneralOptionsUsage()
	return strings.TrimSpace(helpText)
}


text:
<?php
namespace TSwiackiewicz\EventsCollector\Tests\Unit\Event\Watcher\Action\Handler;

use TSwiackiewicz\EventsCollector\Event\Watcher\Action\Handler\WatcherActionHandler;
use TSwiackiewicz\EventsCollector\Event\Watcher\Action\Handler\WatcherEmailActionHandler;
use TSwiackiewicz\EventsCollector\Exception\InvalidParameterException;
use TSwiackiewicz\EventsCollector\Tests\BaseTestCase;

/**
 * Class WatcherEmailActionHandlerTest
 * @package TSwiackiewicz\EventsCollector\Tests\Unit\Event\Watcher\Action\Handler
 */
class WatcherEmailActionHandlerTest extends BaseTestCase
{
    /**
     * @test
     */
    public function shouldCreateWatcherEmailActionHandler()
    {
        $handler = new WatcherEmailActionHandler('test@domain.com', 'Test');

        $this->assertInstanceOf(WatcherActionHandler::class, $handler);
    }

    /**
     * @test
     * @dataProvider getInvalidHandler
     *
     * @param array $invalidHandler
     */
    public function shouldThrowInvalidParameterExceptionWhenGivenHandlerIsInvalid(array $invalidHandler)
    {
        $this->setExpectedException(InvalidParameterException::class);

        new WatcherEmailActionHandler($invalidHandler[0], $invalidHandler[1]);
    }

    /**
     * @return array
     */
    public function getInvalidHandler()
    {
        return [
            [
                [
                    'test',
                    'Test'
                ]
            ],
            [
                [
                    'test@',
                    'Test'
                ]
            ],
            [
                [
                    '@test',
                    'Test'
                ]
            ],
            [
                [
                    'test@domain.com',
                    ''
                ]
            ],
            [
                [
                    'test@domain.com',
                    []
                ]
            ],
            [
                [
                    'test@domain.com',
                    false
                ]
            ],
            [
                [
                    'test@domain.com',
                    true
                ]
            ],
            [
                [
                    'test@domain.com',
                    null
                ]
            ],
            [
                [
                    'test@domain.com',
                    0
                ]
            ],
            [
                [
                    'test@domain.com',
                    -123
                ]
            ]
        ];
    }
}


text:
#ifndef ALINOUS_REMOTE_DB_CLIENT_COMMAND_DML_ENDSCANSTORAGECOMMAND_H_
#define ALINOUS_REMOTE_DB_CLIENT_COMMAND_DML_ENDSCANSTORAGECOMMAND_H_
namespace alinous {namespace remote {namespace db {namespace server {
class RemoteTableStorageServer;}}}}

namespace java {namespace io {
class BufferedOutputStream;}}

namespace java {namespace io {
class OutputStream;}}

namespace alinous {namespace remote {namespace socket {
class NetworkBinaryBuffer;}}}

namespace java {namespace io {
class InputStream;}}

namespace alinous {namespace db {namespace trx {
class DbVersionContext;}}}

namespace alinous {namespace remote {namespace db {namespace client {namespace command {
class AbstractRemoteStorageCommand;}}}}}

namespace java {namespace io {
class IOException;}}

namespace alinous {namespace runtime {namespace dom {
class VariableException;}}}

namespace alinous {
class ThreadContext;
}

namespace alinous {namespace remote {namespace db {namespace client {namespace command {namespace dml {

using namespace ::alinous;
using namespace ::java::lang;
using ::java::util::Iterator;
using ::java::io::BufferedOutputStream;
using ::java::io::IOException;
using ::java::io::InputStream;
using ::java::io::OutputStream;
using ::alinous::db::trx::DbVersionContext;
using ::alinous::remote::db::client::command::AbstractRemoteStorageCommand;
using ::alinous::remote::db::server::RemoteTableStorageServer;
using ::alinous::remote::socket::NetworkBinaryBuffer;
using ::alinous::runtime::dom::VariableException;

class EndScanStorageCommand final : public AbstractRemoteStorageCommand {
public:
	EndScanStorageCommand(const EndScanStorageCommand& base) = default;
public:
	EndScanStorageCommand(ThreadContext* ctx) throw() ;
	void __construct_impl(ThreadContext* ctx) throw() ;
	virtual ~EndScanStorageCommand() throw();
	virtual void __releaseRegerences(bool prepare, ThreadContext* ctx) throw();
private:
	DbVersionContext* vctx;
public:
	void executeOnServer(RemoteTableStorageServer* tableStorageServer, BufferedOutputStream* outStream, ThreadContext* ctx) final;
	void readFromStream(InputStream* stream, int remain, ThreadContext* ctx) final;
	DbVersionContext* getVctx(ThreadContext* ctx) throw() ;
	void setVctx(DbVersionContext* vctx, ThreadContext* ctx) throw() ;
	void writeByteStream(OutputStream* outStream, ThreadContext* ctx) final;
public:
	static bool __init_done;
	static bool __init_static_variables();
public:
	static void __cleanUp(ThreadContext* ctx);
};

}}}}}}

#endif /* end of ALINOUS_REMOTE_DB_CLIENT_COMMAND_DML_ENDSCANSTORAGECOMMAND_H_ */


text:
@interface PodsDummy_DiscogsAPI : NSObject
@end
@implementation PodsDummy_DiscogsAPI
@end


text:
call rake test
pause


text:
<!DOCTYPE html>
<html>
  <head>
    <script src="jschannel.js"></script>
    <script src="journaling.js"></script>
    <!-- No css file. Nothing to style, really. -->
  </head>
  <body>
    <!-- There's nothing here. The text box is actually in the edX page. -->
  </body>
</html>


text:
<?php

use tests\common\TestCommon;
use app\components\HelperPage;

$scenario->group('upload');
$I = new FunctionalTester($scenario);

TestCommon::logMeIn($I);

$I->wantTo('ensure that upload preview works for edit item page');
$I->amOnPage('/item/edit/6');

$I->expectTo('see correct title');
$I->see(HelperPage::EDIT_ITEM_PAGE_HEADER, 'h1');

$I->amGoingTo('Attache incorrect file');
$I->attachFile('input[type="file"]', 'file.txt');
$I->click('#form-upload-images input[type="submit"]');
$I->expectTo('see error message');
$I->see('Please fix the following errors:');
$I->see('Only files with these extensions are allowed: jpg, png');

TestCommon::logMeOut($I);


text:
/*
  Copyright 2011  Dean Camera (dean [at] fourwalledcubicle [dot] com)

  Permission to use, copy, modify, distribute, and sell this
  software and its documentation for any purpose is hereby granted
  without fee, provided that the above copyright notice appear in
  all copies and that both that the copyright notice and this
  permission notice and warranty disclaimer appear in supporting
  documentation, and that the name of the author not be used in
  advertising or publicity pertaining to distribution of the
  software without specific, written prior permission.

  The author disclaim all warranties with regard to this
  software, including all implied warranties of merchantability
  and fitness.  In no event shall the author be liable for any
  special, indirect or consequential damages or any damages
  whatsoever resulting from loss of use, data or profits, whether
  in an action of contract, negligence or other tortious action,
  arising out of or in connection with the use or performance of
  this software.
*/

/** \file
 *
 *  Header file for AudioOutput.c.
 */

#ifndef _AUDIO_OUTPUT_H_
#define _AUDIO_OUTPUT_H_

	/* Includes: */
		#include <avr/io.h>
		#include <avr/wdt.h>
		#include <avr/power.h>
		#include <avr/pgmspace.h>
		#include <avr/interrupt.h>
		#include <stdbool.h>

		#include "Descriptors.h"

		#include <LUFA/Version.h>
		#include <LUFA/Drivers/Board/LEDs.h>
		#include <LUFA/Drivers/Peripheral/ADC.h>
		#include <LUFA/Drivers/USB/USB.h>
		#include <LUFA/Drivers/USB/Class/MIDI.h>

	/* Macros: */
		/** LED mask for the library LED driver, to indicate that the USB interface is not ready. */
		#define LEDMASK_USB_NOTREADY      LEDS_LED1

		/** LED mask for the library LED driver, to indicate that the USB interface is enumerating. */
		#define LEDMASK_USB_ENUMERATING  (LEDS_LED2 | LEDS_LED3)

		/** LED mask for the library LED driver, to indicate that the USB interface is ready. */
		#define LEDMASK_USB_READY        (LEDS_LED2 | LEDS_LED4)

		/** LED mask for the library LED driver, to indicate that an error has occurred in the USB interface. */
		#define LEDMASK_USB_ERROR        (LEDS_LED1 | LEDS_LED3)

		/** Scale factor used to convert the floating point frequencies and ratios into a fixed point number */
		#define SCALE_FACTOR               65536

		/** Base (lowest) allowable MIDI note frequency */
		#define BASE_FREQUENCY             27.5

		/** Ratio between each note in an octave */
		#define NOTE_OCTIVE_RATIO          1.05946

		/** Lowest valid MIDI pitch index */
		#define BASE_PITCH_INDEX           21

		/** Maximum number of MIDI notes that can be played simultaneously */
		#define MAX_SIMULTANEOUS_NOTES     3

		/** Number of samples in the virtual sample table (can be expanded to lower maximum frequency, but allow for
		 *  more simultaneous notes due to the reduced amount of processing time needed when the samples are spaced out)
		 */
		#define VIRTUAL_SAMPLE_TABLE_SIZE  512

		/** Sample table increments per period for the base MIDI note frequency */
		#define BASE_INCREMENT             (((F_CPU / VIRTUAL_SAMPLE_TABLE_SIZE / 2) / BASE_FREQUENCY))

	/* Type Defines: */
		typedef struct
		{
			uint8_t  LRUAge;
			uint8_t  Pitch;
			uint32_t TableIncrement;
			uint32_t TablePosition;
		} DDSNoteData;

	/* Function Prototypes: */
		void SetupHardware(void);

		void EVENT_USB_Device_Connect(void);
		void EVENT_USB_Device_Disconnect(void);
		void EVENT_USB_Device_ConfigurationChanged(void);
		void EVENT_USB_Device_UnhandledControlRequest(void);

#endif


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

<title>Uses of Class pb.locationintelligence.model.CandidateRange</title>
<meta name="date" content="2020-04-16">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
pb.locationintelligence.model.CandidateRange

Packages that use CandidateRange

Package
Description

pb.locationintelligence.model

Uses of CandidateRange in pb.locationintelligence.model

Methods in pb.locationintelligence.model that return CandidateRange

Modifier and Type
Method and Description

CandidateRange
CandidateRange.customValues(java.util.Map<java.lang.String,java.lang.Object> customValues)

CandidateRange
CandidateRange.highHouse(java.lang.String highHouse)

CandidateRange
CandidateRange.lowHouse(java.lang.String lowHouse)

CandidateRange
CandidateRange.oddEvenIndicator(CandidateRange.OddEvenIndicatorEnum oddEvenIndicator)

CandidateRange
CandidateRange.placeName(java.lang.String placeName)

CandidateRange
CandidateRange.side(CandidateRange.SideEnum side)

CandidateRange
CandidateRange.units(java.util.List<CandidateRangeUnit> units)

Methods in pb.locationintelligence.model that return types with arguments of type CandidateRange

Modifier and Type
Method and Description

java.util.List<CandidateRange>
Candidate.getRanges()

Get ranges

Method parameters in pb.locationintelligence.model with type arguments of type CandidateRange

Modifier and Type
Method and Description

Candidate
Candidate.ranges(java.util.List<CandidateRange> ranges)

void
Candidate.setRanges(java.util.List<CandidateRange> ranges)

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
title: Direction
is_name: false

---

Direction Post


text:
<?php

namespace MessageBird\Objects;

/**
 * Class Group
 *
 * @package MessageBird\Objects
 */
class Group extends Base
{
    /**
     * An unique random ID which is created on the MessageBird
     * platform and is returned upon creation of the object.
     *
     * @var string
     */
    protected $id;

    /**
     * The URL of the created object.
     *
     * @var string
     */
    protected $href;

    /**
     * The name of the group.
     *
     * @var int
     */
    public $name;

    /**
     * The hash with the contacts in group.
     *
     * @var array
     */
    protected $contacts = array ();

    /**
     * The date and time of the creation of the group in RFC3339 format (Y-m-d\TH:i:sP)
     *
     * @var string
     */
    protected $createdDatetime;

    /**
     * The date and time of the updated of the group in RFC3339 format (Y-m-d\TH:i:sP)
     *
     * @var string
     */
    protected $updatedDatetime;

    /**
     * Get the created id
     *
     * @return mixed
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Get the created href
     *
     * @return string
     */
    public function getHref()
    {
        return $this->href;
    }

    /**
     * Get the $createdDatetime value
     *
     * @return string
     */
    public function getCreatedDatetime()
    {
        return $this->createdDatetime;
    }

    /**
     * Get the $updatedDatetime value
     *
     * @return string
     */
    public function getUpdatedDatetime()
    {
        return $this->createdDatetime;
    }

    /**
     * @param $object
     *
     * @return $this|void
     */
    public function loadFromArray ($object)
    {
        parent::loadFromArray($object);

        if (!empty($object->items)) {
            foreach($object->items AS &$item) {
                $Contact = new Contact();
                $Contact->loadFromArray($item);

                $item = $Contact;
            }
        }

        return $object;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE html PUBLIC  "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 <meta name="keywords" content="W3C SVG 1.1 Test Suite testsuite mobile"/>
 <meta name="description" content="W3C SVG 1.2 Tiny Test Suite"/>
 <title>
SVG 1.2 Tiny test:struct-cond-204-t </title>

Tiny version

Specification link: 5.8 Conditional processing

    struct-cond-03-t ←
    index
    → struct-cond-205-t

struct-cond-204-t

							SVG Image

							PNG Image

   	    		  			<object data="../svggen/struct-cond-204-t.svg" width="480" height="360" type="image/svg+xml">
FAIL
</object>

Required Formats Attribute

        A series of switches are used to determine which Internet Media types ('MIME types')
        are supported, using the 'requiredFormats' attribute,
        displaying a 'yes' or 'no' as appropriate. The test is passed if there is text in
        the second row of each column, and that text is only
        green (in the top table)
        or blueviolet (in the bottom table);
        no red text is displayed.

        The SVG Tiny 1.2 specification mandates certain formats, so these must be supported:
        image/jpeg, image/png, image/svg+xml.
        It is an error not to support them, therefore 'yes' is green and 'no' is red.

        This test also checks for support of Internet Media types which are
        assumed to not exist and are unlikely to ever be registered: garbage/garbage.
        Therefore, 'yes' is red and 'no' is green.

        Lastly, most media types are optional. For example, image/tiff may be
        supported but support is not mandated by the SVG Tiny 1.2 specification.
        The second table examines these optional formats.
        Both 'yes' and 'no' are displayed in blueviolet. Whether the particular Internet Media type
        is supported or not does not affect whether the test is passed or failed, but does provide useful
        information about the optional capabilities of a particular implementation.

				struct-cond-03-t ←
				index
				→ struct-cond-205-t


text:
(function() {
  'use strict';
  Module.loaded('event', 'effect-util')
    .add('keypad', function(EventManager, EffectUtil) {
    var $window = $(window);

    /**
      Wriggle if a key is clicked and then send out the 'selected' event.
    */
    function addClickToWriggleKey($keys, Keypad) {
      $keys.click(function() {
        var $key = $(this);
        // After the animation ends, remove the class.
        $key.one(EffectUtil.ANIMATION_END_EVENT_NAMES, function() {
          $key.removeClass('wriggle');
        });
        $key.removeClass('wriggle').addClass('wriggle');

        // Broadcast selected event and the key.
        var eventData = {
            selectedKey: parseInt($key.text(), 10),
            $key: $key
        };
        EventManager.trigger('selected', eventData);
      });
    }

    var Keypad = {
      Model: {},
      View: {
        $keys: $('.key'),

        fadeIn: function() {
          var $keys = Keypad.View.$keys;
          $keys.each(function(index) {
            var $key = $(this);
            $key.on(EffectUtil.ANIMATION_END_EVENT_NAMES, function() {
              $key.removeClass('fadein');
            });

            setTimeout(function() {
                $key.addClass('fadein').removeClass('transparent');
            }, 100 * index);
          });
        },

        /**
          Move the target key to the selected cell.
        */
        moveKeyToCell: function($key, options) {
          options = options || {};
          var destination = options.$selectedCell.position();
          var boardMarginLeft = options.boardMarginLeft;

          return $($key).animate({
            // Resize & place the key in the middle of the selected cell.
            top: destination.top,
            left: destination.left + boardMarginLeft,
            width: options.cellSize,
            height: options.cellSize,
            'line-height': options.cellSize
          }, 500);
        },

        /**
          Move the target key back to its original position.
        */
        moveKeyToInitialPosition: function($key, initialPosition, initialKeySize) {
          return $key.animate({
            opacity: '0'
          }, 500).promise().pipe(function() {
            Keypad.View.animateKeyToInitialPosition($key, initialPosition, initialKeySize, 0);
          }).pipe(function() {
            $key.animate({
              opacity: '1'
            }, 500);
          });
        },

        /**
          Animate the key to the initial position.
        */
        animateKeyToInitialPosition: function($key, initialPosition, initialKeySize, ms) {
          return $key.animate({
            top: initialPosition.top,
            left: initialPosition.left,
            width: initialKeySize.width,
            height: initialKeySize.height,
            'line-height': initialKeySize.height
          }, typeof(ms) !== 'undefined' ? ms : 500);
        },

        shakeKey: function($key, cellSize) {
          return $key.animate({
            left: '-=' + cellSize + 'px'
          }, 100).promise().pipe(function() {
            $key.animate({
              left: '+=' + cellSize * 2 + 'px'
            }, 100);
          }).pipe(function() {
            $key.animate({
              left: '-=' + cellSize + 'px'
            }, 100);
          });
        }
      },

      Controller: {
        /**
          Constructor
        */
        init: function() {
          addClickToWriggleKey(Keypad.View.$keys, Keypad);
        },

        /**
          Adjust the size of the keys and their fonts,
          and then the position of each key based on the size of the board.
          input:
            boardSize: size object that contains the width and height of the borad.
        */
        adjustKeySizeAndUpdatePosition: function(boardSize) {
          if (!boardSize) { return; }

          // TODO: Remove magic numbers.
          var $keys = Keypad.View.$keys;
          var keySize = boardSize.width / 6;
          var keyMargin = boardSize.width / 25;
          var fontSize = keySize * 25 / 60;

          // The position where the keys will be enumerated.
          var boardBottomPosition = {
            top: boardSize.height + 30,
            left: ($window.width() - boardSize.width) / 2
          };

          // Update key and font sizes.
          $keys
            .width(keySize)
            .height(keySize)
            .css('line-height', '' + keySize + 'px')
            .css('font-size', '' + fontSize + 'px');

          // Rearrange the key sizes.
          $keys.each(function(index) {
            var $key = $(this);
            // Place key 1-5 to the top.
            if (index < 5) {
              $key.css('top', '' + boardBottomPosition.top + 'px');
              $key.css('left', '' + (boardBottomPosition.left + index * (keySize + keyMargin)) + 'px');
            } else {
            // Place key 6-9 to the bottom.
              $key.css('top', '' + (boardBottomPosition.top + (keySize + keyMargin)) + 'px');
              $key.css('left', '' + (boardBottomPosition.left + (index - 5) * (keySize + keyMargin)) + 'px');
            }
          });
        },

        /**
          Show wriggling effect for all keys.
        */
        wriggleKeys: function() {
          Keypad.View.$keys.each(function(index) {
            var $key = $(this);

            $key.one(EffectUtil.ANIMATION_END_EVENT_NAMES, function() {
              $key.removeClass('wriggle');
            });

            setTimeout(function() {
              $key.removeClass('wriggle').addClass('wriggle');
            }, 20 * index);
          });
        }
      }
    };

    Keypad.Controller.init();
    return Keypad;
  });
}());


text:
'*******************************************************************************************'
'                                                                                '
' Download Free Evaluation Version From:     https://bytescout.com/download/web-installer   '
'                                                                                '
' Also available as Web API! Get free API Key https://app.pdf.co/signup                     '
'                                                                                '
' Copyright © 2017-2020 ByteScout, Inc. All rights reserved.                                '
' https://www.bytescout.com                                                                 '
' https://www.pdf.co                                                                        '
'*******************************************************************************************'

Imports System.Diagnostics
Imports Bytescout.BarCode

Class Program
	Friend Shared Sub Main(args As String())
		' Create new barcode
		Dim barcode As New Barcode()

		' Set symbology
		barcode.Symbology = SymbologyType.Code39
		' Set value
		barcode.Value = "Sample"

		' Specify barcode size by bounds to fit into.
		' You can use any measure units.
		barcode.FitInto(5, 3, UnitOfMeasure.Inch)

		' Save barcode to image
		barcode.SaveImage("result.png")

		' Show image in default image viewer
		Process.Start("result.png")
	End Sub
End Class


text:
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="UTF-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"
    />
    <meta name="format-detection" content="telephone=no" />
    <meta name="msapplication-tap-highlight" content="no" />
  </head>
  <body>
    <script>
      function detectMobilePlatform() {
        if (
          typeof navigator === 'undefined' &&
          (typeof window === 'undefined' || typeof window.opera === 'undefined')
        ) {
          // not browser env
          return 'unknown'
        }
        var userAgent = navigator.userAgent || navigator.vendor || window.opera
        if (/windows phone/i.test(userAgent)) {
          return 'Windows Phone'
        }
        if (/android/i.test(userAgent)) {
          return 'Android'
        }
        if (/ipad|iphone|ipod/i.test(userAgent)) {
          return 'iOS'
        }
        return 'unknown'
      }
      var platform = detectMobilePlatform()
      if (platform === 'unknown') {
        document.write('not mobile platform')
      } else {
        document.write('mobile platform: ' + detectMobilePlatform())
      }
    </script>
  </body>
</html>