text:
/**
 * Copyright 2015 ThoughtWorks Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may obtain
 * a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

(function () {
  'use strict';

  describe('MetadataModalController', function () {
    var $controller, treeService, modalInstance, toast;

    var metadataService = {
      editMetadata: function() {}
    };

    var availableItem = {
      'namespace': 'bug1606988',
      'properties': {
        'UPPER_lower': {
          'items': {
            'enum': [
              'foo',
              'bar'
            ],
            'type': 'string'
          },
          'type': 'array'
        }
      }
    };

    var existing = {
      'upper_lower': 'foo',
      'custom': 'bar'
    };

    beforeEach(function() {
      modalInstance = {
        dismiss: jasmine.createSpy(),
        close: jasmine.createSpy()
      };
    });

    beforeEach(module('horizon.app.core.metadata.modal',
      'horizon.framework'));
    beforeEach(inject(function (_$controller_, $injector) {
      $controller = _$controller_;
      treeService = $injector.get('horizon.framework.widgets.metadata.tree.service');
      toast = $injector.get('horizon.framework.widgets.toast.service');
      spyOn(toast, 'add');
    }));

    it('should dismiss modal on cancel', function () {
      var controller = createController(modalInstance);

      controller.cancel();

      expect(modalInstance.dismiss).toHaveBeenCalledWith('cancel');
    });

    it('should close modal on successful save', function () {
      var controller = createController(modalInstance);
      metadataService.editMetadata = function() {
        return {
          then: function(success) {
            success();
          }
        };
      };

      spyOn(metadataService, 'editMetadata').and.callThrough();

      controller.save();

      expect(modalInstance.close).toHaveBeenCalled();
      expect(metadataService.editMetadata)
        .toHaveBeenCalledWith('aggregate', '123', {'custom': 'bar'}, ['UPPER_lower']);
      expect(toast.add).toHaveBeenCalledWith('success', 'Metadata was successfully updated.');
    });

    it('should clear saving flag on failed save', function() {
      var controller = createController(modalInstance);
      metadataService.editMetadata = function() {
        return {
          then: function(success, fail) {
            fail();
          }
        };
      };

      spyOn(metadataService, 'editMetadata').and.callThrough();

      controller.save();

      expect(modalInstance.close).not.toHaveBeenCalled();
      expect(metadataService.editMetadata)
        .toHaveBeenCalledWith('aggregate', '123', {'custom': 'bar'}, ['UPPER_lower']);
      expect(toast.add).toHaveBeenCalledWith('error', 'Unable to update metadata.');
    });

    function createController() {
      //Purposely use different cases in available and existing.
      return $controller('MetadataModalController', {
        '$modalInstance': modalInstance,
        'horizon.framework.widgets.metadata.tree.service': treeService,
        'horizon.app.core.metadata.service': metadataService,
        'available': {data: {items: [availableItem]}},
        'existing': {data: existing},
        'params': {resource: 'aggregate', id: '123'}
      });
    }
  });
})();


text:
// prettier配置项说明 https://blog.csdn.net/peade/article/details/103865934
module.exports = {
  printWidth: 160, //编辑器每行的长度，默认80
  tabWidth: 2, //制表符tab的宽度，默认值是2
  useTabs: false, //代码缩进是否用制表符tab，默认false
  semi: false, //是否使用分号，默认true，使用分号
  singleQuote: true, //是否使用单引号，默认为false，不适用单引号，使用双引号
  quoteProps: "as-needed", //对象属性的引号使用 as-needed 仅在需要的时候使用 consistent 有一个属性需要引号，就都需要引号 preserve 保留用户输入的情况
  jsxSingleQuote: false,
  trailingComma: "es5", //末尾逗号 none 末尾没有逗号 es5 es5有效的地方保留 all 在可能的地方都加上逗号
  bracketSpacing: true, //字面量对象括号中的空格，默认true true - Example: { foo: bar }.  false - Example: {foo: bar}.
  jsxBracketSameLine: false,
  arrowParens: "always", //箭头函数中的括号
  endOfLine: "lf", //行末尾标识
  htmlWhitespaceSensitivity: "ignore",
  vueIndentScriptAndStyle: true,
};

domain: javascript


text:
var webpack = require('webpack');
var path = require('path');

var BUILD_DIR = path.resolve(__dirname, 'public');
var APP_DIR = path.resolve(__dirname, 'src/client');

var config = {
  entry: [
    APP_DIR + '/index.jsx'
  ],

  output: {
    path: BUILD_DIR,
    filename: 'bundle.js',
    publicPath: '/'
  },

  resolve: {
    extensions: ['.js', '.jsx']
  },

  module : {
    rules : [
      {
        test : /\.jsx?/,
        include : APP_DIR,
        use : 'babel-loader'
      },
      {
        test: /\.less/,
        loader: 'style-loader!css-loader!less-loader'
      },
      {
        test: /\.css$/,
        loader: 'style-loader!css-loader'
      }
    ]
  }
};

module.exports = config;


text:
global.__dirname = __dirname
jest.mock('@redwoodjs/internal', () => {
  const path = require('path')
  return {
    ...jest.requireActual('@redwoodjs/internal'),
    getPaths: () => {
      const BASE_PATH = path.join(global.__dirname, 'fixtures')
      return {
        base: BASE_PATH,
        api: {
          db: BASE_PATH, // this folder
        },
      }
    },
  }
})

import path from 'path'

import * as index from '../index'

test('getSchema returns a parsed schema.prisma', async () => {
  let schema = await index.getSchema('Post')
  expect(schema.fields[0].name).toEqual('id')
  expect(schema.fields[1].name).toEqual('title')
  expect(schema.fields[2].name).toEqual('slug')

  // can get a different model
  schema = await index.getSchema('User')
  expect(schema.fields[0].name).toEqual('id')
  expect(schema.fields[1].name).toEqual('name')
  expect(schema.fields[2].name).toEqual('email')
})

test('getSchema throws an error if model name not found', async () => {
  let error

  try {
    await index.getSchema('Foo')
  } catch (e) {
    error = e
  }

  expect(error).toEqual(new Error(error.message))
})

test('nameVariants returns a single word cased variables', () => {
  const names = ['Home', 'home']

  names.forEach((name) => {
    const vars = index.nameVariants(name)

    expect(vars.pascalName).toEqual('Home')
    expect(vars.camelName).toEqual('home')
    expect(vars.singularPascalName).toEqual('Home')
    expect(vars.pluralPascalName).toEqual('Homes')
    expect(vars.singularCamelName).toEqual('home')
    expect(vars.pluralCamelName).toEqual('homes')
    expect(vars.singularParamName).toEqual('home')
    expect(vars.pluralParamName).toEqual('homes')
    expect(vars.singularConstantName).toEqual('HOME')
    expect(vars.pluralConstantName).toEqual('HOMES')
  })
})

test('nameVariants returns a multi word cased variables', () => {
  const names = ['FooBar', 'fooBar', 'foo_bar', 'foo-bar']

  names.forEach((name) => {
    const vars = index.nameVariants(name)

    expect(vars.pascalName).toEqual('FooBar')
    expect(vars.camelName).toEqual('fooBar')
    expect(vars.singularPascalName).toEqual('FooBar')
    expect(vars.pluralPascalName).toEqual('FooBars')
    expect(vars.singularCamelName).toEqual('fooBar')
    expect(vars.pluralCamelName).toEqual('fooBars')
    expect(vars.singularParamName).toEqual('foo-bar')
    expect(vars.pluralParamName).toEqual('foo-bars')
  })
})

test('generateTemplate returns a lodash-templated string', () => {
  const output = index.generateTemplate(path.join('fixtures', 'text.txt'), {
    root: __dirname,
    name: 'amet',
    noun: 'world',
  })

  expect(output).toEqual(`Lorem ipsum dolar sit amet\nHello, world!\n`)
})

// Be careful when editing the code.js fixture as the prettifier.config.js will cause it to get
// prettified and then it already match the expected output, with no changes
test('generateTemplate returns prettified JS code', () => {
  const output = index.generateTemplate(path.join('fixtures', 'code.js'), {
    root: __dirname,
    name: 'fox',
    foo: 'dog',
  })

  expect(output).toEqual(
    `const line1 = 'The quick brown foxes jumps over the lazy dog.'\nconst line2 = 'Sphinx of black quartz, judge my vow.'\n`
  )
})


text:
import React from "react"
import styled from "styled-components"
import { useIntl } from "gatsby-plugin-intl"
import { StaticQuery, graphql } from "gatsby"

import { getLangContentVersion } from "../utils/translations"
import { getLocaleTimestamp } from "../utils/moment"
import Translation from "./Translation"
import Link from "./Link"
import Icon from "./Icon"
import { Mixins } from "./Theme"

const StyledFooter = styled.footer`
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  padding-top: 3rem;
  padding-bottom: 4rem;
  max-width: ${(props) => props.theme.breakpoints.xl};
  padding: 1rem 0;
  @media (max-width: ${(props) => props.theme.breakpoints.xl}) {
    padding: 1rem 2rem;
  }
`

const FooterTop = styled.div`
  ${Mixins.textLevel8}
  margin: 0;
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
`

const LastUpdated = styled.div`
  color: ${(props) => props.theme.colors.text200};
`

const LinkSection = styled.div`
  min-width: 300px;
  @media (min-width: ${(props) => props.theme.breakpoints.l}) {
    min-width: initial;
  }
`

const SectionHeader = styled.h3`
  ${Mixins.textLevel8}
  font-weight: bold;
`

const List = styled.ul`
  ${Mixins.textLevel8}
  margin: 0;
  list-style-type: none;
  list-style-image: none;
`

const ListItem = styled.li`
  margin-bottom: 1rem;
`

const FooterLink = styled(Link)`
  color: ${(props) => props.theme.colors.text200};
  &:after {
    color: ${(props) => props.theme.colors.text200};
  }
  &:hover {
    color: ${(props) => props.theme.colors.primary};
    &:after {
      color: ${(props) => props.theme.colors.primary};
    }
  }
`

const SocialIcons = styled.div`
  margin: 1rem 0;
`
const SocialIcon = styled(Icon)`
  margin-left: 0.5rem;

  @media (max-width: ${(props) => props.theme.breakpoints.s}) {
    margin-left: 0;
    margin-right: 0.5rem;
  }
`

const socialLinks = [
  {
    icon: "github",
    to: "https://github.com/ethereum",
  },
  {
    icon: "twitter",
    to: "https://twitter.com/ethereum",
  },
  {
    icon: "youtube",
    to: "https://youtube.com/channel/UCNOfzGXD_C9YMYmnefmPH0g",
  },
]

const Footer = () => {
  const intl = useIntl()

  const contentVersion = getLangContentVersion(intl.locale)

  const linkSections = [
    {
      title: "page-individuals",
      links: [
        {
          to: `/what-is-ethereum/`,
          text:
            contentVersion > 1
              ? "page-home-section-individuals-item-one"
              : "page-home-section-beginners-item-two",
          shouldDisplay: true,
        },
        {
          to: `/use/`,
          text: "page-use",
          shouldDisplay: contentVersion < 1.1,
        },
        {
          to: `/eth/`,
          text: "page-home-section-individuals-item-four",
          shouldDisplay: contentVersion >= 1.1,
        },
        {
          to: `/dapps/`,
          text: "page-home-section-individuals-item-two",
          shouldDisplay: contentVersion >= 1.1,
        },
        {
          to: `/wallets/`,
          text: "page-home-section-individuals-item-five",
          shouldDisplay: contentVersion >= 1.1,
        },
        {
          to: `/learn/`,
          text:
            contentVersion > 1
              ? "page-home-section-individuals-item-three"
              : "page-learn",
          shouldDisplay: true,
        },
        {
          to: `/community/`,
          text: "page-community",
          shouldDisplay: contentVersion > 1.1,
        },
      ],
    },
    {
      title: "page-developers",
      links: [
        {
          to: `/build/`,
          text: "get-started",
          shouldDisplay: contentVersion >= 1.1,
        },
        {
          to: "https://studio.ethereum.org/",
          text: "ethereum-studio",
          shouldDisplay: true,
        },
        {
          to: `/developers/`,
          text: contentVersion > 1 ? "developer-resources" : "page-developers",
          shouldDisplay: true,
        },
        {
          to: "/whitepaper/",
          text: "footer-ethereum-whitepaper",
          shouldDisplay: contentVersion > 1.1,
        },
      ],
    },
    {
      title: "footer-ecosystem",
      links: [
        {
          to: "/foundation/",
          text: "ethereum-foundation",
          shouldDisplay: contentVersion > 1.1,
        },
        {
          to: "https://blog.ethereum.org/",
          text: "footer-blog",
          shouldDisplay: true,
        },
        {
          to: "https://esp.ethereum.foundation",
          text: "footer-esp",
          shouldDisplay: true,
        },
        {
          to: "/eips/",
          text: "footer-eips",
          shouldDisplay: contentVersion > 1.1,
        },
        {
          to: "/assets/",
          text: "ethereum-brand-assets",
          shouldDisplay: true,
        },
        {
          to: "https://devcon.org/",
          text: "devcon",
          shouldDisplay: true,
        },
      ],
    },
    {
      title: "footer-about",
      links: [
        {
          to: "/en/about/",
          text: "footer-about-us",
          shouldDisplay: true,
        },
        {
          to: "/en/languages/",
          text: "language-support",
          shouldDisplay: true,
        },
        {
          to: "/en/privacy-policy/",
          text: "privacy-policy",
          shouldDisplay: true,
        },
        {
          to: "/en/terms-of-use/",
          text: "terms-of-use",
          shouldDisplay: true,
        },
        {
          to: "/en/cookie-policy/",
          text: "cookie-policy",
          shouldDisplay: true,
        },
        {
          to: "mailto:press@ethereum.org",
          text: "contact",
          shouldDisplay: true,
        },
      ],
    },
  ]

  return (
    <StaticQuery
      query={graphql`
        query FooterQuery {
          allSiteBuildMetadata {
            edges {
              node {
                buildTime
              }
            }
          }
        }
      `}
      render={(data) => (
        <StyledFooter>
          <FooterTop>
            <LastUpdated>
              <Translation id="website-last-updated" />:{" "}
              {getLocaleTimestamp(
                intl.locale,
                data.allSiteBuildMetadata.edges[0].node.buildTime
              )}
            </LastUpdated>
            <SocialIcons>
              {socialLinks.map((link, idx) => {
                return (
                  <Link to={link.to} hideArrow={true} key={idx}>
                    <SocialIcon name={link.icon} size="36" />
                  </Link>
                )
              })}
            </SocialIcons>
          </FooterTop>
          {linkSections.map((section, idx) => {
            return (
              <LinkSection key={idx}>
                <SectionHeader>
                  <Translation id={section.title} />
                </SectionHeader>
                <List>
                  {section.links
                    .filter((link) => link.shouldDisplay)
                    .map((link, linkIdx) => {
                      return (
                        <ListItem key={linkIdx}>
                          <FooterLink to={link.to}>
                            <Translation id={link.text} />
                          </FooterLink>
                        </ListItem>
                      )
                    })}
                </List>
              </LinkSection>
            )
          })}
        </StyledFooter>
      )}
    />
  )
}

export default Footer


text:
var ErrorEnum = {
  'Config_Error':            [1000,'配置错误'],
  'Api_Name_Null':           [1001,'API名称为空'],
  'Api_Not_Support':         [1002,'不支持的API'],
  'Api_Service_Not_Exist':   [1003,'API对应的服务不存在'],
  'Token_Not_Valid':         [1004,'TOKEN无效'],
  'Sign_Not_Valid':          [1005,'签名无效'],
  'Out_Of_Call':             [1006,'超出调用次数'],
  'Out_Of_Service':          [1007,'暂停服务'],
  'Sign_Type_Not_Valid':     [1008,'签名类型无效'],
  'Merchant_Not_Valid':      [1009,'商户无效'],
  'Param_Not_Valid':         [1010,'参数无效'],
  'Charset_Not_Valid':       [1011,'字符集无效'],
  'Network_Error':           [1012,'网络异常'],
  'Method_Not_Allowed':      [1013,'方法不被允许'],
  'Upload_File_Not_Exist':   [1014,'文件不存在'],
  'Upload_Fail':             [1015,'上传失败'],
  'Merchant_No_Authority':   [1016,'商户未授权']
};

module.exports = ErrorEnum;


text:
// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html

module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular-devkit/build-angular'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular-devkit/build-angular/plugins/karma')
    ],
    client: {
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    coverageIstanbulReporter: {
      dir: require('path').join(__dirname, './coverage/skyclubitalia-economy-app'),
      reports: ['html', 'lcovonly', 'text-summary'],
      fixWebpackSourcePaths: true
    },
    reporters: ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false,
    restartOnFileChange: true
  });
};


text:
var JQVMap = function (params) {
  params = params || {};
  var map = this;
  var mapData = JQVMap.maps[params.map];
  var mapPins;

  if( !mapData){
    throw new Error('Invalid "' + params.map + '" map parameter. Please make sure you have loaded this map file in your HTML.');
  }

  this.selectedRegions = [];
  this.multiSelectRegion = params.multiSelectRegion;

  this.container = params.container;

  this.defaultWidth = mapData.width;
  this.defaultHeight = mapData.height;

  this.color = params.color;
  this.selectedColor = params.selectedColor;
  this.hoverColor = params.hoverColor;
  this.hoverColors = params.hoverColors;
  this.hoverOpacity = params.hoverOpacity;
  this.setBackgroundColor(params.backgroundColor);

  this.width = params.container.width();
  this.height = params.container.height();

  this.resize();

  jQuery(window).resize(function () {
    var newWidth = params.container.width();
    var newHeight = params.container.height();

    if(newWidth && newHeight){
      map.width = newWidth;
      map.height = newHeight;
      map.resize();
      map.canvas.setSize(map.width, map.height);
      map.applyTransform();

      var resizeEvent = jQuery.Event('resize.jqvmap');
      jQuery(params.container).trigger(resizeEvent, [newWidth, newHeight]);

      if(mapPins){
        jQuery('.jqvmap-pin').remove();
        map.pinHandlers = false;
        map.placePins(mapPins.pins, mapPins.mode);
      }
    }
  });

  this.canvas = new VectorCanvas(this.width, this.height, params);
  params.container.append(this.canvas.canvas);

  this.makeDraggable();

  this.rootGroup = this.canvas.createGroup(true);

  this.index = JQVMap.mapIndex;
  this.label = jQuery('<div/>').addClass('jqvmap-label').appendTo(jQuery('body')).hide();

  if (params.enableZoom) {
    jQuery('<div/>').addClass('jqvmap-zoomin').text('+').appendTo(params.container);
    jQuery('<div/>').addClass('jqvmap-zoomout').html('−').appendTo(params.container);
  }

  map.countries = [];

  for (var key in mapData.paths) {
    var path = this.canvas.createPath({
      path: mapData.paths[key].path
    });

    path.setFill(this.color);
    path.id = map.getCountryId(key);
    map.countries[key] = path;

    if (this.canvas.mode === 'svg') {
      path.setAttribute('class', 'jqvmap-region');
    } else {
      jQuery(path).addClass('jqvmap-region');
    }

    jQuery(this.rootGroup).append(path);
  }

  jQuery(params.container).delegate(this.canvas.mode === 'svg' ? 'path' : 'shape', 'mouseover mouseout', function (e) {
    var containerPath = e.target,
      code = e.target.id.split('_').pop(),
      labelShowEvent = jQuery.Event('labelShow.jqvmap'),
      regionMouseOverEvent = jQuery.Event('regionMouseOver.jqvmap');

    code = code.toLowerCase();

    if (e.type === 'mouseover') {
      jQuery(params.container).trigger(regionMouseOverEvent, [code, mapData.paths[code].name]);
      if (!regionMouseOverEvent.isDefaultPrevented()) {
        map.highlight(code, containerPath);
      }
      if (params.showTooltip) {
        map.label.text(mapData.paths[code].name);
        jQuery(params.container).trigger(labelShowEvent, [map.label, code]);

        if (!labelShowEvent.isDefaultPrevented()) {
          map.label.show();
          map.labelWidth = map.label.width();
          map.labelHeight = map.label.height();
        }
      }
    } else {
      map.unhighlight(code, containerPath);

      map.label.hide();
      jQuery(params.container).trigger('regionMouseOut.jqvmap', [code, mapData.paths[code].name]);
    }
  });

  jQuery(params.container).delegate(this.canvas.mode === 'svg' ? 'path' : 'shape', 'click', function (regionClickEvent) {

    var targetPath = regionClickEvent.target;
    var code = regionClickEvent.target.id.split('_').pop();
    var mapClickEvent = jQuery.Event('regionClick.jqvmap');

    code = code.toLowerCase();

    jQuery(params.container).trigger(mapClickEvent, [code, mapData.paths[code].name]);

    if ( !params.multiSelectRegion && !mapClickEvent.isDefaultPrevented()) {
      for (var keyPath in mapData.paths) {
        map.countries[keyPath].currentFillColor = map.countries[keyPath].getOriginalFill();
        map.countries[keyPath].setFill(map.countries[keyPath].getOriginalFill());
      }
    }

    if ( !mapClickEvent.isDefaultPrevented()) {
      if (map.isSelected(code)) {
        map.deselect(code, targetPath);
      } else {
        map.select(code, targetPath);
      }
    }
  });

  if (params.showTooltip) {
    params.container.mousemove(function (e) {
      if (map.label.is(':visible')) {
        var left = e.pageX - 15 - map.labelWidth;
        var top = e.pageY - 15 - map.labelHeight;

        if(left < 0) {
          left = e.pageX + 15;
        }
        if(top < 0) {
          top = e.pageY + 15;
        }

        map.label.css({
          left: left,
          top: top
        });
      }
    });
  }

  this.setColors(params.colors);

  this.canvas.canvas.appendChild(this.rootGroup);

  this.applyTransform();

  this.colorScale = new ColorScale(params.scaleColors, params.normalizeFunction, params.valueMin, params.valueMax);

  if (params.values) {
    this.values = params.values;
    this.setValues(params.values);
  }

  if (params.selectedRegions) {
    if (params.selectedRegions instanceof Array) {
      for(var k in params.selectedRegions) {
        this.select(params.selectedRegions[k].toLowerCase());
      }
    } else {
      this.select(params.selectedRegions.toLowerCase());
    }
  }

  this.bindZoomButtons();

  if(params.pins) {
    mapPins = {
      pins: params.pins,
      mode: params.pinMode
    };

    this.pinHandlers = false;
    this.placePins(params.pins, params.pinMode);
  }

  if(params.showLabels){
    this.pinHandlers = false;

    var pins = {};
    for (key in map.countries){
      if (typeof map.countries[key] !== 'function') {
        if( !params.pins || !params.pins[key] ){
          pins[key] = key.toUpperCase();
        }
      }
    }

    mapPins = {
      pins: pins,
      mode: 'content'
    };

    this.placePins(pins, 'content');
  }

  JQVMap.mapIndex++;
};

JQVMap.prototype = {
  transX: 0,
  transY: 0,
  scale: 1,
  baseTransX: 0,
  baseTransY: 0,
  baseScale: 1,
  width: 0,
  height: 0,
  countries: {},
  countriesColors: {},
  countriesData: {},
  zoomStep: 1.4,
  zoomMaxStep: 4,
  zoomCurStep: 1
};

JQVMap.xlink = 'http://www.w3.org/1999/xlink';
JQVMap.mapIndex = 1;
JQVMap.maps = {};


text:
import React from 'react';
import PropTypes from 'prop-types';

import {autobind} from '../helpers';

export default class PrUrlInputBox extends React.Component {
  static propTypes = {
    onSubmit: PropTypes.func.isRequired,
    children: PropTypes.node,
  }

  constructor(props, context) {
    super(props, context);
    autobind(this, 'handleSubmitUrlClick', 'handleSubmitUrl', 'handleUrlChange');
    this.state = {
      url: '',
    };
  }

  render() {
    return (
      <form className="github-PrUrlInputBox-Subview" onSubmit={this.handleSubmitUrl}>
        {this.props.children}
        <input
          type="text"
          className="input-text native-key-bindings"
          placeholder="e.g. https://github.com/owner/repo/pull/123"
          value={this.state.url}
          onChange={this.handleUrlChange}
        />
        <div>
          <input
            type="submit"
            value="Submit"
            onClick={this.handleSubmitUrlClick} className="btn btn-primary icon icon-check inline-block-tight"
          />
        </div>
      </form>
    );
  }

  handleSubmitUrlClick(e) {
    e.preventDefault();
    this.handleSubmitUrl();
  }

  handleSubmitUrl() {
    this.props.onSubmit(this.state.url);
  }

  handleUrlChange(e) {
    this.setState({url: e.target.value});
  }
}


text:
define(
"dojo/cldr/nls/bn/gregorian", //begin v1.x content
{
	"months-format-narrow": [
		"জা",
		"ফে",
		"মা",
		"এ",
		"মে",
		"জুন",
		"জু",
		"আ",
		"সে",
		"অ",
		"ন",
		"ডি"
	],
	"quarters-standAlone-narrow": [
		"১",
		"২",
		"৩",
		"৪"
	],
	"field-weekday": "সপ্তাহের দিন",
	"dateFormatItem-yQQQ": "QQQ y",
	"dateFormatItem-yMEd": "E, d/M/y",
	"dateFormatItem-MMMEd": "E d MMM",
	"eraNarrow": [
		"খৃষ্টপূর্ব",
		"খৃষ্টাব্দ"
	],
	"dateFormat-long": "d MMMM, y",
	"months-format-wide": [
		"জানুয়ারী",
		"ফেব্রুয়ারী",
		"মার্চ",
		"এপ্রিল",
		"মে",
		"জুন",
		"জুলাই",
		"আগস্ট",
		"সেপ্টেম্বর",
		"অক্টোবর",
		"নভেম্বর",
		"ডিসেম্বর"
	],
	"dayPeriods-format-wide-pm": "অপরাহ্ণ",
	"dateFormat-full": "EEEE, d MMMM, y",
	"dateFormatItem-Md": "d/M",
	"dateFormatItem-yMd": "d/M/y",
	"field-era": "যুগ",
	"dateFormatItem-yM": "M/yyyy",
	"months-standAlone-wide": [
		"জানুয়ারী",
		"ফেব্রুয়ারী",
		"মার্চ",
		"এপ্রিল",
		"মে",
		"জুন",
		"জুলাই",
		"আগস্ট",
		"সেপ্টেম্বর",
		"অক্টোবর",
		"নভেম্বর",
		"ডিসেম্বর"
	],
	"timeFormat-short": "h:mm a",
	"quarters-format-wide": [
		"প্রথম চতুর্থাংশ",
		"দ্বিতীয় চতুর্থাংশ",
		"তৃতীয় চতুর্থাংশ",
		"চতুর্থ চতুর্থাংশ"
	],
	"timeFormat-long": "h:mm:ss a z",
	"field-year": "বছর",
	"dateFormatItem-yMMM": "MMM y",
	"dateFormatItem-yQ": "Q y",
	"dateFormatItem-yyyyMMMM": "MMMM y",
	"field-hour": "ঘন্টা",
	"dateFormatItem-MMdd": "dd-MM",
	"months-format-abbr": [
		"জানুয়ারী",
		"ফেব্রুয়ারী",
		"মার্চ",
		"এপ্রিল",
		"মে",
		"জুন",
		"জুলাই",
		"আগস্ট",
		"সেপ্টেম্বর",
		"অক্টোবর",
		"নভেম্বর",
		"ডিসেম্বর"
	],
	"dateFormatItem-yyQ": "Q yy",
	"timeFormat-full": "h:mm:ss a zzzz",
	"field-day-relative+0": "আজ",
	"field-day-relative+1": "আগামীকাল",
	"field-day-relative+2": "আগামী পরশু",
	"months-standAlone-abbr": [
		"জানুয়ারী",
		"ফেব্রুয়ারী",
		"মার্চ",
		"এপ্রিল",
		"মে",
		"জুন",
		"জুলাই",
		"আগস্ট",
		"সেপ্টেম্বর",
		"অক্টোবর",
		"নভেম্বর",
		"ডিসেম্বর"
	],
	"quarters-format-abbr": [
		"চতুর্থাংশ ১",
		"চতুর্থাংশ ২",
		"চতুর্থাংশ ৩",
		"চতুর্থাংশ ৪"
	],
	"quarters-standAlone-wide": [
		"প্রথম চতুর্থাংশ",
		"দ্বিতীয় চতুর্থাংশ",
		"তৃতীয় চতুর্থাংশ",
		"চতুর্থ চতুর্থাংশ"
	],
	"dateFormatItem-M": "L",
	"days-standAlone-wide": [
		"রবিবার",
		"সোমবার",
		"মঙ্গলবার",
		"বুধবার",
		"বৃহষ্পতিবার",
		"শুক্রবার",
		"শনিবার"
	],
	"dateFormatItem-MMMMd": "d MMMM",
	"timeFormat-medium": "h:mm:ss a",
	"dateFormatItem-Hm": "HH:mm",
	"quarters-standAlone-abbr": [
		"Q1",
		"Q2",
		"Q3",
		"Q4"
	],
	"eraAbbr": [
		"খৃষ্টপূর্ব",
		"খৃষ্টাব্দ"
	],
	"field-minute": "মিনিট",
	"field-dayperiod": "পূর্বাহ্ণ/অপরাহ্ণ",
	"days-standAlone-abbr": [
		"রবি",
		"সোম",
		"মঙ্গল",
		"বুধ",
		"বৃহস্পতি",
		"শুক্র",
		"শনি"
	],
	"dateFormatItem-d": "d",
	"dateFormatItem-ms": "mm:ss",
	"quarters-format-narrow": [
		"1",
		"2",
		"3",
		"4"
	],
	"field-day-relative+-1": "গতকাল",
	"field-day-relative+-2": "গত পরশু",
	"dateFormatItem-MMMd": "d MMM",
	"dateFormatItem-MEd": "E, d-M",
	"dateFormatItem-yMMMM": "MMMM y",
	"field-day": "দিন",
	"days-format-wide": [
		"রবিবার",
		"সোমবার",
		"মঙ্গলবার",
		"বুধবার",
		"বৃহষ্পতিবার",
		"শুক্রবার",
		"শনিবার"
	],
	"field-zone": "এলাকা",
	"dateFormatItem-yyyyMM": "MM-yyyy",
	"dateFormatItem-y": "y",
	"months-standAlone-narrow": [
		"জা",
		"ফে",
		"মা",
		"এ",
		"মে",
		"জুন",
		"জু",
		"আ",
		"সে",
		"অ",
		"ন",
		"ডি"
	],
	"field-year-relative+-1": "আগের বছর",
	"field-month-relative+-1": "গত মাস",
	"days-format-abbr": [
		"রবি",
		"সোম",
		"মঙ্গল",
		"বুধ",
		"বৃহস্পতি",
		"শুক্র",
		"শনি"
	],
	"dateFormatItem-yMMMd": "d MMM, y",
	"eraNames": [
		"খৃষ্টপূর্ব",
		"খৃষ্টাব্দ"
	],
	"days-format-narrow": [
		"র",
		"সো",
		"ম",
		"বু",
		"বৃ",
		"শু",
		"শ"
	],
	"field-month": "মাস",
	"days-standAlone-narrow": [
		"র",
		"সো",
		"ম",
		"বু",
		"বৃ",
		"শু",
		"শ"
	],
	"dateFormatItem-MMM": "LLL",
	"dayPeriods-format-wide-am": "পূর্বাহ্ণ",
	"dateFormatItem-MMMMEd": "E d MMMM",
	"dateFormat-short": "d/M/yy",
	"field-second": "সেকেন্ড",
	"dateFormatItem-yMMMEd": "E, d MMM, y",
	"field-month-relative+0": "এই মাস",
	"field-month-relative+1": "পরের মাস",
	"dateFormatItem-Ed": "d E",
	"field-week": "সপ্তাহ",
	"dateFormat-medium": "d MMM, y",
	"field-year-relative+0": "এই বছর",
	"field-week-relative+-1": "গত সপ্তাহ",
	"field-year-relative+1": "পরের বছর",
	"field-week-relative+0": "এই সপ্তাহ",
	"field-week-relative+1": "পরবর্তী সপ্তাহ"
}
//end v1.x content
);


text:
/**
 * This module is used to accommodate Swagger 2 data for easier rendering.
 * @module swagger2
 */

const _ = require('lodash');
const wrap = require('word-wrap');
const bundler = require('./bundler');

/**
 * Generates an "operationId" attribute based on path and method names.
 *
 * @private
 * @param  {String} method_name HTTP method name.
 * @param  {String} path_name   Path name.
 * @return {String}
 */
const generateOperationId = (method_name, path_name) => {
  if (path_name === '/') return method_name;

  // clean url path for requests ending with '/'
  let clean_path = path_name;
  if (clean_path.indexOf('/', clean_path.length - 1) !== -1) {
    clean_path = clean_path.substring(0, clean_path.length - 1);
  }

  let segments = clean_path.split('/').slice(1);
  segments = _.transform(segments, (result, segment) => {
    if (segment[0] === '{' && segment[segment.length - 1] === '}') {
      segment = `by-${_.capitalize(segment.substring(1, segment.length - 1))}}`;
    }
    result.push(segment);
  });

  return _.camelCase(`${method_name.toLowerCase()}-${segments.join('-')}`);
};

/**
 * Accommodates Swagger object for easier rendering.
 *
 * @param  {String|Object} swagger File path to Swagger file or **fully bundled and dereferenced** Swagger JS object.
 * @return {Object}                The accommodated Swagger object.
 */
const swagger2 = async swagger => {
  const authorized_methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'COPY', 'HEAD', 'OPTIONS', 'LINK', 'UNLINK', 'PURGE', 'LOCK', 'UNLOCK', 'PROPFIND'];

  if (typeof swagger === 'string') {
    try {
      swagger = await bundler(swagger);
    } catch (e) {
      throw e;
    }
  } else if (typeof swagger !== 'object') {
    throw new Error(`Could not find a valid swagger definition: ${swagger}`);
  }

  swagger.basePath = swagger.basePath || '';

  _.each(swagger.paths, (path, path_name) => {
    path.endpointName = path_name === '/' ? 'root' : path_name.split('/')[1];
    _.each(path, (method, method_name) => {
      if (authorized_methods.indexOf(method_name.toUpperCase()) === -1) return;

      method.operationId = _.camelCase(method.operationId || generateOperationId(method_name, path_name).replace(/\s/g, '-'));
      method.descriptionLines = wrap(method.description || method.summary || '', { width: 60, indent: '' }).split(/\n/);
      _.each(method.parameters, param => {
        param.type = param.type || (param.schema ? param.schema.type : undefined);
      });
    });
  });

  swagger.endpoints = _.uniq(_.map(swagger.paths, 'endpointName'));

  return swagger;
};

module.exports = swagger2;


text:
/*
* Kendo UI Beta v2013.2.716 (http://kendoui.com)
* Copyright 2013 Telerik AD. All rights reserved.
*
* Kendo UI Beta license terms available at
* http://www.kendoui.com/purchase/license-agreement/kendo-ui-beta.aspx
*/

("function"==typeof define&&define.amd?define:function(n,y){return y()})(["../kendo.core.min"],function(){!function(){kendo.cultures["bn-BD"]={name:"bn-BD",numberFormat:{pattern:["-n"],decimals:2,",":",",".":".",groupSize:[3,2],percent:{pattern:["-%n","%n"],decimals:2,",":",",".":".",groupSize:[3,2],symbol:"%"},currency:{pattern:["$ -n","$ n"],decimals:2,",":",",".":".",groupSize:[3,2],symbol:"৳"}},calendars:{standard:{days:{names:["রবিবার","সোমবার","মঙ্গলবার","বুধবার","বৃহস্পতিবার","শুক্রবার","শনিবার"],namesAbbr:["রবি.","সোম.","মঙ্গল.","বুধ.","বৃহস্পতি.","শুক্র.","শনি."],namesShort:["র","স","ম","ব","ব","শ","শ"]},months:{names:["জানুয়ারী","ফেব্রুয়ারী","মার্চ","এপ্রিল","মে","জুন","জুলাই","আগস্ট","সেপ্টেম্বর","অক্টোবর","নভেম্বর","ডিসেম্বর",""],namesAbbr:["জানু.","ফেব্রু.","মার্চ","এপ্রিল","মে","জুন","জুলাই","আগ.","সেপ্টে.","অক্টো.","নভে.","ডিসে.",""]},AM:["পুর্বাহ্ন","পুর্বাহ্ন","পুর্বাহ্ন"],PM:["অপরাহ্ন","অপরাহ্ন","অপরাহ্ন"],patterns:{d:"dd-MM-yy",D:"dd MMMM yyyy",F:"dd MMMM yyyy HH.mm.ss",g:"dd-MM-yy HH.mm",G:"dd-MM-yy HH.mm.ss",m:"dd MMMM",M:"dd MMMM",s:"yyyy'-'MM'-'dd'T'HH':'mm':'ss",t:"HH.mm",T:"HH.mm.ss",u:"yyyy'-'MM'-'dd HH':'mm':'ss'Z'",y:"MMMM, yyyy",Y:"MMMM, yyyy"},"/":"-",":":".",firstDay:1}}}}(this)});


text:
const Topic  = require('../../models/forums/topic');
const Forum = require('../../models/forums/forum');
const Post = require('../../models/forums/post');
const User = require('../../models/user');

exports.getPosts = function(req, res) {
  if (typeof req.body.access_token === 'undefined') {
    return res.status(400).send('Authentication is required');
  }

  User.findOne({ token: req.body.access_token }, function(err, user) {
    if (err || !user) {
      return res.status(400).send('Authentication failed');
    } else {
      Post.find({}, null, {sort: {createdDate: -1}}, function(err, posts) {
        if (err || !posts.length) {
          return res.json({
            type: false,
            data: "Error occured: " + err
          });
        } else {
          return res.json(posts);
        }
      });
    }
  });
};

exports.getPostsByTopicId = function(req, res) {
  if (typeof req.body.access_token === 'undefined') {
    return res.status(400).send('Authentication is required');
  }

  User.findOne({ token: req.body.access_token }, function(err, user) {
    if (err || !user) {
      return res.status(400).send('Authentication failed');
    } else {
      Post.find({topicId: req.body.id}, null, {sort: {createdDate: 1}}, function(err, posts) {
        if (err || !posts.length) {
          return res.json({
            type: false,
            data: "Error occured: " + err
          });
        } else {
          return res.json({type: true, data: posts});
        }
      });
    }
  });
};

exports.getPostById = function(req, res) {
  if (typeof req.body.access_token === 'undefined') {
    return res.status(400).send('Authentication is required');
  }

  User.findOne({ token: req.body.access_token }, function(err, user) {
    if (err || !user) {
      return res.status(400).send('Authentication failed');
    } else {
      Post.findOne({_id: req.body.id}, function(err, post) {
        if (err || !post) {
          return res.json({
            type: false,
            data: "Error occured: " + err
          });
        } else {
          return res.json({type: true, data: post});
        }
      });
    }
  });
};

exports.likePostById = function(req, res) {
  if (typeof req.body.access_token === 'undefined') {
    return res.status(400).send('Authentication is required');
  }

  User.findOne({ token: req.body.access_token }, function(err, user) {
    if (err || !user) {
      return res.status(400).send('Authentication failed');
    } else {
      Post.findOne({_id: req.body.id}, function(err, post) {
        if (err || !post) {
          return res.json({
            type: false,
            data: "Error occured: " + err
          });
        } else {
          console.log(post);
          if (post.likeUsersId.indexOf(user._id) == -1) {
            console.log(post);
            post.likeUsersId.push(user._id);
            post.save();
          }
          return res.json({type: true});
        }
      });
    }
  });
};

exports.removeLikePostById = function(req, res) {
  if (typeof req.body.access_token === 'undefined') {
    return res.status(400).send('Authentication is required');
  }

  User.findOne({ token: req.body.access_token }, function(err, user) {
    if (err || !user) {
      return res.status(400).send('Authentication failed');
    } else {
      Post.findOne({_id: req.body.id}, function(err, post) {
        if (err || !post) {
          return res.json({
            type: false,
            data: "Error occured: " + err
          });
        } else {
          var idx = post.likeUsersId.indexOf(user._id);
          if (idx > -1) {
            post.likeUsersId.splice(idx);
            post.save();
            return res.json({type: true});
          }
        }
      });
    }
  });
};

exports.dislikePostById = function(req, res) {
  if (typeof req.body.access_token === 'undefined') {
    return res.status(400).send('Authentication is required');
  }

  User.findOne({ token: req.body.access_token }, function(err, user) {
    if (err || !user) {
      return res.status(400).send('Authentication failed');
    } else {
      Post.findOne({_id: req.body.id}, function(err, post) {
        if (err || !post) {
          return res.json({
            type: false,
            data: "Error occured: " + err
          });
        } else {
          if (post.unlikeUsersId.indexOf(user._id) == -1) {
            post.unlikeUsersId.push(user._id);
            post.save();
            return res.json({type: true});
          } else {
            return res.json({
              type: false,
              data: "Error1 occured: " + err
            });
          }
        }
      });
    }
  });
};

exports.removeDisLikePostById = function(req, res) {
  if (typeof req.body.access_token === 'undefined') {
    return res.status(400).send('Authentication is required');
  }

  User.findOne({ token: req.body.access_token }, function(err, user) {
    if (err || !user) {
      return res.status(400).send('Authentication failed');
    } else {
      Post.findOne({_id: req.body.id}, function(err, post) {
        if (err || !post) {
          return res.json({
            type: false,
            data: "Error occured: " + err
          });
        } else {
          var idx = post.unlikeUsersId.indexOf(user._id);
          if (idx > -1) {
            post.unlikeUsersId.splice(idx);
            post.save();
            return res.json({type: true});
          }
        }
      });
    }
  });
};

exports.addPost = function(req, res) {
  if (typeof req.body.access_token === 'undefined') {
    return res.status(400).send('Authentication is required');
  }

  User.findOne({ token: req.body.access_token }, function(err, user) {
    if (err || !user) {
      return res.status(400).send('Authentication failed');
    } else {
      var item = req.body.data;
      item.createdDate = new Date();
      item.createdUserId = user._id;
      var newPost = new Post(item);
      newPost.save(function (err, post) {
        if (err || !post) {
          return res.status(500).send(err);
        } else {
          if (post.topicId) {
            Topic.findOne({_id: post.topicId}, function(err, topic) {
              if (err || !topic) {
                res.json({type: false, msg: 'err: ' + err});
              } else {
                topic.replies++;
                topic.lastreplied = new Date();
                topic.save();

                Forum.findOne({_id: topic.forumId}, function (err, parentForum) {
                  if (err || !parentForum) {
                    return res.status(500).send('cannot find parent forum');
                  } else {
                    parentForum.posts++;
                    parentForum.lastreplied = new Date();
                    parentForum.save();
                    return res.json({type: true, msg: 'successfully added'});
                  }
                })
              }
            });
          } else {
            return res.json({ type: true, msg: 'successfully added'});
          }
        }
      })
    }
  });
};

exports.deletePost = function(req, res) {
  if (typeof req.body.access_token === 'undefined') {
    return res.status(400).send('Authentication is required');
  }

  User.findOne({ token: req.body.access_token }, function(err, user) {
    if (err || !user) {
      return res.status(400).send('Authentication failed');
    } else {
      Post.findOneAndRemove({_id: req.body.id}, function (err, post) {
        if (err || !post) {
          return res.status(500).send(err);
        } else {
          if (post.topicId) {
            Topic.findOne({_id: post.topicId}, function(err, topic) {
              if (err || topic) {
                return res.json({type: false, msg: 'err: ' + err});
              } else {
                topic.replies--;
                topic.save();

                Forum.findOne({_id: topic.forumId}, function (err, parentForum) {
                  if (err || !parentForum) {
                    return res.status(500).send('cannot find parent forum');
                  } else {
                    parentForum.posts--;
                    parentForum.save();
                    return res.json({type: true, msg: 'successfully deleted'});
                  }
                })
              }
            });
          } else {
            return res.json({ type: false, msg: 'topic id invalid'});
          }
        }
      })
    }
  });
};


text:
import React from 'react';

export default function MyLocation(props) {
	const { width, height, color, backgroundColor, ...others } = props;
	return (
		<div {...others} style={{ height: `${height}px`, width: `${width}px` }}>
			<svg
				xmlns="http://www.w3.org/2000/svg"
				width={width}
				height={height}
				viewBox="0 0 24 24"
			>
				<path
					d="M12 8c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm8.94 3c-.46-4.17-3.77-7.48-7.94-7.94V1h-2v2.06C6.83 3.52 3.52 6.83 3.06 11H1v2h2.06c.46 4.17 3.77 7.48 7.94 7.94V23h2v-2.06c4.17-.46 7.48-3.77 7.94-7.94H23v-2h-2.06zM12 19c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7z"
					fill={color}
				/>
				<path d="M0 0h24v24H0z" fill="none" />
			</svg>
		</div>
	);
}

MyLocation.defaultProps = {
	color: 'black',
	width: '24',
	height: '24'
};


text:
import React, { Component } from "react"
import PropTypes from "prop-types"
import styled from "styled-components"
import { Link } from "gatsby"

import Img from "gatsby-image"
import AddToCartBtn from "./AddToCartBtn"

const GridItem = styled.div`
  justify-items: center;
  justify-content: space-evenly;
  text-align: center;
  border: 3px solid #f6f7f8;
  border-radius: 5px;
  padding: 5px;
`

const ItemLink = styled(Link)`
  text-decoration: none;
  color: black;
`

const ItemTitle = styled.p`
  line-height: 1.45em;
`

const ItemPrice = styled.p`
  color: #ff5100;
`

export default class ProductItem extends Component {
  render() {
    const { node } = this.props
    return (
      <GridItem>
        <ItemLink to={`${node.uid}`}>
          <Img fluid={node.data.image.localFile.childImageSharp.fluid} />
          <ItemTitle>{node.data.title.text}</ItemTitle>
        </ItemLink>
        <ItemPrice>${node.data.price}</ItemPrice>
        <form
          action="https://upsafetysolutions.foxycart.com/cart"
          method="post"
          accept-charset="utf-8"
        >
          <input
            type="hidden"
            name={`${node.data.name_hmac.text}`}
            value={`${node.data.name.text}`}
          />
          <input
            type="hidden"
            name={`${node.data.price_hmac.text}`}
            value={`${node.data.price}`}
          />
          <input
            type="hidden"
            name={`${node.data.item_code_hmac.text}`}
            value={`${node.data.item_code_sku.text}`}
          />
          <input
            type="hidden"
            name={`${node.data.cart_image_hmac.text}`}
            value={`${node.data.cart_image.url}`}
          />
          <input
            type="hidden"
            name={`${node.data.weight_hmac.text}`}
            value={`${node.data.weight}`}
          />
          <AddToCartBtn
            type="submit"
            value="Add To Cart"
            className="submit"
            style={{justifySelf:`end`,}}
          >
            ADD TO CART
          </AddToCartBtn>

        </form>
      </GridItem>
    )
  }
}

ProductItem.propTypes = {
  node: PropTypes.object.isRequired,
  categories: PropTypes.array.isRequired,
}


text:
require([
    'dijit/_WidgetBase',

    'dojo/dom-construct',

    'app/ListPicker'
], function (
    _WidgetBase,

    domConstruct,

    ListPicker
) {
    describe('ListPicker Widget', function () {
        var testWidget;
        beforeEach(function () {
            testWidget = new ListPicker({
                availableListArray: [
                    {code: 'testcode', name: 'testvalue'},
                    {code: 'testcode2', name: 'testvalue2'}
                ],
                listName: 'Species'
            }, domConstruct.create('div', null, document.body));
        });

        afterEach(function () {
            testWidget.destroy();
            testWidget = null;
        });

        it('Should create a valid instance of _widget', function () {
            expect(testWidget).toEqual(jasmine.any(ListPicker));
        });
    });
});


text:
import {
  sortTimeCreator,
  sortTimeSuccessCreator,
} from "../../store/reducers/sortReducers/sortTimeReducer";

const weekDays = ["Sun.", "Mon.", "Tue.", "Wed.", "Thu.", "Fri.", "Sat."];
const months = [
  "Jan.",
  "Feb.",
  "Mar.",
  "Apr.",
  "May",
  "Jun.",
  "Jul.",
  "Aug.",
  "Sep.",
  "Oct.",
  "Nov.",
  "Dec.",
];

export function sortMain(time, xArr, typeForCheck) {
  return async (dispatch) => {
    dispatch(sortTimeCreator());

    const WIDTH = 700;
    const X_PADDING = 80;
    const VIEW_WIDTH = WIDTH - X_PADDING * 2;
    const xRatio = Math.round(VIEW_WIDTH / (xArr.length - 2));

    const xAllStep = [];
    const timeForX = [];
    const allTimeForX = [];
    let xIterStep = 4;

    const allYear = [];
    const allMonth = [];
    const allHours = [];
    const sortedYear = [];
    const sortedHours = [];
    const outputHours = [];
    const sortedMonth = [];
    const outputYear = [];
    const outputMonth = [];
    const outputDate = [];

    const outputLines = []; // xDoneStep
    const outputX = []; // xDoneTextStep
    const outputTime = []; // time

    for (let i = 0; i < time.length; i++) {
      typeForCheck == "1d"
        ? timeForX.push(time[i].getHours())
        : typeForCheck == "7d"
        ? timeForX.push(time[i].getDay())
        : typeForCheck == "1m" || typeForCheck == "3m"
        ? allMonth.push(time[i].getMonth()) &&
          timeForX.push(time[i].getDate()) &&
          allHours.push(time[i].getHours())
        : typeForCheck == "1y"
        ? allMonth.push(time[i].getMonth()) &&
          timeForX.push(time[i].getDate()) &&
          allYear.push(time[i].getFullYear())
        : null;
    }

    for (let i = 0; i < xArr.length - 1; i++) {
      if (timeForX[i] !== timeForX[i + 1]) {
        typeForCheck !== "3m" && typeForCheck !== "1y"
          ? xArr[i + 1]
            ? xAllStep.push(xArr[i + 1] * xRatio + X_PADDING)
            : xAllStep.push(xArr[i] * xRatio + X_PADDING)
          : null;

        typeForCheck == "1d"
          ? allTimeForX.push(timeForX[i + 1])
          : typeForCheck == "7d"
          ? allTimeForX.push(timeForX[i])
          : typeForCheck == "1m"
          ? allTimeForX.push(timeForX[i + 1]) &&
            sortedMonth.push(allMonth[i + 1]) &&
            sortedHours.push(allHours[i + 1])
          : // (allMonth[i + 1] ? sortedMonth.push(allMonth[i + 1]) : null)
            null;

        typeForCheck == "3m" && allMonth[i] !== allMonth[i + 1]
          ? allTimeForX.push(timeForX[i + 1]) &&
            xAllStep.push(xArr[i + 1] * xRatio + X_PADDING) &&
            sortedMonth.push(allMonth[i + 1]) &&
            sortedHours.push(allHours[i + 1])
          : null;

        typeForCheck == "1y" && allYear[i] !== allYear[i + 1]
          ? allTimeForX.push(timeForX[i + 1]) &&
            xAllStep.push(xArr[i + 1] * xRatio + X_PADDING) &&
            sortedMonth.push(allMonth[i + 1]) &&
            sortedYear.push(allYear[i + 1])
          : null;
      }
    }

    if (allTimeForX.length == 6 && typeForCheck == "7d") {
      allTimeForX[allTimeForX.length - 1] < 6
        ? allTimeForX.push(allTimeForX[allTimeForX.length - 1] + 1)
        : allTimeForX[allTimeForX.length - 1] == 6
        ? allTimeForX.push(0)
        : null;
      xAllStep.push(xAllStep[0] - X_PADDING);
    }

    typeForCheck == "7d" || typeForCheck == "3m" || typeForCheck == "1y"
      ? (xIterStep = 1)
      : typeForCheck == "1m"
      ? (xIterStep = 5)
      : null;

    for (let i = 0; i < allTimeForX.length; i += xIterStep) {
      outputX.push(xAllStep[i]);
      outputLines.push(xAllStep[i]);

      typeForCheck == "1d"
        ? outputTime.push(allTimeForX[i])
        : typeForCheck == "7d"
        ? outputTime.push(weekDays[allTimeForX[i]])
        : typeForCheck == "1m" || typeForCheck == "3m"
        ? outputMonth.push(sortedMonth[i]) &&
          outputDate.push(allTimeForX[i]) &&
          outputHours.push(sortedHours[i])
        : typeForCheck == "1y"
        ? outputMonth.push(sortedMonth[i]) &&
          outputDate.push(allTimeForX[i]) &&
          outputYear.push(sortedYear[i])
        : null;
    }

    if (typeForCheck == "7d") {
      if (X_PADDING > xAllStep[0] - 55) {
        const excess = outputX.shift();
        outputX.unshift(xAllStep[0] + VIEW_WIDTH + X_PADDING / 2);
      }

      if (X_PADDING > xAllStep[xAllStep.length - 1] - 55) {
        const excess = outputX.pop();
        outputX.push(
          xAllStep[xAllStep.length - 1] + VIEW_WIDTH + X_PADDING / 2
        );
      }
    }

    if (typeForCheck == "1m" || typeForCheck == "3m") {
      for (let i = 0; i < outputDate.length; i++) {
        outputTime.push(
          outputDate[i] +
            " " +
            months[outputMonth[i]] +
            " " +
            outputHours[i] +
            "h."
        );
      }
    } else if (typeForCheck == "1y") {
      for (let i = 0; i < outputDate.length; i++) {
        outputTime.push(
          outputDate[i] + " " + months[outputMonth[i]] + " " + outputYear[i]
        );
      }
    }

    dispatch(sortTimeSuccessCreator({ outputTime, outputX, outputLines }));
  };
}


text:
/* global angular, gscDatacat */

'use strict';
angular.module('gscDatacat.services')
    .factory('dataSvc', [
        '$rootScope',
        '$state',
        'authSvc',
        '$http',
        '$q',
        function($rootScope,
            $state,
            authSvc,
            $http,
            $q) {

            var self = this;

            self.loadLayers = function() {
                var dfd = $q.defer();
                gsc.layer.list(null, null, null, authSvc.authUsr.organizationId)
                    .then(function(res) {
                        if (res.status !== 'error' &&
                            gsc.util.isArrayWithContent(res.layers)) {
                            dfd.resolve(res.layers);
                            $rootScope.console.log('Loaded layers');
                        } else if (res.status === 'error') {
                            dfd.reject('An error occurred while loading layers');
                            dfd.reject(res.description);
                            $rootScope.console.log(res);
                        } else {
                            dfd.reject('An error occurred while loading layers');
                            $rootScope.console.log(res);
                        }
                    }, function(err) {
                        dfd.resolve(err.statusText);
                    });
                return dfd.promise;
            };

            self.loadLayer = function(layerId) {
                var dfd = $q.defer();
                gsc.layer.list(null, layerId)
                    .then(function(res) {
                        if (res.status !== 'error' &&
                            gsc.util.isArrayWithContent(res.layers)) {
                            $rootScope.console.log(res.layers[0]);
                            dfd.resolve(res.layers[0]);
                        } else if (res.status === 'error') {
                            dfd.reject(res.description);
                        } else {
                            dfd.reject(
                                'No layer data returned for specified id');
                        }
                    }, function(err) {
                        dfd.resolve(err.statusText);
                    });
                return dfd.promise;
            };

            self.loadDataSources = function() {
                var dfd = $q.defer();
                gsc.datasource.list(null, authSvc.authUsr.organizationId, null, true)
                    .then(function(res) {
                        $rootScope.console.log('Loading data sources');
                        if (gsc.util.isArrayWithContent(res.datasources)) {
                            dfd.resolve(res.datasources);
                        } else {
                            $rootScope.console.error('No data sources');
                            dfd.reject('No data sources');
                        }
                    }, function(err) {
                        dfd.reject(err.statusText);
                    });
                return dfd.promise;
            };

            self.loadDataOrigin = function(dataSourceId) {
                var dfd = $q.defer();
                gsc.datasource.listDataOrigin(dataSourceId)
                    .then(function(res) {
                        $rootScope.console.log('Loading data origin');
                        if (res.status !== 'error' &&
                            res.dataorigin !== undefined &&
                            jQuery.isArray(res.dataorigin)) {
                            dfd.resolve(res.dataorigin);
                        } else if (res.status === 'error') {
                            dfd.reject(res.description);
                        } else {
                            dfd.reject('Error during loading of data origin');
                        }
                    }, function(err) {
                        dfd.reject(err.statusText);
                    });

                return dfd.promise;
            };

            self.loadDataSource = function(dataSourceId) {
                var dfd = $q.defer();
                gsc.datasource.list(dataSourceId, null, null, true)
                    .then(function(res) {
                        if (res.datasources.length > 0) {
                            dfd.resolve(res.datasources[0]);
                        } else {
                            dfd.reject('No data sources');
                        }
                    }, function(err) {
                        dfd.reject(err.statusText);
                    });
                return dfd.promise;
            };

            self.loadDataSet = function(dataSetId) {
                var dfd = $q.defer();
                gsc.dataset.list(undefined, +dataSetId, undefined, undefined)
                    .then(function(res) {
                        if (res.status !== 'error' && res.dataset.length > 0) {
                            dfd.resolve(res.dataset[0]);
                        } else if (res.status === 'error') {
                            dfd.reject(res.description);
                        } else {
                            dfd.reject('No data sources');
                        }
                    }, function(err) {
                        dfd.reject(err.statusText);
                    });
                return dfd.promise;
            };

            self.listDataSetColumns = function(dataSetId) {
                var dfd = $q.defer();
                gsc.dataset.listCols(+dataSetId).
                    then(function(res) {
                        console.log(res);
                        if (res.status !== 'error') {
                            dfd.resolve(res.columns);
                        } else {
                            dfd.reject(res.description);
                        }
                    }, function(err) {
                        dfd.reject(err.statusText);
                    });
                return dfd.promise;
            };

            self.loadDataSets = function(dataSourceId) {
                var dfd = $q.defer();
                gsc.dataset.list(dataSourceId,
                    undefined,
                    undefined,
                    authSvc.authUsr.organizationId)
                    .then(function(res) {
                        if (res.dataset.length > 0) {
                            dfd.resolve(res.dataset);
                        } else {
                            dfd.reject('No data sources');
                        }
                    }, function(err) {
                        dfd.reject(err.statusText);
                    });
                return dfd.promise;
            };

            self.loadOrganizations = function() {
                var dfd = $q.defer();

                gsc.organization.list().then(function(res) {
                    $rootScope.console.log('Loading organizations');
                    if (res.status !== 'error' && gsc.util.isArrayWithContent(
                        res.organizations)) {
                        dfd.resolve(res.organizations);
                    } else if (res.status === 'error') {
                        dfd.reject(res.description);
                    } else {
                        dfd.reject('No organizations available');
                    }
                }, function(err) {
                    dfd.reject(err.statusText);
                });

                return dfd.promise;
            };

            self.loadUsers = function() {
                var dfd = $q.defer();

                gsc.user.list(+authSvc.authUsr.organizationId)
                    .then(function(res) {

                        if (typeof res.users === 'string') {
                            res.users = JSON.parse(res.users);
                        }

                        $rootScope.console.log('Loaded users for organization');
                        if (gsc.util.isArrayWithContent(
                            res.users)) {
                            dfd.resolve(res.users);
                        } else if (res.status === 'error') {
                            dfd.reject(res.description);
                        } else {
                            dfd.reject('No users returned');
                            $rootScope.console.log(res);
                        }
                    }, function(err) {
                        dfd.reject(err.statusText);
                    });

                return dfd.promise;
            };

            self.loadUser = function(userId) {
                var dfd = $q.defer();

                gsc.user.list(+authSvc.authUsr.organizationId)
                    .then(function(userListResponse) {
                        $rootScope.console.info('Loaded user');
                        if (gsc.util.isArrayWithContent(
                            userListResponse.users)) {
                            dfd.resolve(userListResponse.users);
                        } else if (userListResponse.status === 'error') {
                            $rootScope.console.error('An error occurred loading users');
                            dfd.reject(userListResponse.description);
                            $rootScope.console.debug(userListResponse);
                        } else {
                            $rootScope.console.info('No users returned');
                            dfd.reject('No users returned');
                        }
                    }, function(err) {
                        $rootScope.console.error('An error occurred loading users');
                        $rootScope.console.debug(err);
                        dfd.reject(err.statusText);
                    });

                return dfd.promise;
            };

            self.loadRoles = function() {
                var dfd = $q.defer();
                gsc.role.listrole(authSvc.authUsr.organizationId, null, true)
                    .then(function(res) {
                        if (res.status !== 'error' && gsc.util.isArrayWithContent(res.roles)) {
                            $rootScope.console.info('Loaded roles');
                            dfd.resolve(res.roles);
                        } else {
                            $rootScope.console.error('An error occurred loading roles');
                            dfd.reject(res.description);
                        }
                    }, function(err) {
                        $rootScope.console.error('An error occurred loading roles');
                        $rootScope.console.debug(err);
                        dfd.reject(err.statusText);
                    });
                return dfd.promise;
            };

            self.loadPermissions = function(roleId) {
                var dfd = $q.defer();
                gsc.permission.list(roleId)
                    .then(function(res) {
                        if (res.description === undefined &&
                            gsc.util.isArrayWithContent(res.functions)) {
                            $rootScope.console.info('Loaded permissions');
                            dfd.resolve(res.functions);
                        } else if (res.description !== undefined &&
                            res.description === 'No results found.') {
                            $rootScope.console.info('No permissions found for role');
                            dfd.resolve([]);
                        } else {
                            $rootScope.console.error('An error occurred loading permissions');
                            $rootScope.console.debug(res);
                            dfd.reject(res.description);
                        }
                    }, function(err) {
                        $rootScope.console.error('An error occurred loading permissions');
                        $rootScope.console.debug(err);
                        dfd.reject(err.statusText);
                    });
                return dfd.promise;
            };

            self.loadGroupLayers = function() {
                var dfd = $q.defer();
                gsc.grouplayer.list(authSvc.authUsr.organizationId)
                    .then(function(res) {
                        if (res.status !== 'error' &&
                            gsc.util.isArrayWithContent(res.grouplayers)) {
                            $rootScope.console.log('Loaded group layers');
                            dfd.resolve(res.grouplayers);
                        } else {
                            $rootScope.console.log('An error occurred loading group layers');
                            $rootScope.console.log(res);
                            dfd.reject(res.description);
                        }
                    }, function(err) {
                        $rootScope.console.log('An error occurred loading group layers');
                        dfd.reject(err.statusText);
                    });

                return dfd.promise;
            };

            self.loadGroupLayer = function(groupLayerId) {
                var dfd = $q.defer();
                gsc.grouplayer.list(null, null, groupLayerId)
                    .then(function(res) {
                        if (res.status !== 'error' &&
                            gsc.util.isArrayWithContent(res.grouplayers)) {
                            $rootScope.console.log('Loaded group layer');
                            dfd.resolve(res.grouplayers[0]);
                        } else {
                            $rootScope.console.log('An error occurred loading group layer');
                            $rootScope.console.log(res);
                            dfd.reject(res.description);
                        }
                    }, function(err) {
                        $rootScope.console.log('An error occurred loading group layer');
                        dfd.reject(err.statusText);
                    });

                return dfd.promise;
            };

            self.loadFunctions = function() {
                var dfd = $q.defer();
                gsc.function.list(authSvc.authUsr.organizationId)
                    .then(function(res) {
                        if (res.status !== 'error' &&
                            gsc.util.isArrayWithContent(res.functions)) {
                            $rootScope.console.log('Loaded functions');
                            dfd.resolve(res.functions);
                        } else {
                            $rootScope.console.log('An error occurred loading functions');
                            dfd.reject(res.description);
                            $rootScope.console.log(res);
                        }
                    }, function(err) {
                        $rootScope.console.log('An error occurred loading functions');
                        dfd.reject(err.statusText);
                    });
                return dfd.promise;
            };

            self.loadApplications = function() {
                var dfd = $q.defer();

                gsc.application.list(authSvc.authUsr.organizationId, undefined, undefined)
                    .then(function(res) {
                        if (res.status !== 'error' && gsc.util.isArrayWithContent(
                            res.applications)) {
                            $rootScope.console.log('Loaded applications');
                            dfd.resolve(res.applications);
                        } else {
                            $rootScope.console.log(
                                'An error occurred loading applications');
                            $rootScope.console.log(res.description);
                            $rootScope.console.log(res);
                            dfd.reject(res.description);
                        }
                    }, function(err) {
                        $rootScope.console.log(
                            'An error occurred loading applications');
                        $rootScope.console.log(err);
                        dfd.reject(err.statusText);
                    });

                return dfd.promise;
            };

            self.loadApplication = function(applicationId) {
                var dfd = $q.defer();

                gsc.application.list(null, null, applicationId)
                    .then(function(res) {
                        if (res.status !== 'error' && gsc.util.isArrayWithContent(
                            res.applications)) {
                            $rootScope.console.log('Loaded application');
                            dfd.resolve(res.applications[0]);
                        } else {
                            $rootScope.console.log(
                                'An error occurred loading application');
                            $rootScope.console.log(res.description);
                            $rootScope.console.log(res);
                            dfd.reject(res.description);
                        }
                    }, function(err) {
                        $rootScope.console.log(
                            'An error occurred loading applications');
                        $rootScope.console.log(err);
                        dfd.reject(err.statusText);
                    });

                return dfd.promise;
            };

            return self;

        }]);


text:
import { connect } from 'react-redux'
import { withRouter } from 'react-router-dom'
import { push } from 'connected-react-router'
import Submit from './Submit'

import {
  closeSubmitAction,
  onInputNameAction,
  onInputUrlAction,
  onInputDescAction,
  onImgReadAction,
  onImgZoomAction,
  onImgMoveControlAction,
  onImgMoveAction,
  onImgDoneAction,
  onImgCancelAction,
  submitAction,
  switchToRatingAction,
  onInputSntValueAction,
} from './Submit.reducer'

const mapStateToProps = state =>
  Object.assign(state.submit, { dapps: state.dapps.dapps })
const mapDispatchToProps = dispatch => ({
  onClickClose: () => dispatch(closeSubmitAction()),
  onInputName: name => dispatch(onInputNameAction(name)),
  onInputDesc: name => dispatch(onInputDescAction(name)),
  onInputUrl: name => dispatch(onInputUrlAction(name)),
  onImgRead: imgBase64 => dispatch(onImgReadAction(imgBase64)),
  onImgZoom: zoom => dispatch(onImgZoomAction(zoom)),
  onImgMoveControl: move => dispatch(onImgMoveControlAction(move)),
  onImgMove: (x, y) => dispatch(onImgMoveAction(x, y)),
  onImgCancel: () => dispatch(onImgCancelAction()),
  onImgDone: imgBase64 => dispatch(onImgDoneAction(imgBase64)),
  onSubmit: (dapp, sntValue) => dispatch(submitAction(dapp, sntValue)),
  onClickTerms: () => dispatch(push('/terms')),
  switchToRating: () => dispatch(switchToRatingAction()),
  onInputSntValue: sntValue => dispatch(onInputSntValueAction(sntValue)),
})

export default withRouter(
  connect(
    mapStateToProps,
    mapDispatchToProps,
  )(Submit),
)


text:
THREE.VTKLoader = function ( manager ) {

	THREE.Loader.call( this, manager );

};

THREE.VTKLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), {

	constructor: THREE.VTKLoader,

	load: function ( url, onLoad, onProgress, onError ) {

		var scope = this;

		var loader = new THREE.FileLoader( scope.manager );
		loader.setPath( scope.path );
		loader.setResponseType( 'arraybuffer' );
		loader.setRequestHeader( scope.requestHeader );
		loader.setWithCredentials( scope.withCredentials );
		loader.load( url, function ( text ) {

			try {

				onLoad( scope.parse( text ) );

			} catch ( e ) {

				if ( onError ) {

					onError( e );

				} else {

					console.error( e );

				}

				scope.manager.itemError( url );

			}

		}, onProgress, onError );

	},

	parse: function ( data ) {

		function parseASCII( data ) {

			// connectivity of the triangles
			var indices = [];

			// triangles vertices
			var positions = [];

			// red, green, blue colors in the range 0 to 1
			var colors = [];

			// normal vector, one per vertex
			var normals = [];

			var result;

			// pattern for detecting the end of a number sequence
			var patWord = /^[^\d.\s-]+/;

			// pattern for reading vertices, 3 floats or integers
			var pat3Floats = /(\-?\d+\.?[\d\-\+e]*)\s+(\-?\d+\.?[\d\-\+e]*)\s+(\-?\d+\.?[\d\-\+e]*)/g;

			// pattern for connectivity, an integer followed by any number of ints
			// the first integer is the number of polygon nodes
			var patConnectivity = /^(\d+)\s+([\s\d]*)/;

			// indicates start of vertex data section
			var patPOINTS = /^POINTS /;

			// indicates start of polygon connectivity section
			var patPOLYGONS = /^POLYGONS /;

			// indicates start of triangle strips section
			var patTRIANGLE_STRIPS = /^TRIANGLE_STRIPS /;

			// POINT_DATA number_of_values
			var patPOINT_DATA = /^POINT_DATA[ ]+(\d+)/;

			// CELL_DATA number_of_polys
			var patCELL_DATA = /^CELL_DATA[ ]+(\d+)/;

			// Start of color section
			var patCOLOR_SCALARS = /^COLOR_SCALARS[ ]+(\w+)[ ]+3/;

			// NORMALS Normals float
			var patNORMALS = /^NORMALS[ ]+(\w+)[ ]+(\w+)/;

			var inPointsSection = false;
			var inPolygonsSection = false;
			var inTriangleStripSection = false;
			var inPointDataSection = false;
			var inCellDataSection = false;
			var inColorSection = false;
			var inNormalsSection = false;

			var lines = data.split( '\n' );

			for ( var i in lines ) {

				var line = lines[ i ].trim();

				if ( line.indexOf( 'DATASET' ) === 0 ) {

					var dataset = line.split( ' ' )[ 1 ];

					if ( dataset !== 'POLYDATA' ) throw new Error( 'Unsupported DATASET type: ' + dataset );

				} else if ( inPointsSection ) {

					// get the vertices
					while ( ( result = pat3Floats.exec( line ) ) !== null ) {

						if ( patWord.exec( line ) !== null ) break;

						var x = parseFloat( result[ 1 ] );
						var y = parseFloat( result[ 2 ] );
						var z = parseFloat( result[ 3 ] );
						positions.push( x, y, z );

					}

				} else if ( inPolygonsSection ) {

					if ( ( result = patConnectivity.exec( line ) ) !== null ) {

						// numVertices i0 i1 i2 ...
						var numVertices = parseInt( result[ 1 ] );
						var inds = result[ 2 ].split( /\s+/ );

						if ( numVertices >= 3 ) {

							var i0 = parseInt( inds[ 0 ] );
							var i1, i2;
							var k = 1;
							// split the polygon in numVertices - 2 triangles
							for ( var j = 0; j < numVertices - 2; ++ j ) {

								i1 = parseInt( inds[ k ] );
								i2 = parseInt( inds[ k + 1 ] );
								indices.push( i0, i1, i2 );
								k ++;

							}

						}

					}

				} else if ( inTriangleStripSection ) {

					if ( ( result = patConnectivity.exec( line ) ) !== null ) {

						// numVertices i0 i1 i2 ...
						var numVertices = parseInt( result[ 1 ] );
						var inds = result[ 2 ].split( /\s+/ );

						if ( numVertices >= 3 ) {

							var i0, i1, i2;
							// split the polygon in numVertices - 2 triangles
							for ( var j = 0; j < numVertices - 2; j ++ ) {

								if ( j % 2 === 1 ) {

									i0 = parseInt( inds[ j ] );
									i1 = parseInt( inds[ j + 2 ] );
									i2 = parseInt( inds[ j + 1 ] );
									indices.push( i0, i1, i2 );

								} else {

									i0 = parseInt( inds[ j ] );
									i1 = parseInt( inds[ j + 1 ] );
									i2 = parseInt( inds[ j + 2 ] );
									indices.push( i0, i1, i2 );

								}

							}

						}

					}

				} else if ( inPointDataSection || inCellDataSection ) {

					if ( inColorSection ) {

						// Get the colors

						while ( ( result = pat3Floats.exec( line ) ) !== null ) {

							if ( patWord.exec( line ) !== null ) break;

							var r = parseFloat( result[ 1 ] );
							var g = parseFloat( result[ 2 ] );
							var b = parseFloat( result[ 3 ] );
							colors.push( r, g, b );

						}

					} else if ( inNormalsSection ) {

						// Get the normal vectors

						while ( ( result = pat3Floats.exec( line ) ) !== null ) {

							if ( patWord.exec( line ) !== null ) break;

							var nx = parseFloat( result[ 1 ] );
							var ny = parseFloat( result[ 2 ] );
							var nz = parseFloat( result[ 3 ] );
							normals.push( nx, ny, nz );

						}

					}

				}

				if ( patPOLYGONS.exec( line ) !== null ) {

					inPolygonsSection = true;
					inPointsSection = false;
					inTriangleStripSection = false;

				} else if ( patPOINTS.exec( line ) !== null ) {

					inPolygonsSection = false;
					inPointsSection = true;
					inTriangleStripSection = false;

				} else if ( patTRIANGLE_STRIPS.exec( line ) !== null ) {

					inPolygonsSection = false;
					inPointsSection = false;
					inTriangleStripSection = true;

				} else if ( patPOINT_DATA.exec( line ) !== null ) {

					inPointDataSection = true;
					inPointsSection = false;
					inPolygonsSection = false;
					inTriangleStripSection = false;

				} else if ( patCELL_DATA.exec( line ) !== null ) {

					inCellDataSection = true;
					inPointsSection = false;
					inPolygonsSection = false;
					inTriangleStripSection = false;

				} else if ( patCOLOR_SCALARS.exec( line ) !== null ) {

					inColorSection = true;
					inNormalsSection = false;
					inPointsSection = false;
					inPolygonsSection = false;
					inTriangleStripSection = false;

				} else if ( patNORMALS.exec( line ) !== null ) {

					inNormalsSection = true;
					inColorSection = false;
					inPointsSection = false;
					inPolygonsSection = false;
					inTriangleStripSection = false;

				}

			}

			var geometry = new THREE.BufferGeometry();
			geometry.setIndex( indices );
			geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( positions, 3 ) );

			if ( normals.length === positions.length ) {

				geometry.setAttribute( 'normal', new THREE.Float32BufferAttribute( normals, 3 ) );

			}

			if ( colors.length !== indices.length ) {

				// stagger

				if ( colors.length === positions.length ) {

					geometry.setAttribute( 'color', new THREE.Float32BufferAttribute( colors, 3 ) );

				}

			} else {

				// cell

				geometry = geometry.toNonIndexed();
				var numTriangles = geometry.attributes.position.count / 3;

				if ( colors.length === ( numTriangles * 3 ) ) {

					var newColors = [];

					for ( var i = 0; i < numTriangles; i ++ ) {

						var r = colors[ 3 * i + 0 ];
						var g = colors[ 3 * i + 1 ];
						var b = colors[ 3 * i + 2 ];

						newColors.push( r, g, b );
						newColors.push( r, g, b );
						newColors.push( r, g, b );

					}

					geometry.setAttribute( 'color', new THREE.Float32BufferAttribute( newColors, 3 ) );

				}

			}

			return geometry;

		}

		function parseBinary( data ) {

			var count, pointIndex, i, numberOfPoints, s;
			var buffer = new Uint8Array( data );
			var dataView = new DataView( data );

			// Points and normals, by default, are empty
			var points = [];
			var normals = [];
			var indices = [];

			// Going to make a big array of strings
			var vtk = [];
			var index = 0;

			function findString( buffer, start ) {

				var index = start;
				var c = buffer[ index ];
				var s = [];
				while ( c !== 10 ) {

					s.push( String.fromCharCode( c ) );
					index ++;
					c = buffer[ index ];

				}

				return { start: start,
					end: index,
					next: index + 1,
					parsedString: s.join( '' ) };

			}

			var state, line;

			while ( true ) {

				// Get a string
				state = findString( buffer, index );
				line = state.parsedString;

				if ( line.indexOf( 'DATASET' ) === 0 ) {

					var dataset = line.split( ' ' )[ 1 ];

					if ( dataset !== 'POLYDATA' ) throw new Error( 'Unsupported DATASET type: ' + dataset );

				} else if ( line.indexOf( 'POINTS' ) === 0 ) {

					vtk.push( line );
					// Add the points
					numberOfPoints = parseInt( line.split( ' ' )[ 1 ], 10 );

					// Each point is 3 4-byte floats
					count = numberOfPoints * 4 * 3;

					points = new Float32Array( numberOfPoints * 3 );

					pointIndex = state.next;
					for ( i = 0; i < numberOfPoints; i ++ ) {

						points[ 3 * i ] = dataView.getFloat32( pointIndex, false );
						points[ 3 * i + 1 ] = dataView.getFloat32( pointIndex + 4, false );
						points[ 3 * i + 2 ] = dataView.getFloat32( pointIndex + 8, false );
						pointIndex = pointIndex + 12;

					}

					// increment our next pointer
					state.next = state.next + count + 1;

				} else if ( line.indexOf( 'TRIANGLE_STRIPS' ) === 0 ) {

					var numberOfStrips = parseInt( line.split( ' ' )[ 1 ], 10 );
					var size = parseInt( line.split( ' ' )[ 2 ], 10 );
					// 4 byte integers
					count = size * 4;

					indices = new Uint32Array( 3 * size - 9 * numberOfStrips );
					var indicesIndex = 0;

					pointIndex = state.next;
					for ( i = 0; i < numberOfStrips; i ++ ) {

						// For each strip, read the first value, then record that many more points
						var indexCount = dataView.getInt32( pointIndex, false );
						var strip = [];
						pointIndex += 4;
						for ( s = 0; s < indexCount; s ++ ) {

							strip.push( dataView.getInt32( pointIndex, false ) );
							pointIndex += 4;

						}

						// retrieves the n-2 triangles from the triangle strip
						for ( var j = 0; j < indexCount - 2; j ++ ) {

							if ( j % 2 ) {

								indices[ indicesIndex ++ ] = strip[ j ];
								indices[ indicesIndex ++ ] = strip[ j + 2 ];
								indices[ indicesIndex ++ ] = strip[ j + 1 ];

							} else {

								indices[ indicesIndex ++ ] = strip[ j ];
								indices[ indicesIndex ++ ] = strip[ j + 1 ];
								indices[ indicesIndex ++ ] = strip[ j + 2 ];

							}

						}

					}

					// increment our next pointer
					state.next = state.next + count + 1;

				} else if ( line.indexOf( 'POLYGONS' ) === 0 ) {

					var numberOfStrips = parseInt( line.split( ' ' )[ 1 ], 10 );
					var size = parseInt( line.split( ' ' )[ 2 ], 10 );
					// 4 byte integers
					count = size * 4;

					indices = new Uint32Array( 3 * size - 9 * numberOfStrips );
					var indicesIndex = 0;

					pointIndex = state.next;
					for ( i = 0; i < numberOfStrips; i ++ ) {

						// For each strip, read the first value, then record that many more points
						var indexCount = dataView.getInt32( pointIndex, false );
						var strip = [];
						pointIndex += 4;
						for ( s = 0; s < indexCount; s ++ ) {

							strip.push( dataView.getInt32( pointIndex, false ) );
							pointIndex += 4;

						}

						// divide the polygon in n-2 triangle
						for ( var j = 1; j < indexCount - 1; j ++ ) {

							indices[ indicesIndex ++ ] = strip[ 0 ];
							indices[ indicesIndex ++ ] = strip[ j ];
							indices[ indicesIndex ++ ] = strip[ j + 1 ];

						}

					}

					// increment our next pointer
					state.next = state.next + count + 1;

				} else if ( line.indexOf( 'POINT_DATA' ) === 0 ) {

					numberOfPoints = parseInt( line.split( ' ' )[ 1 ], 10 );

					// Grab the next line
					state = findString( buffer, state.next );

					// Now grab the binary data
					count = numberOfPoints * 4 * 3;

					normals = new Float32Array( numberOfPoints * 3 );
					pointIndex = state.next;
					for ( i = 0; i < numberOfPoints; i ++ ) {

						normals[ 3 * i ] = dataView.getFloat32( pointIndex, false );
						normals[ 3 * i + 1 ] = dataView.getFloat32( pointIndex + 4, false );
						normals[ 3 * i + 2 ] = dataView.getFloat32( pointIndex + 8, false );
						pointIndex += 12;

					}

					// Increment past our data
					state.next = state.next + count;

				}

				// Increment index
				index = state.next;

				if ( index >= buffer.byteLength ) {

					break;

				}

			}

			var geometry = new THREE.BufferGeometry();
			geometry.setIndex( new THREE.BufferAttribute( indices, 1 ) );
			geometry.setAttribute( 'position', new THREE.BufferAttribute( points, 3 ) );

			if ( normals.length === points.length ) {

				geometry.setAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );

			}

			return geometry;

		}

		function Float32Concat( first, second ) {

		    var firstLength = first.length, result = new Float32Array( firstLength + second.length );

		    result.set( first );
		    result.set( second, firstLength );

		    return result;

		}

		function Int32Concat( first, second ) {

		    var firstLength = first.length, result = new Int32Array( firstLength + second.length );

		    result.set( first );
		    result.set( second, firstLength );

		    return result;

		}

		function parseXML( stringFile ) {

			// Changes XML to JSON, based on https://davidwalsh.name/convert-xml-json

			function xmlToJson( xml ) {

				// Create the return object
				var obj = {};

				if ( xml.nodeType === 1 ) { // element

					// do attributes

					if ( xml.attributes ) {

						if ( xml.attributes.length > 0 ) {

							obj[ 'attributes' ] = {};

							for ( var j = 0; j < xml.attributes.length; j ++ ) {

								var attribute = xml.attributes.item( j );
								obj[ 'attributes' ][ attribute.nodeName ] = attribute.nodeValue.trim();

							}

						}

					}

				} else if ( xml.nodeType === 3 ) { // text

					obj = xml.nodeValue.trim();

				}

				// do children
				if ( xml.hasChildNodes() ) {

					for ( var i = 0; i < xml.childNodes.length; i ++ ) {

						var item = xml.childNodes.item( i );
						var nodeName = item.nodeName;

						if ( typeof obj[ nodeName ] === 'undefined' ) {

							var tmp = xmlToJson( item );

							if ( tmp !== '' ) obj[ nodeName ] = tmp;

						} else {

							if ( typeof obj[ nodeName ].push === 'undefined' ) {

								var old = obj[ nodeName ];
								obj[ nodeName ] = [ old ];

							}

							var tmp = xmlToJson( item );

							if ( tmp !== '' ) obj[ nodeName ].push( tmp );

						}

					}

				}

				return obj;

			}

			// Taken from Base64-js
			function Base64toByteArray( b64 ) {

				var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;
				var i;
				var lookup = [];
				var revLookup = [];
				var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
				var len = code.length;

				for ( i = 0; i < len; i ++ ) {

					lookup[ i ] = code[ i ];

				}

				for ( i = 0; i < len; ++ i ) {

					revLookup[ code.charCodeAt( i ) ] = i;

				}

				revLookup[ '-'.charCodeAt( 0 ) ] = 62;
				revLookup[ '_'.charCodeAt( 0 ) ] = 63;

				var j, l, tmp, placeHolders, arr;
				var len = b64.length;

				if ( len % 4 > 0 ) {

					throw new Error( 'Invalid string. Length must be a multiple of 4' );

				}

				placeHolders = b64[ len - 2 ] === '=' ? 2 : b64[ len - 1 ] === '=' ? 1 : 0;
				arr = new Arr( len * 3 / 4 - placeHolders );
				l = placeHolders > 0 ? len - 4 : len;

				var L = 0;

				for ( i = 0, j = 0; i < l; i += 4, j += 3 ) {

					tmp = ( revLookup[ b64.charCodeAt( i ) ] << 18 ) | ( revLookup[ b64.charCodeAt( i + 1 ) ] << 12 ) | ( revLookup[ b64.charCodeAt( i + 2 ) ] << 6 ) | revLookup[ b64.charCodeAt( i + 3 ) ];
					arr[ L ++ ] = ( tmp & 0xFF0000 ) >> 16;
					arr[ L ++ ] = ( tmp & 0xFF00 ) >> 8;
					arr[ L ++ ] = tmp & 0xFF;

				}

				if ( placeHolders === 2 ) {

					tmp = ( revLookup[ b64.charCodeAt( i ) ] << 2 ) | ( revLookup[ b64.charCodeAt( i + 1 ) ] >> 4 );
					arr[ L ++ ] = tmp & 0xFF;

				} else if ( placeHolders === 1 ) {

					tmp = ( revLookup[ b64.charCodeAt( i ) ] << 10 ) | ( revLookup[ b64.charCodeAt( i + 1 ) ] << 4 ) | ( revLookup[ b64.charCodeAt( i + 2 ) ] >> 2 );
					arr[ L ++ ] = ( tmp >> 8 ) & 0xFF;
					arr[ L ++ ] = tmp & 0xFF;

				}

				return arr;

			}

			function parseDataArray( ele, compressed ) {

				var numBytes = 0;

				if ( json.attributes.header_type === 'UInt64' ) {

					numBytes = 8;

				}	else if ( json.attributes.header_type === 'UInt32' ) {

					numBytes = 4;

				}

				// Check the format
				if ( ele.attributes.format === 'binary' && compressed ) {

					var rawData, content, byteData, blocks, cSizeStart, headerSize, padding, dataOffsets, currentOffset;

					if ( ele.attributes.type === 'Float32' ) {

						var txt = new Float32Array( );

					} else if ( ele.attributes.type === 'Int64' ) {

						var txt = new Int32Array( );

					}

					// VTP data with the header has the following structure:
					// [#blocks][#u-size][#p-size][#c-size-1][#c-size-2]...[#c-size-#blocks][DATA]
					//
					// Each token is an integer value whose type is specified by "header_type" at the top of the file (UInt32 if no type specified). The token meanings are:
					// [#blocks] = Number of blocks
					// [#u-size] = Block size before compression
					// [#p-size] = Size of last partial block (zero if it not needed)
					// [#c-size-i] = Size in bytes of block i after compression
					//
					// The [DATA] portion stores contiguously every block appended together. The offset from the beginning of the data section to the beginning of a block is
					// computed by summing the compressed block sizes from preceding blocks according to the header.

					rawData = ele[ '#text' ];

					byteData = Base64toByteArray( rawData );

					blocks = byteData[ 0 ];
					for ( var i = 1; i < numBytes - 1; i ++ ) {

						blocks = blocks | ( byteData[ i ] << ( i * numBytes ) );

					}

					headerSize = ( blocks + 3 ) * numBytes;
					padding = ( ( headerSize % 3 ) > 0 ) ? 3 - ( headerSize % 3 ) : 0;
					headerSize = headerSize + padding;

					dataOffsets = [];
					currentOffset = headerSize;
					dataOffsets.push( currentOffset );

					// Get the blocks sizes after the compression.
					// There are three blocks before c-size-i, so we skip 3*numBytes
					cSizeStart = 3 * numBytes;

					for ( var i = 0; i < blocks; i ++ ) {

						var currentBlockSize = byteData[ i * numBytes + cSizeStart ];

						for ( var j = 1; j < numBytes - 1; j ++ ) {

							// Each data point consists of 8 bytes regardless of the header type
							currentBlockSize = currentBlockSize | ( byteData[ i * numBytes + cSizeStart + j ] << ( j * 8 ) );

						}

						currentOffset = currentOffset + currentBlockSize;
						dataOffsets.push( currentOffset );

					}

					for ( var i = 0; i < dataOffsets.length - 1; i ++ ) {

						var data = fflate.unzlibSync( byteData.slice( dataOffsets[ i ], dataOffsets[ i + 1 ] ) ); // eslint-disable-line no-undef
						content = data.buffer;

						if ( ele.attributes.type === 'Float32' ) {

							content = new Float32Array( content );
							txt = Float32Concat( txt, content );

						} else if ( ele.attributes.type === 'Int64' ) {

							content = new Int32Array( content );
							txt = Int32Concat( txt, content );

						}

					}

					delete ele[ '#text' ];

					if ( ele.attributes.type === 'Int64' ) {

						if ( ele.attributes.format === 'binary' ) {

							txt = txt.filter( function ( el, idx ) {

								if ( idx % 2 !== 1 ) return true;

							} );

						}

					}

				} else {

					if ( ele.attributes.format === 'binary' && ! compressed ) {

						var content = Base64toByteArray( ele[ '#text' ] );

						//  VTP data for the uncompressed case has the following structure:
						// [#bytes][DATA]
						// where "[#bytes]" is an integer value specifying the number of bytes in the block of data following it.


text: module.exports={A:{A:{"2":"I D F E A B oB"},B:{"1":"Z MB M R S N U V W","2":"C O H P J K L"},C:{"1":"0 1 2 3 4 5 6 7 8 9 I D F E A B C O H P J K L b c d e f g h i j k l m n o p q r s t u v w x y z AB BB CB DB EB FB GB TB IB JB KB LB T NB OB PB QB RB HB Y XB UB VB WB SB Z MB M mB R S N U V","2":"nB cB G a vB yB"},D:{"1":"0 1 2 3 4 5 6 7 8 9 I D F E A B C O H P J K L b c d e f g h i j k l m n o p q r s t u v w x y z AB BB CB DB EB FB GB TB IB JB KB LB T NB OB PB QB RB HB Y XB UB VB WB SB Z MB M R S N U V W 0B dB eB fB","2":"G a"},E:{"1":"a I D F E A B C O H iB jB kB lB ZB X Q pB qB","2":"G gB YB"},F:{"1":"0 1 2 3 4 5 6 7 8 9 B C P J K L b c d e f g h i j k l m n o p q r s t u v w x y z AB BB CB DB EB GB IB JB KB LB T NB OB PB QB RB HB Y X aB wB Q","4":"E rB sB tB uB"},G:{"1":"F xB bB zB YC 1B 2B 3B 4B 5B 6B 7B 8B 9B AC BC CC DC EC FC","2":"YB"},H:{"2":"GC"},I:{"1":"M LC MC","2":"cB G HC IC JC KC bB"},J:{"1":"D A"},K:{"1":"C FB X aB Q","4":"A B"},L:{"1":"W"},M:{"1":"N"},N:{"2":"A B"},O:{"1":"NC"},P:{"1":"G OC PC QC RC SC ZB TC UC VC"},Q:{"1":"WC"},R:{"1":"XC"},S:{"1":"hB"}},B:1,C:"Server-sent events"};


text:
"use strict";
/**
 * Accounting API
 * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
 *
 * The version of the OpenAPI document: 2.0.2
 * Contact: api@xero.com
 *
 * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */
Object.defineProperty(exports, "__esModule", { value: true });
class Invoices {
    static getAttributeTypeMap() {
        return Invoices.attributeTypeMap;
    }
}
exports.Invoices = Invoices;
Invoices.discriminator = undefined;
Invoices.attributeTypeMap = [
    {
        "name": "invoices",
        "baseName": "Invoices",
        "type": "Array<Invoice>"
    }
];
//# sourceMappingURL=invoices.js.map