() => {
      when(configurationServiceMock.getServerConfiguration()).thenReturn(of({}));
    }


() => {
      const action = loadServerConfig();
      const completion = loadServerConfigSuccess({ config: {} });

      actions$ = hot('-a-a-a', { a: action });
      const expected$ = cold('-c-c-c', { c: completion });

      expect(effects.loadServerConfig$).toBeObservable(expected$);
    }


() => {
      when(configurationServiceMock.getServerConfiguration()).thenReturn(
        throwError(makeHttpError({ message: 'invalid' }))
      );

      const action = loadServerConfig();
      const completion = loadServerConfigFail({ error: makeHttpError({ message: 'invalid' }) });
      actions$ = hot('-a-a-a', { a: action });
      const expected$ = cold('-c-c-c', { c: completion });

      expect(effects.loadServerConfig$).toBeObservable(expected$);
    }


export async function outputDocs(config: d.Config, compilerCtx: d.CompilerCtx, buildCtx: d.BuildCtx) {
  if (!config.buildDocs) {
    return;
  }
  const docsOutputTargets = config.outputTargets.filter(o => (
    isOutputTargetCustom(o) ||
    isOutputTargetDocsReadme(o) ||
    isOutputTargetDocsJson(o) ||
    isOutputTargetDocsCustom(o) ||
    isOutputTargetDocsVscode(o)
  ));

  // ensure all the styles are built first, which parses all the css docs
  await buildCtx.stylesPromise;

  const docsData = await generateDocData(config, compilerCtx, buildCtx);

  await Promise.all([
    generateReadmeDocs(config, compilerCtx, docsData, docsOutputTargets),
    generateJsonDocs(config, compilerCtx, docsData, docsOutputTargets),
    generateVscodeDocs(compilerCtx, docsData, docsOutputTargets),
    generateCustomDocs(config, docsData, docsOutputTargets),
    outputCustom(config, compilerCtx, buildCtx, docsData, docsOutputTargets)
  ]);
}


o => (
    isOutputTargetCustom(o) ||
    isOutputTargetDocsReadme(o) ||
    isOutputTargetDocsJson(o) ||
    isOutputTargetDocsCustom(o) ||
    isOutputTargetDocsVscode(o)
  )


(integrationTypes: DesktopIntegrationTypeModel[]) => {
  return integrationTypes
    .map((integrationType) => {
      // Removing payment as only an internal replacement screen option
      if (integrationType.id !== 'Payment') {
        return {
          value: integrationType.id || '',
          label: integrationType.name || '',
          description: integrationType.description || '',
          link: integrationType.url || '',
        }
      }
    })
    .filter((option) => Boolean(option)) as SelectOption[]
}


(integrationType) => {
      // Removing payment as only an internal replacement screen option
      if (integrationType.id !== 'Payment') {
        return {
          value: integrationType.id || '',
          label: integrationType.name || '',
          description: integrationType.description || '',
          link: integrationType.url || '',
        }
      }
    }


(option) => Boolean(option)


() => {
  const integrationTypes = useSelector(selectIntegrationTypes)

  const integrationTypeOptions: SelectOption[] = prepareIntegrationTypeOptions(integrationTypes)

  return (
    <FormSection>
      <FormHeading>Agency Cloud Integration</FormHeading>
      <FormSubHeading>
        To be able to associate your application with an action in Agency Cloud the application will need to be given a
        desktop type. Please select the type of integration your app requires from the list below. For more information
        on Desktop Types, please{' '}
        <a
          className={link}
          href="https://foundations-documentation.reapit.cloud/api/desktop-api#desktop-types"
          target="_blank"
          rel="noopener noreferrer"
        >
          click here
        </a>
      </FormSubHeading>
      <Grid>
        <GridItem>
          <DropdownSelect
            mode="multiple"
            options={integrationTypeOptions}
            labelText="Integration Type"
            name="desktopIntegrationTypeIds"
            id="desktopIntegrationTypeIds"
            placeholder="Please select"
            fixedPosition
          />
        </GridItem>
      </Grid>
    </FormSection>


export type AgencyCloudIntegrationSectionProps = {}


type of integration


@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  exports: [
    RouterModule
  ],
  declarations: []
})
export class AppRoutingModule { }


function handleRouteChange(val: any) {
    switch (val.query) {
      case 'q':
        setSearch(val.value);
        break;
      case 'sort':
        setSorts(val.value);
        break;
      case 'size':
        setItems(val.value);
        break;
      case 'fq':
        setFilters(val.value);
        break;
      case 'from':
        setPages(val.value);
        break;
    }
  }


function handleButtonClick(e: any) {
    e.preventDefault();
    setModalIsOpen(!modalIsOpen);
  }


({ data, facets }) => {
  const router = useRouter();
  const { q, sort, size, fq, from } = router.query;
  const [search, setSearch] = useState(q);
  const [sorts, setSorts] = useState(sort);
  const [items, setItems] = useState(size);
  const [filters, setFilters] = useState(fq);
  const [pages, setPages] = useState(from);
  const [modalIsOpen, setModalIsOpen] = useState(false);

  const { results, count } = data.result;
  useEffect(() => {
    router.push({
      pathname: router.pathname,
      query: { fq: filters, q: search, sort: sorts, size: items, from: pages },
    });
  }, [filters, search, sorts, pages, items]);

  function handleRouteChange(val: any) {
    switch (val.query) {
      case 'q':
        setSearch(val.value);
        break;
      case 'sort':
        setSorts(val.value);
        break;
      case 'size':
        setItems(val.value);
        break;
      case 'fq':
        setFilters(val.value);
        break;
      case 'from':
        setPages(val.value);
        break;
    }
  }

  function handleButtonClick(e: any) {
    e.preventDefault();
    setModalIsOpen(!modalIsOpen);
  }

  const headerData = {
    title: 'Contracts Data',
    content:
      'This page shows the public procurement data of the last 5 financial years for the contracts over INR 50 lakh value. One could download the total compiled data or explore specific tender groups using various filters like financial year, tendering organization, tender status, tender types, etc.',
  };

  return (
    <>

        <title>HAQ-GEST | Datasets</title>
        <link rel="icon" href="/favicon.ico" />

        <MegaHeader data={headerData} />

          <Filter data={facets} newFilters={handleRouteChange} fq={filters} />
          {data && (

Browse Contracts

              <Search newSearch={handleRouteChange} />

                <Total text="contracts" total={count} />

                  <Sort newSort={handleRouteChange} />
                  <button
                    id="modalTrigger"
                    className="btn-primary"
                    onClick={handleButtonClick}
                  >
                    <svg
                      width="10"
                      height="12"
                      viewBox="0 0 10 12"
                      fill="none"
                      xmlns="http://www.w3.org/2000/svg"
                    >
                      <path
                        d="M8.05967 4H6.99967V0.666667C6.99967 0.3 6.69967 0 6.33301 0H3.66634C3.29967 0 2.99967 0.3 2.99967 0.666667V4H1.93967C1.34634 4 1.04634 4.72 1.46634 5.14L4.52634 8.2C4.78634 8.46 5.20634 8.46 5.46634 8.2L8.52634 5.14C8.94634 4.72 8.65301 4 8.05967 4ZM0.333008 10.6667C0.333008 11.0333 0.633008 11.3333 0.999674 11.3333H8.99967C9.36634 11.3333 9.66634 11.0333 9.66634 10.6667C9.66634 10.3 9.36634 10 8.99967 10H0.999674C0.633008 10 0.333008 10.3 0.333008 10.6667Z"
                        fill="white"
                      />
                    </svg>
                    Download
                  </button>
                  <Modal
                    isOpen={modalIsOpen}
                    onRequestClose={handleButtonClick}
                    className="dialog dialog--download"
                    overlayClassName="dialog__backdrop"
                    contentLabel="Download Tenders"
                    aria={{
                      labelledby: 'dialog-head',
                      describedby: 'dialog-para',
                    }}


() => {
    router.push({
      pathname: router.pathname,
      query: { fq: filters, q: search, sort: sorts, size: items, from: pages },
    });
  }


async (context) => {
  const query = context.query || {};
  const variables = convertToCkanSearchQuery(query);
  const facets = await getFilters(list, variables, 'tender_dataset');

  const data = await fetchDatasets('tender_dataset', variables);
  return {
    props: {
      data,
      facets,
    },
  };
}


type Props = {
  data: any;
  facets: any;
  variables: any;
};


@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    NgbModule,
  ],
  declarations: [
    HomeComponent,
    ServicosComponent,
    HistoriaComponent,
    NoticiasComponent,
    TrabalheConoscoComponent,
    ContatoComponent,
    EmBreveComponent
  ]
})
export class PagesModule { }


export function createTranslateLoader( httpClient: HttpClient ) {
    return new TranslateHttpLoader( httpClient, '../assets/i18n/', '.json' );
}


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule,
    AppRoutingModule,
    TranslateModule.forRoot({
			loader: {
			  provide: TranslateLoader,
			  useFactory: (createTranslateLoader),
			  deps: [HttpClient]
			}
		})
  ],
  providers: [
    {
      provide: MissingTranslationHandler, useClass: MyMissingTranslationHandler
    },
    TranslateService
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }


(id: unknown): id is string => typeof id === 'string' && Boolean(id.trim())


async get() {
		check(this.queryParams, Match.ObjectIncluding({
			platform: Match.OneOf(...Object.values(BannerPlatform)),
			bid: Match.Maybe(String),
		}));

		const { platform, bid: bannerId } = this.queryParams;

		const banners = await Banner.getBannersForUser(this.userId, platform, bannerId ?? undefined);

		return API.v1.success({ banners });
	}


async get() {
		check(this.urlParams, Match.ObjectIncluding({
			id: Match.Where((id: unknown): id is string => typeof id === 'string' && Boolean(id.trim())),
		}));

		check(this.queryParams, Match.ObjectIncluding({
			platform: Match.OneOf(...Object.values(BannerPlatform)),
		}));

		const { platform } = this.queryParams;
		const { id } = this.urlParams;

		const banners = await Banner.getBannersForUser(this.userId, platform, id);

		return API.v1.success({ banners });
	}


async get() {
		check(this.queryParams, Match.ObjectIncluding({
			platform: Match.OneOf(...Object.values(BannerPlatform)),
		}));

		const { platform } = this.queryParams;

		const banners = await Banner.getBannersForUser(this.userId, platform);

		return API.v1.success({ banners });
	}


async post() {
		check(this.bodyParams, Match.ObjectIncluding({
			bannerId: Match.Where((id: unknown): id is string => typeof id === 'string' && Boolean(id.trim())),
		}));

		const { bannerId } = this.bodyParams;

		await Banner.dismiss(this.userId, bannerId);
		return API.v1.success();
	}


@NgModule({
  imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }


/**
 * Set of functions you can use to customize how insights are rendered.
 *
 * @public
 */
export interface IDashboardInsightCustomizer {
    /**
     * A convenience method that will register a specific React component to use for rendering
     * any insight that is tagged with the provided `tag`. If plugins register multiple providers
     * for the same tag, then the provider will be picked using 'last-win' strategy.
     *
     * @param tag - tag to look for on the insight, this function will do nothing if this argument is an empty string
     * @param component - component to use if the tag is found
     * @returns self, for call chaining sakes
     */
    withTag(tag: string, component: CustomDashboardInsightComponent): IDashboardInsightCustomizer;

    /**
     * Register a provider for React components to render insights. A provider takes the insight and
     * widget that it is part of as input and is expected to return a React component that should be
     * used to render that insight.
     *
     * If the provider returns `undefined` then:
     *
     * -  if there are other providers registered, they will be called to see if they can provide
     *    a component to render the insight
     * -  if there are no other providers registered, the default, built-in component will be used.
     *
     * You may register multiple providers. They will be evaluated in the order you register them.
     *
     * @remarks see the {@link IDashboardInsightCustomizer.withTag} convenience method to register components for insights
     *  with particular tags.
     * @param provider - provider to register
     * @returns self, for call chaining sakes
     */
    withCustomProvider(provider: OptionalInsightComponentProvider): IDashboardInsightCustomizer;

    /**
     * Register a factory for insight decorator providers. Decorators are a way to add customizations or embellishments on top
     * of an existing component. Decorators are more complex to write because they need to work with the component
     * they should decorate and add 'something' on top of that component.
     *
     * This is best illustrated on an example:
     *
     * @example
     * ```
     * withCustomDecorator((next) => {
     *     return (insight, widget) => {
     *         if (some_condition_to_prevent_decoration) {
     *             return undefined;
     *         }
     *
     *         function MyCustomDecorator(props) {
     *              const Decorated = next(insight, widget);
     *
     *              return (
     *                  <div>
     *                      <p>My Custom Decoration</p>
     *                      <Decorated {...props} />
     *                  </div>
     *              )
     *         }
     *
     *         return MyCustomDecorator;
     *     }
     * })
     * ```
     *
     * The above shows how to register a decorator that will use some condition to determine whether particular
     * insight is eligible for decoration. If yes, it will add some extra text in front of the insight. Decorator
     * defers rendering of the actual insight to the underlying provider.
     *
     * Note: the factory function that you specify will be called immediately at the registration time. The
     * provider that it returns will be called at render time.
     *
     * @param providerFactory - factory
     */
    withCustomDecorator(
        providerFactory: (next: InsightComponentProvider) => OptionalInsightComponentProvider,
    ): IDashboardInsightCustomizer;
}


/**
 * Set of functions you can use to customize how KPIs are rendered.
 *
 * @public
 */
export interface IDashboardKpiCustomizer {
    /**
     * Register a provider for React components to render insights. A provider takes the insight and
     * widget that it is part of as input and is expected to return a React component that should be
     * used to render that insight.
     *
     * If the provider returns `undefined` then:
     *
     * -  if there are other providers registered, they will be called to see if they can provide
     *    a component to render the insight
     * -  if there are no other providers registered, the default, built-in component will be used.
     *
     * You may register multiple providers. They will be evaluated in the order you register them.
     *
     * @param provider - provider to register
     * @returns self, for call chaining sakes
     */
    withCustomProvider(provider: OptionalKpiComponentProvider): IDashboardKpiCustomizer;

    /**
     * Register a factory for insight decorator providers. Decorators are a way to add customizations or embellishments on top
     * of an existing component. Decorators are more complex to write because they need to work with the component
     * they should decorate and add 'something' on top of that component.
     *
     * This is best illustrated on an example:
     *
     * @example
     * ```
     * withCustomDecorator((next) => {
     *     return (kpi, widget) => {
     *         if (some_condition_to_prevent_decoration) {
     *             return undefined;
     *         }
     *
     *         function MyCustomDecorator(props) {
     *              const Decorated = next(kpi, widget);
     *
     *              return (
     *                  <div>
     *                      <p>My Custom Decoration</p>
     *                      <Decorated {...props}/>
     *                  </div>
     *              )
     *         }
     *
     *         return MyCustomDecorator;
     *     }
     * })
     * ```
     *
     * The above shows how to register a decorator that will use some condition to determine whether particular
     * insight is eligible for decoration. If yes, it will add some extra text in front of the insight. Decorator
     * defers rendering of the actual insight to the underlying provider.
     *
     * Note: the factory function that you specify will be called immediately at the registration time. The
     * provider that it returns will be called at render time.
     *
     * @param providerFactory - factory
     */
    withCustomDecorator(
        providerFactory: (next: KpiComponentProvider) => OptionalKpiComponentProvider,
    ): IDashboardKpiCustomizer;
}


/**
 * Set of functions you can use to customize custom widgets.
 *
 * @public
 */
export interface IDashboardWidgetCustomizer {
    /**
     * Adds a new custom widget type. Custom widget's can be used to render arbitrary content.
     *
     * The custom widget must be wrapped inside an element which sets the height and width CSS sizing
     * properties in order to align the behavior with the provided widget types.
     *
     * @param widgetType - unique type name of the custom widget; if plugins register multiple custom
     *  widgets for the same widget type, then the last-registered custom widget wins
     * @param Component - React component to use for rendering of the custom widget
     */
    addCustomWidget(
        widgetType: string,
        Component: CustomDashboardWidgetComponent,
    ): IDashboardWidgetCustomizer;
}


/**
 * Set of functions you can use to customize the fluid layout of the dashboard rendered.
 *
 * @public
 */
export interface IFluidLayoutCustomizer {
    /**
     * Adds a new section with one or more custom widgets onto the fluid layout. The section to add must not
     * be empty - it must contain at least one item. Attempts to add empty sections will be ignored and
     * warnings will be reported.
     *
     * @param sectionIdx - index to add the new section at
     * @param section - section to add; note: customizer will make a deep copy of the item before adding it
     *  onto a dashboard. At this moment, the newly added items are read-only.
     */
    addSection(sectionIdx: number, section: IDashboardLayoutSection<ICustomWidget>): IFluidLayoutCustomizer;

    /**
     * Adds a new item containing a custom widget onto the dashboard. New item will be added to
     * an existing section at index `sectionIdx` and within that section will be placed at `itemIdx`. The item
     * to add must contain a custom widget data. Attempts to add item that does not contain any widget data
     * will be ignored and warnings will be reported. Keep in mind that this can lead to further errors or
     * problems down the line if you are adding more items at specific indexes into the same section.
     *
     * Note: new items will be added into existing sections before new sections will be added using the
     * {@link IFluidLayoutCustomizer.addSection} method. Therefore,
     *
     * @param sectionIdx - index of section where to add the new item
     * @param itemIdx - index within the section where to add new item; you may specify -1 to add the
     *  item at the end of the section
     * @param item - item containing custom widget; note: customizer will make a deep copy of the item before adding it
     *  onto a dashboard. At this moment, the newly added items are read-only.
     */
    addItem(
        sectionIdx: number,
        itemIdx: number,
        item: IDashboardLayoutItem<ICustomWidget>,
    ): IFluidLayoutCustomizer;
}


/**
 * Set of functions you can use to customize the layout of the dashboard rendered.
 *
 * @public
 */
export interface IDashboardLayoutCustomizer {
    /**
     * Register customization of the fluid layout that is used to render the dashboard.
     *
     * @remarks
     * At this point, you can register a function which will be called after dashboard component loads
     * the dashboard and before it starts initializing the layout itself. The function will be called
     * with two arguments:
     *
     * -  The actual dashboard layout
     * -  Customizer that allows the plugin to add new sections or section items
     *
     * Your customization function may introspect the original layout and then register its customizations.
     *
     * If the dashboard is not rendering fluid layout, then the registered function will not
     * be called.
     */
    customizeFluidLayout(fun: FluidLayoutCustomizationFn): IDashboardLayoutCustomizer;
}


/**
 * Set of functions you can use to customize some aspects of the FilterBar.
 *
 * @public
 */
export interface IFilterBarCustomizer {
    /**
     * Set the rendering mode of the FilterBar.
     *
     * @param mode - the mode to use, see {@link FilterBarRenderingMode} for info on individual values
     */
    setRenderingMode(mode: FilterBarRenderingMode): IFilterBarCustomizer;
}


/**
 * @public
 */
export interface IDashboardCustomizer {
    /**
     * Customize how rendering of insight widgets is done.
     */
    insightWidgets(): IDashboardInsightCustomizer;

    /**
     * Customize how rendering of KPI widgets is done.
     */
    kpiWidgets(): IDashboardKpiCustomizer;

    /**
     * Register custom widget types.
     */
    customWidgets(): IDashboardWidgetCustomizer;

    /**
     * Customize dashboard layout.
     *
     * @remarks
     * This allows the plugin to step in during initialization and modify
     * the existing dashboard layout before it gets stored into dashboard component's state and
     * before it is rendered.
     */
    layout(): IDashboardLayoutCustomizer;

    /**
     * Customize the filter bar.
     */
    filterBar(): IFilterBarCustomizer;
}


/**
 * Defines a facade that you can use to register or unregister dashboard event handlers.
 *
 * @public
 */
export interface IDashboardEventHandling {
    /**
     * Adds a handler for particular event type. Every time event of that type occurs, the provided callback
     * function will be triggered.
     *
     * @param eventType - type of the event to handle; this can be either built-event event type (see {@link DashboardEventType}), a custom
     *  event type or `'*'` to register handler for all events
     * @param callback - function to call when the event occurs
     */
    addEventHandler<TEvents extends DashboardEvents | ICustomDashboardEvent>(
        eventType: DashboardEventType | string | "*",
        callback: DashboardEventHandlerFn<TEvents>,
    ): IDashboardEventHandling;

    /**
     * Removes a handler for particular event type. This is reverse operation to {@link IDashboardEventHandling.addEventHandler}.
     *
     * @remarks
     * In order for this method to remove a handler, the arguments must be the same when you added the handler.
     *
     * E.g. it is not possible to add a handler for all events using `'*'` and then subtract just one particular event
     * from handling.
     *
     * @param eventType - type of the event to stop handling; this can be either built-event event type (see {@link DashboardEventType}), a custom
     *  event type or `'*'` to register handler for all events
     * @param callback - originally registered callback function
     * @returns self, for call chaining sakes
     */
    removeEventHandler<TEvents extends DashboardEvents | ICustomDashboardEvent>(
        eventType: DashboardEventType | string | "*",
        callback: DashboardEventHandlerFn<TEvents>,
    ): IDashboardEventHandling;

    /**
     * Adds a custom event handler. This is a lower-level API where the handler can include both the function to
     * evaluate events and the function to trigger when the evaluation succeeds.
     *
     * @remarks
     * Attempts to register same handler twice will be ignored.
     *
     * @param handler - event handler to add
     * @returns self, for call chaining sakes
     */
    addCustomEventHandler(handler: DashboardEventHandler): IDashboardEventHandling;

    /**
     * Removes custom event handler. In order for successful removal the entire handler object must be
     * exactly the same as the one that was used when you added the handler.
     *
     * @param handler - event handler to remove
     * @returns self, for call chaining sakes
     */
    removeCustomEventHandler(handler: DashboardEventHandler): IDashboardEventHandling;

    /**
     * Subscribe to state changes of the dashboard.
     *
     * @remarks
     * There is no need to use this if all you need is your custom React components to get up-to-date state. Your
     * React component code can (and really should) use the {@link @gooddata/sdk-ui-dashboard#useDashboardSelector} and
     * {@link @gooddata/sdk-ui-dashboard#useDashboardDispatch} hooks instead.
     *
     * Subscription to state changes is only really needed if you have custom code outside of React components and
     * you need to extract custom data from state using the selectors API.
     *
     * See also {@link SingleDashboardStoreAccessor} and {@link DashboardStoreAccessorRepository} for utility classes
     * that make managing the callback subscriptions more convenient.
     *
     * @param callback - function to call when dashboard state changes; the function will be called with
     *  two parameters: the new state and an instance of dispatch to use.
     * @returns self, for call chaining sakes
     */
    subscribeToStateChanges(callback: DashboardStateChangeCallback): IDashboardEventHandling;

    /**
     * Unsubscribe from receiving calls about state changes of the dashboard.
     *
     * @param callback - callback that was previously used for subscription
     * @returns self, for call chaining sakes
     */
    unsubscribeFromStateChanges(callback: DashboardStateChangeCallback): IDashboardEventHandling;
}


/**
 * @public
 */
export type FluidLayoutCustomizationFn = (
    layout: IDashboardLayout<ExtendedDashboardWidget>,
    customizer: IFluidLayoutCustomizer,
) => void;


/**
 * Mode of rendering of the FilterBar:
 * - default - the filter bar will be rendered as if no rendering mode was set at all.
 * - hidden - the filter bar is hidden. Note that the filters set on the dashboard are still active, just not visible.
 *
 * @public
 */
export type FilterBarRenderingMode = "default" | "hidden";


/**
 * Callback called whenever the Dashboard's internal state changes.
 *
 * @param state - the new value of the state
 * @param dispatch - the new dispatcher function that can be used to dispatch commands
 *
 * @public
 */
// TODO: move to common location
export type DashboardStateChangeCallback = (state: DashboardState, dispatch: DashboardDispatch) => void;


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {}


@Injectable()
export class TransporterService {

  constructor(private http: HttpClient) {
    this.header = new Headers({ 'Content-Type': 'application/json' });
  }

  private header;
  private url = 'http://127.0.0.1:8000/masters/transporter/';

  addTransporter(transporter: Transporter) {
    return this.http
      .post(
        this.url,
        transporter,
        { headers: this.header });

  }

  getTransporter(): Observable<HttpResponse<Transporter[]>>  {
    return this.http
      .get<Transporter[]>(this.url,
        {
          observe: 'response',
          headers: this.header,
        });
    }

  getTransporterById(id) {
    return this.http
      .get(
        this.url + id + '/',
        { headers: this.header },
      );
  }

  deleteTransporter(data) {
    // We receive data object which is a part of the event object
    // passed by the event emitter of smart table. This data object
    // has the data of the field, out of which we can extract the
    // transporter_id.
    const id = data['transporter_id'];
    return this.http
      .delete(
        this.url + id + '/',
        { headers: this.header },
      );
  }

  editTransporter(
    transporter: Transporter,
    id: number) {
    return this.http
      .put(
        this.url + id + '/',
        transporter,
        { headers: this.header },
      );
  }
}


addTransporter(transporter: Transporter) {
    return this.http
      .post(
        this.url,
        transporter,
        { headers: this.header });

  }


getTransporter(): Observable<HttpResponse<Transporter[]>>  {
    return this.http
      .get<Transporter[]>(this.url,
        {
          observe: 'response',
          headers: this.header,
        });
    }


getTransporterById(id) {
    return this.http
      .get(
        this.url + id + '/',
        { headers: this.header },
      );
  }


deleteTransporter(data) {
    // We receive data object which is a part of the event object
    // passed by the event emitter of smart table. This data object
    // has the data of the field, out of which we can extract the
    // transporter_id.
    const id = data['transporter_id'];
    return this.http
      .delete(
        this.url + id + '/',
        { headers: this.header },
      );
  }


editTransporter(
    transporter: Transporter,
    id: number) {
    return this.http
      .put(
        this.url + id + '/',
        transporter,
        { headers: this.header },
      );
  }


data=>{
      console.log(data);
      this.updateData=data;
    }


res=>{
        // alert(res.toString());
        //this.refreshDepList();
        if(res.toString())
        {
          alert(res.toString());
        }
      }


@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  encapsulation: ViewEncapsulation.None,
  //styleUrls: ['./profile.component.scss']
  styles:[
    `
    .example {
      display: flex;
      justify-content: center;
  }
  .wrap {
      display: flex;
      justify-content: space-between;
  }
  .k-form {
      width: 400px;
  }
    `
  ]
})
export class ProfileComponent{
  public phoneNumberValue: string = "";
  public phoneNumberMask: string = "(999) 000-00-00";
  public form: FormGroup;
  public updateData: any;
  public data: any = {
    email: "",
    phoneNumber: this.phoneNumberValue,
    address: "",
    state:"",
    city:""
  };
  public emaildata:any={
    email:""
  };
  public states: Array<string> = states;
  public citys: Array<string> = citys;
  public types: Array<string> = types;
  public getsession:any;
  constructor(private service:RegisterService) {
    this.form = new FormGroup({
      email: new FormControl(this.data.email, [
        Validators.required,
        Validators.email,
      ]),
      phoneNumber: new FormControl(this.data.phoneNumber, [
        Validators.required,
      ]),
      address: new FormControl(this.data.comments),
      state: new FormControl(this.data.state, [Validators.required]),
      city: new FormControl(this.data.city, [Validators.required])
    });
  }

  ngOnInit(): void {
    this.getsession = window.sessionStorage.getItem("username");
    console.log(this.getsession);
    this.emaildata.email=this.getsession;
    this.service.getadmindata(this.emaildata).subscribe(data=>{
      console.log(data);
      this.updateData=data;
    });
  }
  public submitForm(): void {

    if(this.form.valid)
    {
      var companydata={
        Email:this.getsession,
        Contactno:this.form.value.contactno,
        Address:this.form.value.address,
        State:this.form.value.state,
        City:this.form.value.city
      };
      console.log(companydata);
      this.service.updateprofile(companydata).subscribe(res=>{
        // alert(res.toString());
        //this.refreshDepList();
        if(res.toString())
        {
          alert(res.toString());
        }
      });
    }
    else
    {
      alert("Failed");
    }

  }

  public clearForm(): void {
    this.form.reset();
  }
}


ngOnInit(): void {
    this.getsession = window.sessionStorage.getItem("username");
    console.log(this.getsession);
    this.emaildata.email=this.getsession;
    this.service.getadmindata(this.emaildata).subscribe(data=>{
      console.log(data);
      this.updateData=data;
    });
  }


public submitForm(): void {

    if(this.form.valid)
    {
      var companydata={
        Email:this.getsession,
        Contactno:this.form.value.contactno,
        Address:this.form.value.address,
        State:this.form.value.state,
        City:this.form.value.city
      };
      console.log(companydata);
      this.service.updateprofile(companydata).subscribe(res=>{
        // alert(res.toString());
        //this.refreshDepList();
        if(res.toString())
        {
          alert(res.toString());
        }
      });
    }
    else
    {
      alert("Failed");
    }

  }


public clearForm(): void {
    this.form.reset();
  }


export class ThrowStatementNode extends Node {
  public astNode: ThrowStatement;

  constructor(
    throwStatement: ThrowStatement,
    uri: string,
    rootPath: string,
    documentsAnalyzer: SolFileIndexMap
  ) {
    super(throwStatement, uri, rootPath, documentsAnalyzer, undefined);
    this.astNode = throwStatement;
    // TO-DO: Implement name location for rename
  }

  public accept(
    find: FinderType,
    orphanNodes: Node[],
    parent?: Node,
    expression?: Node
  ): Node {
    this.setExpressionNode(expression);
    // TO-DO: Method not implemented
    return this;
  }
}


public accept(
    find: FinderType,
    orphanNodes: Node[],
    parent?: Node,
    expression?: Node
  ): Node {
    this.setExpressionNode(expression);
    // TO-DO: Method not implemented
    return this;
  }


() => {
  it('caches when a primitive is resolved', () => {
    var i = 0;
    var s = memoize(() => {
      i++;
      return i;
    });

    s();
    s();
    s();

    assert.equal(i, 1);
  });

  it('caches a function', () => {
    var s = memoize(() => () => {
      /**/
    });

    var first = s();
    var second = s();

    assert.equal(first, second);
  });

  it('caches based on one argument', () => {
    var i = 0;
    var s = memoize((n: number) => {
      i += n;
      return i;
    });

    s(1);
    s(2);
    s(3);

    s(1);
    s(2);
    s(3);

    s(1);
    s(2);
    s(3);

    assert.equal(i, 6);
  });

  it('caches based on two arguments', () => {
    var i = 0;
    var s = memoize((n1: number, _s: string) => {
      i += n1;
      return i;
    });

    s(1, '');
    s(1, 'something');

    s(1, '');
    s(1, 'something');

    assert.equal(i, 2);
  });
}


() => {
    var i = 0;
    var s = memoize(() => {
      i++;
      return i;
    });

    s();
    s();
    s();

    assert.equal(i, 1);
  }


() => {
      i++;
      return i;
    }


() => {
    var s = memoize(() => () => {
      /**/
    });

    var first = s();
    var second = s();

    assert.equal(first, second);
  }


() => {
    var i = 0;
    var s = memoize((n: number) => {
      i += n;
      return i;
    });

    s(1);
    s(2);
    s(3);

    s(1);
    s(2);
    s(3);

    s(1);
    s(2);
    s(3);

    assert.equal(i, 6);
  }


(n: number) => {
      i += n;
      return i;
    }


() => {
    var i = 0;
    var s = memoize((n1: number, _s: string) => {
      i += n1;
      return i;
    });

    s(1, '');
    s(1, 'something');

    s(1, '');
    s(1, 'something');

    assert.equal(i, 2);
  }


(n1: number, _s: string) => {
      i += n1;
      return i;
    }


@Injectable()
export class GuTreeViewService {

  currentSelectedNode: any;

  changeCurrentSelectNode(newNode) {

    if (this.currentSelectedNode === newNode) {
      return;
    }

    if (this.currentSelectedNode) {
      this.currentSelectedNode.isSelect = false;
    }
    this.currentSelectedNode = newNode;
  }
}


changeCurrentSelectNode(newNode) {

    if (this.currentSelectedNode === newNode) {
      return;
    }

    if (this.currentSelectedNode) {
      this.currentSelectedNode.isSelect = false;
    }
    this.currentSelectedNode = newNode;
  }


/**
 * compose :: ((y -> z), ..., (a -> b)) -> a -> z
 */
declare function compose<Z>(f: ReadonlyArray<(y: unknown) => Z>, g: (...args: any[]) => unknown): Z;


export function LazyLoadObj (property: string, emptyValue: any = null, url?: string) {
	return function (target: any, propertyName: string) {
		const needUpdate = true;
		let realValue;

		Object.defineProperty(target, propertyName, {
			async get () {
				if (realValue != emptyValue) {
					return realValue;
				}
				const content = {};

				content[property] = this[property];

				const value = await DataGetter.instance.post(url, content);

				realValue = value;

				return value;
			},
			async set (value) {
				realValue = value;
			}
		});
	};
}


async get () {
				if (realValue != emptyValue) {
					return realValue;
				}
				const content = {};

				content[property] = this[property];

				const value = await DataGetter.instance.post(url, content);

				realValue = value;

				return value;
			}


async set (value) {
				realValue = value;
			}


() => {
    mockStatement = Mock.ofType<sqlite.Statement>();

    mockSqlite = Mock.ofType<sqlite.Database>();
    mockSqlite
      .setup((m) => m.prepare(It.isAnyString()))
      .returns(() => mockStatement.object);

    mockLogger = Mock.ofType<Logger>();

    testObject = new TestableSqliteWrapper(mockLogger.object);
  }


(m) => m.prepare(It.isAnyString())


() => mockStatement.object


() => {
    expect(testObject).toBeTruthy();
  }


() => {
    // Can't work out a way to mock out the Database constructor cleanly so that
    // This test works properly. Disabling for now.
    xit('should connect', (done) => {
      const mockDbConcretion = (
        file: string,
        callback: (err: Error) => void
      ) => {
        callback(null);
      };

      spyOn(sqlite, 'Database').and.returnValue(mockDbConcretion as any);

      testObject
        .connect()
        .then(() => {
          const dbHandle = testObject.dbInstance;
          expect(dbHandle).toBeTruthy();
          expect(dbHandle.fileName).toBe('./bot.sqlite');
          done();
        })
        .catch((err) => fail(err));
    });

    it('should not attempt to reconnect if there is already a connection object', (done) => {
      testObject.dbInstance = {};

      testObject
        .connect()
        .then(() => fail('Should not get here'))
        .catch((err: Error) => {
          expect(err).toBeTruthy();
          done();
        });
    });

    it('should disconnect if connected', (done) => {
      const mySqlite = {
        close(cb: () => void) {
          cb();
        }
      };

      const spy = spyOn(mySqlite, 'close').and.callThrough();

      testObject.dbInstance = mySqlite;

      testObject
        .disconnect()
        .then(() => {
          expect(spy).toHaveBeenCalled();
          done();
        })
        .catch(() => fail('Should not get here'));
    });

    it('should not reject when trying to disconnect if not connected', (done) => {
      testObject
        .disconnect()
        .then(() => {
          expect().nothing();
          done();
        })
        .catch(() => {
          fail('Throwing when disconnecting when not connected');
        });
    });

    it('should bubble up error and reject if disconnect fails', (done) => {
      const expectedError = 'ERROR';
      const mySqlite = {
        close(cb: (err: Error) => void) {
          cb(new Error(expectedError));
        }
      };

      testObject.dbInstance = mySqlite;

      testObject
        .disconnect()
        .then(() => fail('Should not get here'))
        .catch((err: Error) => {
          expect(err).toBeTruthy();
          expect(err.message).toBe(expectedError);
          done();
        });
    });
  }


(done) => {
      const mockDbConcretion = (
        file: string,
        callback: (err: Error) => void
      ) => {
        callback(null);
      };

      spyOn(sqlite, 'Database').and.returnValue(mockDbConcretion as any);

      testObject
        .connect()
        .then(() => {
          const dbHandle = testObject.dbInstance;
          expect(dbHandle).toBeTruthy();
          expect(dbHandle.fileName).toBe('./bot.sqlite');
          done();
        })
        .catch((err) => fail(err));
    }


(
        file: string,
        callback: (err: Error) => void
      ) => {
        callback(null);
      }


() => {
          const dbHandle = testObject.dbInstance;
          expect(dbHandle).toBeTruthy();
          expect(dbHandle.fileName).toBe('./bot.sqlite');
          done();
        }


(err) => fail(err)


(done) => {
      testObject.dbInstance = {};

      testObject
        .connect()
        .then(() => fail('Should not get here'))
        .catch((err: Error) => {
          expect(err).toBeTruthy();
          done();
        });
    }


() => fail('Should not get here')


(err: Error) => {
          expect(err).toBeTruthy();
          done();
        }


(done) => {
      const mySqlite = {
        close(cb: () => void) {
          cb();
        }
      };

      const spy = spyOn(mySqlite, 'close').and.callThrough();

      testObject.dbInstance = mySqlite;

      testObject
        .disconnect()
        .then(() => {
          expect(spy).toHaveBeenCalled();
          done();
        })
        .catch(() => fail('Should not get here'));
    }


() => {
          expect(spy).toHaveBeenCalled();
          done();
        }


(done) => {
      testObject
        .disconnect()
        .then(() => {
          expect().nothing();
          done();
        })
        .catch(() => {
          fail('Throwing when disconnecting when not connected');
        });
    }


() => {
          expect().nothing();
          done();
        }


() => {
          fail('Throwing when disconnecting when not connected');
        }


(done) => {
      const expectedError = 'ERROR';
      const mySqlite = {
        close(cb: (err: Error) => void) {
          cb(new Error(expectedError));
        }
      };

      testObject.dbInstance = mySqlite;

      testObject
        .disconnect()
        .then(() => fail('Should not get here'))
        .catch((err: Error) => {
          expect(err).toBeTruthy();
          expect(err.message).toBe(expectedError);
          done();
        });
    }


(err: Error) => {
          expect(err).toBeTruthy();
          expect(err.message).toBe(expectedError);
          done();
        }


() => {
    it('should reject when trying to get records and not connected', (done) => {
      testObject
        .getRecordsFromCollection('any', {})
        .then(() => fail('Should not get here'))
        .catch((err: Error) => {
          expect(err).toBeTruthy();
          done();
        });
    });

    it('should handle error returned from getting a collection', (done) => {
      const expectedError = 'ERROR';
      mockStatement
        .setup((m) => m.all(It.isAny(), It.isAny()))
        .callback((_: unknown, cb: (err: Error) => void) => {
          cb(new Error(expectedError));
        });

      testObject.dbInstance = mockSqlite.object;

      testObject
        .getRecordsFromCollection('any', {})
        .then(() => fail('Should not get here'))
        .catch((err: Error) => {
          expect(err.message).toBe(expectedError);
          done();
        });
    });

    it('should get all records from a collection', (done) => {
      const expectedCollection = 'myCollection';
      const mockRows = [{ id: 0 }, { id: 1 }];
      mockStatement
        .setup((m) => m.all(It.isAny(), It.isAny()))
        .callback(
          (_: unknown, cb: (err: Error, rows: KeyedObject[]) => void) => {
            cb(null, mockRows);
          }
        );

      testObject.dbInstance = mockSqlite.object;

      testObject
        .getRecordsFromCollection<KeyedObject>(expectedCollection, {})
        .then((records: KeyedObject[]) => {
          mockSqlite.verify(
            (m) => m.prepare(It.isValue(`SELECT * FROM ${expectedCollection}`)),
            Times.once()
          );
          expect(records).toEqual(mockRows);
          done();
        })
        .catch((err) => fail(err));
    });

    it('should correctly build SQL statement when filter has been applied', (done) => {
      const filter = {
        where: [
          { field: 'a', value: 'a' },
          { field: 'b', value: 'b' }
        ]
      };
      mockStatement
        .setup((m) => m.all(It.isAny(), It.isAny()))
        .callback(
          (_: unknown, cb: (err: Error, rows: KeyedObject[]) => void) => {
            cb(null, []);
          }
        );

      testObject.dbInstance = mockSqlite.object;

      testObject
        .getRecordsFromCollection('col', filter)
        .then(() => {
          mockSqlite.verify(
            (m) => m.prepare(It.isValue(`SELECT * FROM col WHERE a=? AND b=?`)),
            Times.once()
          );
          done();
        })
        .catch((err) => fail(err));
    });
  }


(done) => {
      testObject
        .getRecordsFromCollection('any', {})
        .then(() => fail('Should not get here'))
        .catch((err: Error) => {
          expect(err).toBeTruthy();
          done();
        });
    }


(done) => {
      const expectedError = 'ERROR';
      mockStatement
        .setup((m) => m.all(It.isAny(), It.isAny()))
        .callback((_: unknown, cb: (err: Error) => void) => {
          cb(new Error(expectedError));
        });

      testObject.dbInstance = mockSqlite.object;

      testObject
        .getRecordsFromCollection('any', {})
        .then(() => fail('Should not get here'))
        .catch((err: Error) => {
          expect(err.message).toBe(expectedError);
          done();
        });
    }


(m) => m.all(It.isAny(), It.isAny())


(_: unknown, cb: (err: Error) => void) => {
          cb(new Error(expectedError));
        }


(err: Error) => {
          expect(err.message).toBe(expectedError);
          done();
        }


(done) => {
      const expectedCollection = 'myCollection';
      const mockRows = [{ id: 0 }, { id: 1 }];
      mockStatement
        .setup((m) => m.all(It.isAny(), It.isAny()))
        .callback(
          (_: unknown, cb: (err: Error, rows: KeyedObject[]) => void) => {
            cb(null, mockRows);
          }
        );

      testObject.dbInstance = mockSqlite.object;

      testObject
        .getRecordsFromCollection<KeyedObject>(expectedCollection, {})
        .then((records: KeyedObject[]) => {
          mockSqlite.verify(
            (m) => m.prepare(It.isValue(`SELECT * FROM ${expectedCollection}`)),
            Times.once()
          );
          expect(records).toEqual(mockRows);
          done();
        })
        .catch((err) => fail(err));
    }


(_: unknown, cb: (err: Error, rows: KeyedObject[]) => void) => {
            cb(null, mockRows);
          }


(records: KeyedObject[]) => {
          mockSqlite.verify(
            (m) => m.prepare(It.isValue(`SELECT * FROM ${expectedCollection}`)),
            Times.once()
          );
          expect(records).toEqual(mockRows);
          done();
        }


(m) => m.prepare(It.isValue(`SELECT * FROM ${expectedCollection}`))


(done) => {
      const filter = {
        where: [
          { field: 'a', value: 'a' },
          { field: 'b', value: 'b' }
        ]
      };
      mockStatement
        .setup((m) => m.all(It.isAny(), It.isAny()))
        .callback(
          (_: unknown, cb: (err: Error, rows: KeyedObject[]) => void) => {
            cb(null, []);
          }
        );

      testObject.dbInstance = mockSqlite.object;

      testObject
        .getRecordsFromCollection('col', filter)
        .then(() => {
          mockSqlite.verify(
            (m) => m.prepare(It.isValue(`SELECT * FROM col WHERE a=? AND b=?`)),
            Times.once()
          );
          done();
        })
        .catch((err) => fail(err));
    }


(_: unknown, cb: (err: Error, rows: KeyedObject[]) => void) => {
            cb(null, []);
          }


() => {
          mockSqlite.verify(
            (m) => m.prepare(It.isValue(`SELECT * FROM col WHERE a=? AND b=?`)),
            Times.once()
          );
          done();
        }


(m) => m.prepare(It.isValue(`SELECT * FROM col WHERE a=? AND b=?`))


() => {
    beforeEach(() => {
      testObject.dbInstance = mockSqlite.object;
    });

    it('should fix field keys that do not have $-prefix keys', (done) => {
      let lastQueryObject: KeyedObject;

      const fields = {
        bad: 'key'
      };

      mockSqlite
        .setup((m) => m.run(It.isAny(), It.isAny(), It.isAny()))
        .callback(
          (_: string, params: KeyedObject, cb: (err: Error) => void) => {
            lastQueryObject = params;
            cb(null);
          }
        );

      testObject.insertRecordsToCollection('anytable', fields).then(() => {
        const keys = Object.keys(lastQueryObject);
        expect(keys.every((key) => key.startsWith('$'))).toBeTrue();
        done();
      });
    });

    it('should format the input objects into a SQL prepared statement', (done) => {
      const mockTable = 'anyTable';

      const fields = {
        $product: 'a sample',
        $quantity: 4
      };

      mockSqlite
        .setup((m) => m.run(It.isAny(), It.isAny(), It.isAny()))
        .callback((tb: string, _: unknown, cb: (err: Error) => void) => {
          expect(tb).toContain(`INSERT INTO ${mockTable}`);
          cb(null);
        });

      testObject.insertRecordsToCollection(mockTable, fields).then(() => {
        mockSqlite.verify(
          (m) => m.run(It.isAnyString(), It.isObjectWith(fields), It.isAny()),
          Times.once()
        );

        done();
      });
    });
  }


() => {
      testObject.dbInstance = mockSqlite.object;
    }


(done) => {
      let lastQueryObject: KeyedObject;

      const fields = {
        bad: 'key'
      };

      mockSqlite
        .setup((m) => m.run(It.isAny(), It.isAny(), It.isAny()))
        .callback(
          (_: string, params: KeyedObject, cb: (err: Error) => void) => {
            lastQueryObject = params;
            cb(null);
          }
        );

      testObject.insertRecordsToCollection('anytable', fields).then(() => {
        const keys = Object.keys(lastQueryObject);
        expect(keys.every((key) => key.startsWith('$'))).toBeTrue();
        done();
      });
    }


(m) => m.run(It.isAny(), It.isAny(), It.isAny())


(_: string, params: KeyedObject, cb: (err: Error) => void) => {
            lastQueryObject = params;
            cb(null);
          }


() => {
        const keys = Object.keys(lastQueryObject);
        expect(keys.every((key) => key.startsWith('$'))).toBeTrue();
        done();
      }


(key) => key.startsWith('$')


(done) => {
      const mockTable = 'anyTable';

      const fields = {
        $product: 'a sample',
        $quantity: 4
      };

      mockSqlite
        .setup((m) => m.run(It.isAny(), It.isAny(), It.isAny()))
        .callback((tb: string, _: unknown, cb: (err: Error) => void) => {
          expect(tb).toContain(`INSERT INTO ${mockTable}`);
          cb(null);
        });

      testObject.insertRecordsToCollection(mockTable, fields).then(() => {
        mockSqlite.verify(
          (m) => m.run(It.isAnyString(), It.isObjectWith(fields), It.isAny()),
          Times.once()
        );

        done();
      });
    }


(tb: string, _: unknown, cb: (err: Error) => void) => {
          expect(tb).toContain(`INSERT INTO ${mockTable}`);
          cb(null);
        }


() => {
        mockSqlite.verify(
          (m) => m.run(It.isAnyString(), It.isObjectWith(fields), It.isAny()),
          Times.once()
        );

        done();
      }


(m) => m.run(It.isAnyString(), It.isObjectWith(fields), It.isAny())


() => {
    beforeEach(() => {
      testObject.dbInstance = mockSqlite.object;
    });

    it('should fix field keys that do not have $-prefix', (done) => {
      let lastQueryObject: KeyedObject;

      const fields = {
        bad: 'key'
      };

      const where = {
        $key: 'value'
      };

      mockSqlite
        .setup((m) => m.run(It.isAny(), It.isAny(), It.isAny()))
        .callback(
          (_: string, params: KeyedObject, cb: (err: Error) => void) => {
            lastQueryObject = params;
            cb(null);
          }
        );

      testObject
        .updateRecordsInCollection('anytable', fields, where)
        .then(() => {
          const keys = Object.keys(lastQueryObject);
          expect(keys.every((key) => key.startsWith('$'))).toBeTrue();
          done();
        });
    });

    it('should fix where clause keys that do not have $-prefix', (done) => {
      let lastQueryObject: KeyedObject;

      const fields = {
        $key: 'value'
      };

      const where = {
        bad: 'key'
      };

      mockSqlite
        .setup((m) => m.run(It.isAny(), It.isAny(), It.isAny()))
        .callback(
          (_: string, params: KeyedObject, cb: (err: Error) => void) => {
            lastQueryObject = params;
            cb(null);
          }
        );

      testObject
        .updateRecordsInCollection('anytable', fields, where)
        .then(() => {
          const keys = Object.keys(lastQueryObject);
          expect(keys.every((key) => key.startsWith('$'))).toBeTrue();
          done();
        });
    });

    it('should format the input objects into a SQL prepared statement', (done) => {
      const mockTable = 'anyTable';

      const fields = {
        $product: 'a sample',
        $quantity: 4
      };

      const where = {
        $id: '12345id'
      };

      mockSqlite
        .setup((m) => m.run(It.isAny(), It.isAny(), It.isAny()))
        .callback((tb: string, _: unknown, cb: (err: Error) => void) => {
          expect(tb).toContain(`UPDATE ${mockTable}`);
          cb(null);
        });

      testObject
        .updateRecordsInCollection(mockTable, fields, where)
        .then(() => {
          mockSqlite.verify(
            (m) =>
              m.run(
                It.isAnyString(),
                It.isObjectWith({ ...fields, ...where }),
                It.isAny()
              ),
            Times.once()
          );

          done();
        });
    });

    it('should reject if query raises an error', (done) => {
      const fields = {
        $key: 'value'
      };

      const where = {
        $any: 'key'
      };

      mockSqlite
        .setup((m) => m.run(It.isAny(), It.isAny(), It.isAny()))
        .callback((_: unknown, __: unknown, cb: (err: Error) => void) => {
          cb(new Error('Hello I am a mock error'));
        });

      testObject
        .updateRecordsInCollection('anytable', fields, where)
        .then(() => fail('Query errored but wrapper did not handle'))
        .catch((err) => {
          expect(err).toBeTruthy();
          done();
        });
    });
  }


(done) => {
      let lastQueryObject: KeyedObject;

      const fields = {
        bad: 'key'
      };

      const where = {
        $key: 'value'
      };

      mockSqlite
        .setup((m) => m.run(It.isAny(), It.isAny(), It.isAny()))
        .callback(
          (_: string, params: KeyedObject, cb: (err: Error) => void) => {
            lastQueryObject = params;
            cb(null);
          }
        );

      testObject
        .updateRecordsInCollection('anytable', fields, where)
        .then(() => {
          const keys = Object.keys(lastQueryObject);
          expect(keys.every((key) => key.startsWith('$'))).toBeTrue();
          done();
        });
    }


() => {
          const keys = Object.keys(lastQueryObject);
          expect(keys.every((key) => key.startsWith('$'))).toBeTrue();
          done();
        }


(done) => {
      let lastQueryObject: KeyedObject;

      const fields = {
        $key: 'value'
      };

      const where = {
        bad: 'key'
      };

      mockSqlite
        .setup((m) => m.run(It.isAny(), It.isAny(), It.isAny()))
        .callback(
          (_: string, params: KeyedObject, cb: (err: Error) => void) => {
            lastQueryObject = params;
            cb(null);
          }
        );

      testObject
        .updateRecordsInCollection('anytable', fields, where)
        .then(() => {
          const keys = Object.keys(lastQueryObject);
          expect(keys.every((key) => key.startsWith('$'))).toBeTrue();
          done();
        });
    }


(done) => {
      const mockTable = 'anyTable';

      const fields = {
        $product: 'a sample',
        $quantity: 4
      };

      const where = {
        $id: '12345id'
      };

      mockSqlite
        .setup((m) => m.run(It.isAny(), It.isAny(), It.isAny()))
        .callback((tb: string, _: unknown, cb: (err: Error) => void) => {
          expect(tb).toContain(`UPDATE ${mockTable}`);
          cb(null);
        });

      testObject
        .updateRecordsInCollection(mockTable, fields, where)
        .then(() => {
          mockSqlite.verify(
            (m) =>
              m.run(
                It.isAnyString(),
                It.isObjectWith({ ...fields, ...where }),
                It.isAny()
              ),
            Times.once()
          );

          done();
        });
    }


(tb: string, _: unknown, cb: (err: Error) => void) => {
          expect(tb).toContain(`UPDATE ${mockTable}`);
          cb(null);
        }


() => {
          mockSqlite.verify(
            (m) =>
              m.run(
                It.isAnyString(),
                It.isObjectWith({ ...fields, ...where }),
                It.isAny()
              ),
            Times.once()
          );

          done();
        }


(m) =>
              m.run(
                It.isAnyString(),
                It.isObjectWith({ ...fields, ...where }),
                It.isAny()
              )


(done) => {
      const fields = {
        $key: 'value'
      };

      const where = {
        $any: 'key'
      };

      mockSqlite
        .setup((m) => m.run(It.isAny(), It.isAny(), It.isAny()))
        .callback((_: unknown, __: unknown, cb: (err: Error) => void) => {
          cb(new Error('Hello I am a mock error'));
        });

      testObject
        .updateRecordsInCollection('anytable', fields, where)
        .then(() => fail('Query errored but wrapper did not handle'))
        .catch((err) => {
          expect(err).toBeTruthy();
          done();
        });
    }


(_: unknown, __: unknown, cb: (err: Error) => void) => {
          cb(new Error('Hello I am a mock error'));
        }


() => fail('Query errored but wrapper did not handle')


(err) => {
          expect(err).toBeTruthy();
          done();
        }


class TestableSqliteWrapper extends SqliteWrapper {
  public set dbInstance(value: any) {
    this.db = value;
  }

  public get dbInstance() {
    return this.db;
  }
}


close(cb: () => void) {
          cb();
        }


close(cb: (err: Error) => void) {
          cb(new Error(expectedError));
        }


function quickValidAsyncValidator<T extends IModel>(manager: IModelManager, model: T, field: Field, operation: IModelOperation, result: ModelValidationResult) {
    return new Promise<void>((resolve, reject) => {
        resolve();
    });
}


function quickInvalidAsyncValidator<T extends IModel>(manager: IModelManager, model: T, field: Field, operation: IModelOperation, result: ModelValidationResult) {
    return new Promise<void>((resolve, reject) => {
        result.addFieldError('name', 'name field is invalid');
        resolve();
    });
}


function slowInvalidAsyncValidator<T extends IModel>(manager: IModelManager, model: T, field: Field, operation: IModelOperation, result: ModelValidationResult) {
    return new Promise<void>((resolve, reject) => {
        setTimeout(() => {
            result.addFieldError('name', 'name field is invalid');
            resolve();
        }, 8000);
    });
}


(resolve, reject) => {
        resolve();
    }


(resolve, reject) => {
        result.addFieldError('name', 'name field is invalid');
        resolve();
    }


(resolve, reject) => {
        setTimeout(() => {
            result.addFieldError('name', 'name field is invalid');
            resolve();
        }, 8000);
    }


() => {
            result.addFieldError('name', 'name field is invalid');
            resolve();
        }


() => {
    let testOp: IModelOperation = {
        operationName: 'create'
    };

    describe('Field - constructor()', () => {

        it('creates a field with properties as expected', () => {
            let opts: IFieldOptions = {
                required: true,
                stored: true
            };
            let test = new Field('name', opts);
            expect(test.name).to.equal('name');
            expect(test.options).to.deep.equal(opts);
        });

        it('cannot be created without a name', () => {
            expect(() => {
                new Field(undefined as any, undefined);
            }).to.throw('new fields must have a name');
        });

        it('sets default field options if they are not specified', () => {
            let test = new Field('name');
            expect(test.options).to.deep.equal(DEFAULT_FIELD_OPTIONS);
        });

        it('throws an error if options is not an object', () => {
            expect(() => {
                new Field('name', (() => '33') as any);
            }).to.throw('the options parameter must be an object');
        });

        it('adds the "required" validator if options.required is true', () => {
            let test = new Field('name', { required: true });
            expect(test.validators[0]).to.equal(requiredValidator);
        });

        it('adds the "required" validator if options.required is not specified', () => {
            let test = new Field('name', { });
            expect(test.validators[0]).to.equal(requiredValidator);
        });

        it('does not add any validators if options.required is false', () => {
            let test = new Field('name', { required: false });
            expect(test.validators.length).to.equal(0);
        });

    });

    describe('Field - validate()', () => {
        let testModel: TestModel;
        let result: ModelValidationResult;

        beforeEach(() => {
            testModel = new TestModel();
            testModel.name = null;
            result = new ModelValidationResult();
        });

        it('returns a resolved promise when validation completes - no validators', () => {
            let test = new Field('name', { required: false });
            return test.validate(models, testModel, testOp, result)
            .then((res) => { expect(res.valid).to.be.true; });
        });

        it('returns a resolved promise when validation completes - required validator', () => {
            let test = new Field('name', { required: true });
            testModel.name = 'Frank';
            return test.validate(models, testModel, testOp, result)
            .then((res) => { expect(res.valid).to.be.true; });
        });

        it('validation fails as expected when required field not set', () => {
            let test = new Field('name', { required: true });
            return test.validate(models, testModel, testOp, result)
            .then((res) => { expect(res.valid).to.be.false; });
        });

        it('returns valid = true when validation completes with a valid async validator', () => {
            let test = new Field('name', { required: false });
            test.asyncValidators.push(quickValidAsyncValidator);
            return test.validate(models, testModel, testOp, result)
            .then((res) => { expect(res.valid).to.be.true; });
        });

        it('returns valid = false when validation completes with an invalid async validator', () => {
            let test = new Field('name', { required: false });
            test.asyncValidators.push(quickInvalidAsyncValidator);
            return test.validate(models, testModel, testOp, result)
            .then((res) => { expect(res.valid).to.be.false; });
        });

        it('returns valid = false when validation completes with a valid and an invalid async validator', () => {
            let test = new Field('name', { required: false });
            test.asyncValidators.push(quickValidAsyncValidator);
            test.asyncValidators.push(quickInvalidAsyncValidator);
            return test.validate(models, testModel, testOp, result)
            .then((res) => { expect(res.valid).to.be.false; });
        });

        it('returns a rejected promise when async validation times out', () => {
            let test = new Field('name', { required: false });
            test.asyncValidators.push(slowInvalidAsyncValidator);
            return test.validate(models, testModel, testOp, result, {
                    timeout: 100
                })
                .then(() => { throw new Error('expected to reject'); })
                .catch((err) => {
                    expect(err.message).to.contain('timed out');
                });
        });

    });

}


() => {

        it('creates a field with properties as expected', () => {
            let opts: IFieldOptions = {
                required: true,
                stored: true
            };
            let test = new Field('name', opts);
            expect(test.name).to.equal('name');
            expect(test.options).to.deep.equal(opts);
        });

        it('cannot be created without a name', () => {
            expect(() => {
                new Field(undefined as any, undefined);
            }).to.throw('new fields must have a name');
        });

        it('sets default field options if they are not specified', () => {
            let test = new Field('name');
            expect(test.options).to.deep.equal(DEFAULT_FIELD_OPTIONS);
        });

        it('throws an error if options is not an object', () => {
            expect(() => {
                new Field('name', (() => '33') as any);
            }).to.throw('the options parameter must be an object');
        });

        it('adds the "required" validator if options.required is true', () => {
            let test = new Field('name', { required: true });
            expect(test.validators[0]).to.equal(requiredValidator);
        });

        it('adds the "required" validator if options.required is not specified', () => {
            let test = new Field('name', { });
            expect(test.validators[0]).to.equal(requiredValidator);
        });

        it('does not add any validators if options.required is false', () => {
            let test = new Field('name', { required: false });
            expect(test.validators.length).to.equal(0);
        });

    }


() => {
            let opts: IFieldOptions = {
                required: true,
                stored: true
            };
            let test = new Field('name', opts);
            expect(test.name).to.equal('name');
            expect(test.options).to.deep.equal(opts);
        }


() => {
            expect(() => {
                new Field(undefined as any, undefined);
            }).to.throw('new fields must have a name');
        }


() => {
                new Field(undefined as any, undefined);
            }


() => {
            let test = new Field('name');
            expect(test.options).to.deep.equal(DEFAULT_FIELD_OPTIONS);
        }


() => {
            expect(() => {
                new Field('name', (() => '33') as any);
            }).to.throw('the options parameter must be an object');
        }


() => {
                new Field('name', (() => '33') as any);
            }


() => '33'


() => {
            let test = new Field('name', { required: true });
            expect(test.validators[0]).to.equal(requiredValidator);
        }


() => {
            let test = new Field('name', { });
            expect(test.validators[0]).to.equal(requiredValidator);
        }


() => {
            let test = new Field('name', { required: false });
            expect(test.validators.length).to.equal(0);
        }


() => {
        let testModel: TestModel;
        let result: ModelValidationResult;

        beforeEach(() => {
            testModel = new TestModel();
            testModel.name = null;
            result = new ModelValidationResult();
        });

        it('returns a resolved promise when validation completes - no validators', () => {
            let test = new Field('name', { required: false });
            return test.validate(models, testModel, testOp, result)
            .then((res) => { expect(res.valid).to.be.true; });
        });

        it('returns a resolved promise when validation completes - required validator', () => {
            let test = new Field('name', { required: true });
            testModel.name = 'Frank';
            return test.validate(models, testModel, testOp, result)
            .then((res) => { expect(res.valid).to.be.true; });
        });

        it('validation fails as expected when required field not set', () => {
            let test = new Field('name', { required: true });
            return test.validate(models, testModel, testOp, result)
            .then((res) => { expect(res.valid).to.be.false; });
        });

        it('returns valid = true when validation completes with a valid async validator', () => {
            let test = new Field('name', { required: false });
            test.asyncValidators.push(quickValidAsyncValidator);
            return test.validate(models, testModel, testOp, result)
            .then((res) => { expect(res.valid).to.be.true; });
        });

        it('returns valid = false when validation completes with an invalid async validator', () => {
            let test = new Field('name', { required: false });
            test.asyncValidators.push(quickInvalidAsyncValidator);
            return test.validate(models, testModel, testOp, result)
            .then((res) => { expect(res.valid).to.be.false; });
        });

        it('returns valid = false when validation completes with a valid and an invalid async validator', () => {
            let test = new Field('name', { required: false });
            test.asyncValidators.push(quickValidAsyncValidator);
            test.asyncValidators.push(quickInvalidAsyncValidator);
            return test.validate(models, testModel, testOp, result)
            .then((res) => { expect(res.valid).to.be.false; });
        });

        it('returns a rejected promise when async validation times out', () => {
            let test = new Field('name', { required: false });
            test.asyncValidators.push(slowInvalidAsyncValidator);
            return test.validate(models, testModel, testOp, result, {
                    timeout: 100
                })
                .then(() => { throw new Error('expected to reject'); })
                .catch((err) => {
                    expect(err.message).to.contain('timed out');
                });
        });

    }


() => {
            testModel = new TestModel();
            testModel.name = null;
            result = new ModelValidationResult();
        }


() => {
            let test = new Field('name', { required: false });
            return test.validate(models, testModel, testOp, result)
            .then((res) => { expect(res.valid).to.be.true; });
        }


(res) => { expect(res.valid).to.be.true; }


() => {
            let test = new Field('name', { required: true });
            testModel.name = 'Frank';
            return test.validate(models, testModel, testOp, result)
            .then((res) => { expect(res.valid).to.be.true; });
        }


() => {
            let test = new Field('name', { required: true });
            return test.validate(models, testModel, testOp, result)
            .then((res) => { expect(res.valid).to.be.false; });
        }


(res) => { expect(res.valid).to.be.false; }


() => {
            let test = new Field('name', { required: false });
            test.asyncValidators.push(quickValidAsyncValidator);
            return test.validate(models, testModel, testOp, result)
            .then((res) => { expect(res.valid).to.be.true; });
        }


() => {
            let test = new Field('name', { required: false });
            test.asyncValidators.push(quickInvalidAsyncValidator);
            return test.validate(models, testModel, testOp, result)
            .then((res) => { expect(res.valid).to.be.false; });
        }


() => {
            let test = new Field('name', { required: false });
            test.asyncValidators.push(quickValidAsyncValidator);
            test.asyncValidators.push(quickInvalidAsyncValidator);
            return test.validate(models, testModel, testOp, result)
            .then((res) => { expect(res.valid).to.be.false; });
        }


() => {
            let test = new Field('name', { required: false });
            test.asyncValidators.push(slowInvalidAsyncValidator);
            return test.validate(models, testModel, testOp, result, {
                    timeout: 100
                })
                .then(() => { throw new Error('expected to reject'); })
                .catch((err) => {
                    expect(err.message).to.contain('timed out');
                });
        }


() => { throw new Error('expected to reject'); }


(err) => {
                    expect(err.message).to.contain('timed out');
                }


class TestModel {
    name: string | null;
}


/**
 * Contains helper methods to generate a HTTP response.
 */
export class ResponseBuilder {
  public static badRequest(code: string, description: string, callback: ApiCallback): void {
    const errorResult: BadRequestResult = new BadRequestResult(code, description);
    ResponseBuilder._returnAs<BadRequestResult>(errorResult, HttpStatusCode.BadRequest, callback);
  }

  public static configurationError(code: string, description: string, callback: ApiCallback): void {
    const errorResult: ConfigurationErrorResult = new ConfigurationErrorResult(code, description);
    ResponseBuilder._returnAs<ConfigurationErrorResult>(errorResult, HttpStatusCode.ConfigurationError, callback);
  }

  public static forbidden(code: string, description: string, callback: ApiCallback): void {
    const errorResult: ForbiddenResult = new ForbiddenResult(code, description);
    ResponseBuilder._returnAs<ForbiddenResult>(errorResult, HttpStatusCode.Forbidden, callback);
  }

  public static internalServerError(error: Error, callback: ApiCallback): void {
    console.log('INTERNAL SERVER ERROR', error);  // tslint:disable-line no-console (Temporary implementation.)
    const errorResult: InternalServerErrorResult = new InternalServerErrorResult(ErrorCode.GeneralError, 'Sorry...');
    ResponseBuilder._returnAs<InternalServerErrorResult>(errorResult, HttpStatusCode.InternalServerError, callback);
  }

  public static notFound(code: string, description: string, callback: ApiCallback): void {
    const errorResult: NotFoundResult = new NotFoundResult(code, description);
    ResponseBuilder._returnAs<NotFoundResult>(errorResult, HttpStatusCode.NotFound, callback);
  }

  public static ok<T>(result: T, callback: ApiCallback): void {
    ResponseBuilder._returnAs<T>(result, HttpStatusCode.Ok, callback);
  }

  private static _returnAs<T>(result: T, statusCode: number, callback: ApiCallback): void {
    const bodyObject: ErrorResponseBody | T = result instanceof ErrorResult
      ? { error: result }
      : result;
    const response: ApiResponse = {
      body: JSON.stringify(bodyObject),
      headers: {
        'Access-Control-Allow-Origin': '*'  // This is required to make CORS work with AWS API Gateway Proxy Integration.
      },
      statusCode
    };

    callback(undefined, response);
  }
}


public static badRequest(code: string, description: string, callback: ApiCallback): void {
    const errorResult: BadRequestResult = new BadRequestResult(code, description);
    ResponseBuilder._returnAs<BadRequestResult>(errorResult, HttpStatusCode.BadRequest, callback);
  }


public static configurationError(code: string, description: string, callback: ApiCallback): void {
    const errorResult: ConfigurationErrorResult = new ConfigurationErrorResult(code, description);
    ResponseBuilder._returnAs<ConfigurationErrorResult>(errorResult, HttpStatusCode.ConfigurationError, callback);
  }


public static forbidden(code: string, description: string, callback: ApiCallback): void {
    const errorResult: ForbiddenResult = new ForbiddenResult(code, description);
    ResponseBuilder._returnAs<ForbiddenResult>(errorResult, HttpStatusCode.Forbidden, callback);
  }


public static internalServerError(error: Error, callback: ApiCallback): void {
    console.log('INTERNAL SERVER ERROR', error);  // tslint:disable-line no-console (Temporary implementation.)
    const errorResult: InternalServerErrorResult = new InternalServerErrorResult(ErrorCode.GeneralError, 'Sorry...');
    ResponseBuilder._returnAs<InternalServerErrorResult>(errorResult, HttpStatusCode.InternalServerError, callback);
  }


public static notFound(code: string, description: string, callback: ApiCallback): void {
    const errorResult: NotFoundResult = new NotFoundResult(code, description);
    ResponseBuilder._returnAs<NotFoundResult>(errorResult, HttpStatusCode.NotFound, callback);
  }


public static ok<T>(result: T, callback: ApiCallback): void {
    ResponseBuilder._returnAs<T>(result, HttpStatusCode.Ok, callback);
  }


private static _returnAs<T>(result: T, statusCode: number, callback: ApiCallback): void {
    const bodyObject: ErrorResponseBody | T = result instanceof ErrorResult
      ? { error: result }
      : result;
    const response: ApiResponse = {
      body: JSON.stringify(bodyObject),
      headers: {
        'Access-Control-Allow-Origin': '*'  // This is required to make CORS work with AWS API Gateway Proxy Integration.
      },
      statusCode
    };

    callback(undefined, response);
  }


function serializeAccount(account: Account): string {
  return JSON.stringify(
    {
      ClientPublicKey: uint8ArrayToHexString(account.publicKey),
      ClientPrivateKey: uint8ArrayToHexString(account.privateKey),
      ClientAddress: account.address
    },
    null,
    2
  );
}


function deserializeAccount(str: string): Account {
  const asJson = JSON.parse(str);
  return {
    publicKey: hexStringToUint8Array(asJson.ClientPublicKey),
    privateKey: hexStringToUint8Array(asJson.ClientPrivateKey),
    address: asJson.ClientAddress
  };
}


function uint8ArrayToHexString(arr: Uint8Array): string {
  return '0x' + Buffer.from(arr).toString('hex');
}


function hexStringToUint8Array(str: string): Uint8Array {
  str = str.replace(/^0x/i, '');
  return Uint8Array.from(Buffer.from(str, 'hex'));
}


export function generateRandomAccount(): string {
  const newAccount = createAccount();
  return newAccount.address;
}


export function generateMyAccount(): Account {
  const myNewAccount = createAccount();
  localStorage.setItem('my-orbs-account', serializeAccount(myNewAccount));
  return getMyAccount();
}


export function getMyAccount(): Account {
  let asStr = localStorage.getItem('my-orbs-account');
  return asStr ? deserializeAccount(asStr) : generateMyAccount();
}


() => {
  return (
    <style>
      {`
        @keyframes react_simple_image_video_spinner {
            0% {
                  transform: translate3d(-50%, -50%, 0) rotate(0deg);
                }
            100% {
                  transform: translate3d(-50%, -50%, 0) rotate(360deg);
                }
              }

              .react-lightbox-component-icon-hover {
                background-color: rgba(119, 119, 119, .1);
                border-radius: 100%;
              }
              .react-lightbox-component-icon-hover:hover {
                background-color: rgba(119, 119, 119, .6);

              }

              .react-lightbox-component-icon-right {
                right: 0px;
              }
              .react-lightbox-component-icon-left {
                left: 10px;
              }
              @media (min-width: 768px) {
                .react-lightbox-component-icon-right {
                  right: 10px;
                }
                .react-lightbox-component-icon-left {
                  left: 10px;
                }
              }

                `}


({
  name,
  label,
  icon,
  defaultWindowPosition,
  defaultShortcutPosition,
  children,
}) => {
  const { isOpen, toggle, onClose } = useWindow(name);
  const { storeShortcutCoords, saveShortcutPosition } = useShortcut(name, defaultShortcutPosition);

  return (
    <>
      <Window isOpen={isOpen} name={name} label={label} onClose={onClose} defaultPosition={defaultWindowPosition}>
        <ApplicationErrorBoundary>{children}</ApplicationErrorBoundary>
      </Window>
      <Shortcut
        label={label}
        top={storeShortcutCoords.top}
        left={storeShortcutCoords.left}
        toggle={toggle}
        saveShortcutPosition={saveShortcutPosition}
      >
        {icon}
      </Shortcut>
    </>


interface ApplicationProps {
  name: Apps;
  label: string;
  icon: ReactNode;
  defaultWindowPosition: Position;
  defaultShortcutPosition: Position;
}


newEndpoint => {
  endpoint = newEndpoint;
}


newToken => {
  authToken = newToken;
}


x => x.length > 0


x => {
    const batchBody = x.map(arm => {
      return {
        httpMethod: arm.method,
        content: arm.body,
        requestHeaderDetails: {
          commandName: arm.commandName,
        },
        url: Url.appendQueryString(`${arm.resourceId}${arm.queryString || ''}`, `api-version=${arm.apiVersion}`),
      };
    });
    return from(
      makeArmRequest<ArmBatchResponse>({
        method: 'POST',
        resourceId: '/batch',
        body: { requests: batchBody },
        apiVersion: CommonConstants.ApiVersions.armBatchApi,
        id: '',
      })
    ).pipe(
      concatMap(result => {
        const { responses } = result.data;
        const responsesWithId: ArmBatchObject[] = [];
        for (let i = 0; i < responses.length; i = i + 1) {
          responsesWithId.push({ ...responses[i], id: x[i].id });
        }
        return from(responsesWithId);
      })
    );
  }


arm => {
      return {
        httpMethod: arm.method,
        content: arm.body,
        requestHeaderDetails: {
          commandName: arm.commandName,
        },
        url: Url.appendQueryString(`${arm.resourceId}${arm.queryString || ''}`, `api-version=${arm.apiVersion}`),
      };
    }


result => {
        const { responses } = result.data;
        const responsesWithId: ArmBatchObject[] = [];
        for (let i = 0; i < responses.length; i = i + 1) {
          responsesWithId.push({ ...responses[i], id: x[i].id });
        }
        return from(responsesWithId);
      }


async <T>(armObj: InternalArmRequest): Promise<AxiosResponse<T>> => {
  const { method, resourceId, body, apiVersion, queryString } = armObj;
  const url = Url.appendQueryString(`${endpoint}${resourceId}${queryString || ''}`, `api-version=${apiVersion}`);
  try {
    const result = await axios({
      url,
      method,
      data: body,
      headers: {
        Authorization: `Bearer ${authToken}`,
      },
      validateStatus: () => true, // never throw on an error, we can check the status and handle the error in the UI
    });
    return result;
  } catch (err) {
    // This shouldn't be hit since we're telling axios to not throw on error
    LogService.error('ArmHelper', 'makeArmRequest', err);
    throw err;
  }
}


async <T>(requestObject: ArmRequestObject<T>): Promise<HttpResponseObject<T>> => {
  const { skipBuffer, method, resourceId, body, apiVersion, commandName, queryString } = requestObject;

  const id = Guid.newGuid();
  const armBatchObject: InternalArmRequest = {
    resourceId,
    body,
    commandName,
    queryString,
    id,
    method: method || 'GET',
    apiVersion: apiVersion || CommonConstants.ApiVersions.websiteApiVersion20180201,
  };

  if (!skipBuffer && !alwaysSkipBatch) {
    const fetchFromBatch = new Promise<ArmBatchObject>((resolve, reject) => {
      armObs$
        .pipe(
          filter(x => x.id === id),
          take(1)
        )
        .subscribe(x => {
          resolve(x);
        });
      armSubject$.next(armBatchObject);
    });
    const res = await fetchFromBatch;
    const resSuccess = res.httpStatusCode < 300;
    const ret: HttpResponseObject<T> = {
      metadata: {
        success: resSuccess,
        status: res.httpStatusCode,
        headers: res.headers,
        error: resSuccess ? null : res.content,
      },
      data: resSuccess ? res.content : null,
    };
    return ret;
  }
  const response = await makeArmRequest<T>(armBatchObject);
  const responseSuccess = response.status < 300;
  const retObj: HttpResponseObject<T> = {
    metadata: {
      success: responseSuccess,
      status: response.status,
      headers: response.headers,
      error: responseSuccess ? null : response.data,
    },
    data: response.data,
  };
  return retObj;
}


(resolve, reject) => {
      armObs$
        .pipe(
          filter(x => x.id === id),
          take(1)
        )
        .subscribe(x => {
          resolve(x);
        });
      armSubject$.next(armBatchObject);
    }


x => x.id === id


x => {
          resolve(x);
        }


interface InternalArmRequest {
  method: MethodTypes;
  resourceId: string;
  id: string;
  commandName?: string;
  body: any;
  apiVersion: string;
  queryString?: string;
}


interface ArmBatchObject {
  httpStatusCode: number;
  headers: { [key: string]: string };
  contentLength: number;
  content: any;
  id?: string;
}


interface ArmBatchResponse {
  responses: ArmBatchObject[];
}


@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.sass']
})
export class HeaderComponent implements OnInit {

  constructor(
    private _authService: AuthenticationService,
    private _router: Router
  ) { }

  ngOnInit() {
  }

  handleLogout() {
    this._authService.disconnect();
    this._router.navigate(['/auth']);
  }
}


handleLogout() {
    this._authService.disconnect();
    this._router.navigate(['/auth']);
  }


({
  visible,
  onRequestClose,
  onSubmit,
}: IPlaylistGroupInputModalProps) => {
  const {
    control,
    handleSubmit,
    setValue,
    formState: { errors },
    reset,
  } = useForm<PlaylistGroupInputFormData>();

  const onUse = (data: PlaylistGroupInputFormData) => {
    if (onSubmit) {
      onSubmit(data.playlistGroupId);
    }
    reset();
  };

  let playlistGroupIdErrorMessage: string | undefined;
  if (errors.playlistGroupId) {
    if (errors.playlistGroupId.type === 'pattern') {
      playlistGroupIdErrorMessage = 'Please enter correct playlist group id';
    } else {
      playlistGroupIdErrorMessage = 'Please enter playlist group id';
    }
  }

  return (
    <Modal
      animationType="fade"
      transparent={true}
      visible={visible}
      onRequestClose={()


(data: PlaylistGroupInputFormData) => {
    if (onSubmit) {
      onSubmit(data.playlistGroupId);
    }
    reset();
  }


export interface IPlaylistGroupInputModalProps {
  visible: boolean;
  onRequestClose?: () => void;
  onSubmit?: (playlistGroupId: string) => void;
}


type PlaylistGroupInputFormData = {
  playlistGroupId: string;
};


handleSubmit(onUse)


export default function (directories: Directories | string, port?: number): Promise<void>;


export interface Directories {
        production: string;
        development: string;
    }


page => {
        // only the existence of a plp component tells us if products
        // are rendered or if this is an ordinary content page
        if (this.hasProductListComponent(page)) {
          return this.productSearchService.getSearchResults().pipe(
            filter(data => data.breadcrumbs && data.breadcrumbs.length > 0),
            switchMap(data =>
              combineLatest([
                this.resolveTitle(data),
                this.resolveBreadcrumbs(data),
              ])
            ),
            map(([title, breadcrumbs]) => ({ title, breadcrumbs }))
          );
        } else {
          return of({
            title: page.title || page.name,
          });
        }
      }


data => data.breadcrumbs && data.breadcrumbs.length > 0


data =>
              combineLatest([
                this.resolveTitle(data),
                this.resolveBreadcrumbs(data),
              ])


([title, breadcrumbs]) => ({ title, breadcrumbs })


key =>
        !!page.slots[key].components.find(
          comp => comp.typeCode === 'CMSProductListComponent'
        )


comp => comp.typeCode === 'CMSProductListComponent'


@Injectable({
  providedIn: 'root',
})
export class CategoryPageMetaResolver extends PageMetaResolver
  implements PageTitleResolver {
  constructor(
    protected routingService: RoutingService,
    protected productSearchService: ProductSearchService,
    protected cms: CmsService
  ) {
    super();
    this.pageType = PageType.CATEGORY_PAGE;
  }

  resolve(): Observable<PageMeta> {
    return this.cms.getCurrentPage().pipe(
      filter(Boolean),
      switchMap(page => {
        // only the existence of a plp component tells us if products
        // are rendered or if this is an ordinary content page
        if (this.hasProductListComponent(page)) {
          return this.productSearchService.getSearchResults().pipe(
            filter(data => data.breadcrumbs && data.breadcrumbs.length > 0),
            switchMap(data =>
              combineLatest([
                this.resolveTitle(data),
                this.resolveBreadcrumbs(data),
              ])
            ),
            map(([title, breadcrumbs]) => ({ title, breadcrumbs }))
          );
        } else {
          return of({
            title: page.title || page.name,
          });
        }
      })
    );
  }

  resolveTitle(data: UIProductSearchPage): Observable<string> {
    return of(
      `${data.pagination.totalResults} results for ${
        data.breadcrumbs[0].facetValueName
      }`
    );
  }

  resolveBreadcrumbs(data: UIProductSearchPage): Observable<any[]> {
    const breadcrumbs = [];
    breadcrumbs.push({ label: 'Home', link: '/' });
    for (const br of data.breadcrumbs) {
      breadcrumbs.push({
        label: br.facetValueName,
        link: '/c/' + br.facetValueCode,
      });
    }
    return of(breadcrumbs);
  }

  private hasProductListComponent(page: Page): boolean {
    // ProductListComponent
    return !!Object.keys(page.slots).find(
      key =>
        !!page.slots[key].components.find(
          comp => comp.typeCode === 'CMSProductListComponent'
        )
    );
  }
}


resolve(): Observable<PageMeta> {
    return this.cms.getCurrentPage().pipe(
      filter(Boolean),
      switchMap(page => {
        // only the existence of a plp component tells us if products
        // are rendered or if this is an ordinary content page
        if (this.hasProductListComponent(page)) {
          return this.productSearchService.getSearchResults().pipe(
            filter(data => data.breadcrumbs && data.breadcrumbs.length > 0),
            switchMap(data =>
              combineLatest([
                this.resolveTitle(data),
                this.resolveBreadcrumbs(data),
              ])
            ),
            map(([title, breadcrumbs]) => ({ title, breadcrumbs }))
          );
        } else {
          return of({
            title: page.title || page.name,
          });
        }
      })
    );
  }


resolveTitle(data: UIProductSearchPage): Observable<string> {
    return of(
      `${data.pagination.totalResults} results for ${
        data.breadcrumbs[0].facetValueName
      }`
    );
  }


resolveBreadcrumbs(data: UIProductSearchPage): Observable<any[]> {
    const breadcrumbs = [];
    breadcrumbs.push({ label: 'Home', link: '/' });
    for (const br of data.breadcrumbs) {
      breadcrumbs.push({
        label: br.facetValueName,
        link: '/c/' + br.facetValueCode,
      });
    }
    return of(breadcrumbs);
  }


private hasProductListComponent(page: Page): boolean {
    // ProductListComponent
    return !!Object.keys(page.slots).find(
      key =>
        !!page.slots[key].components.find(
          comp => comp.typeCode === 'CMSProductListComponent'
        )
    );
  }


export interface DemoEnvironment {
  production: boolean;
  testing: boolean;
  analytics: {
    segment: string;
  };
  firebase: DbxFirebaseOptions;
}


t => t.id === this.currentTemplate


@Component({
	components: {
		AppPopper,
	},
})
export default class AppThemeSelector extends Vue {
	@Prop(Array)
	templates!: SiteTemplate[];

	@Prop(Number)
	currentTemplate!: number;

	current: SiteTemplate | null = null;

	@Watch('currentTemplate')
	onTemplateChange() {
		this.current = this.templates.find(t => t.id === this.currentTemplate) || null;
	}

	created() {
		if (this.currentTemplate) {
			this.onTemplateChange();
		}
	}

	select(id: number) {
		this.$emit('change', id);
		Popper.hideAll();
	}
}


@Watch('currentTemplate')
	onTemplateChange() {
		this.current = this.templates.find(t => t.id === this.currentTemplate) || null;
	}


created() {
		if (this.currentTemplate) {
			this.onTemplateChange();
		}
	}


select(id: number) {
		this.$emit('change', id);
		Popper.hideAll();
	}


() => {
    const brandingConfig = SdkConfig.get().branding;
    let links = [
        //{ "text": "Blog", "url": "https://element.io/blog" },
        //{ "text": "Twitter", "url": "https://twitter.com/element_hq" },
        { "text": "About", "url": "https://schildi.chat" },
        { "text": "GitHub", "url": "https://github.com/SchildiChat/schildichat-desktop" },
    ];

    if (brandingConfig && brandingConfig.authFooterLinks) {
        links = brandingConfig.authFooterLinks;
    }

    const authFooterLinks = [];
    for (const linkEntry of links) {
        authFooterLinks.push(

                { linkEntry.text }
            ,
        );
    }

    return (

            { authFooterLinks }
            { _t('Powered by Matrix') }


_t('Powered by Matrix')


/**
 * Helper to build custom entrance and exit transition
 */
export function cssTransition(props: cssTransitionProps): React.ComponentType;


export class ToastContainer extends React.Component<ToastContainerProps, any> {}


interface Position {
  /**
   * Set the position to `'top-left'`
   */
  TOP_LEFT: 'top-left';

  /**
   * Set the position to `'top-right'`
   */
  TOP_RIGHT: 'top-right';

  /**
   * Set the position to `'top-center'`
   */
  TOP_CENTER: 'top-center';

  /**
   * Set the position to `'bottom-left'`
   */
  BOTTOM_LEFT: 'bottom-left';

  /**
   * Set the position to `'bottom-right'`
   */
  BOTTOM_RIGHT: 'bottom-right';

  /**
   * Set the position to `'bottom-center'`
   */
  BOTTOM_CENTER: 'bottom-center';
}


interface Type {
  /**
   * Set notification type to `'info'`
   */
  INFO: 'info';

  /**
   * Set notification type to `'success'`
   */
  SUCCESS: 'success';

  /**
   * Set notification type to `'warning'`
   */
  WARNING: 'warning';

  /**
   * Set notification type to `'error'`
   */
  ERROR: 'error';

  /**
   * Set notification type to `'default'`
   */
  DEFAULT: 'default';
}


interface cssTransitionProps {
  /**
   * Css class to apply when toast enter
   */
  enter: string;

  /**
   * Css class to apply when toast leave
   */
  exit: string;

  /**
   * Define the duration of the transition in ms
   * `Default: 750`
   */
  duration?: number | Array<number>;

  /**
   * Append current toast position to the classname.
   * For instance `myclass--top-center`...
   * `Default: false`
   */
  appendPosition?: boolean;
}


interface CommonOptions {
  /**
   * Pause the timer when the mouse hover the toast.
   * `Default: true`
   */
  pauseOnHover?: boolean;

  /**
   * Pause the toast when the window loose focus.
   * `Default: true`
   */
  pauseOnFocusLoss?: boolean;

  /**
   * Remove the toast when clicked.
   * `Default: true`
   */
  closeOnClick?: boolean;

  /**
   * Set the delay in ms to close the toast automatically.
   * Use `false` to prevent the toast from closing.
   * `Default: 5000`
   */
  autoClose?: number | false;

  /**
   * Set the default position to use.
   * `One of: 'top-right', 'top-center', 'top-left', 'bottom-right', 'bottom-center', 'bottom-left'`
   * `Default: 'top-right'`
   */
  position?: PositionOptions;

  /**
   * Pass a custom close button.
   * To remove the close button pass `false`
   */
  closeButton?: React.ReactNode | boolean;

  /**
   * An optional css class to set for the progress bar.
   */
  progressClassName?: string | object;

  /**
   * An optional style to set for the progress bar.
   */
  progressStyle?: object;

  /**
   * An optional css class to set.
   */
  className?: string | object;

  /**
   * An optional css class to set for the toast content.
   */
  bodyClassName?: string | object;

  /**
   * Hide or show the progress bar.
   * `Default: false`
   */
  hideProgressBar?: boolean;

  /**
   * Pass a custom transition built with react-transition-group.
   */
  transition?: React.ComponentType;

  /**
   * Allow toast to be draggable
   * `Default: true`
   */
  draggable?: boolean;

  /**
   * The percentage of the toast's width it takes for a drag to dismiss a toast
   * `Default: 80`
   */
  draggablePercent?: number;
}


interface ToastOptions extends CommonOptions {
  /**
   * Called inside componentDidMount.
   */
  onOpen?: () => void;

  /**
   * Called inside componentWillUnMount.
   */
  onClose?: () => void;

  /**
   * Set the toast type.
   * `One of: 'info', 'success', 'warning', 'error', 'default'`
   */
  type?: TypeOptions;

  /**
   * Set a custom `toastId`
   */
  toastId?: ToastId;

  /**
   * Set the percentage for the controlled progress bar. `Value must be between 0 and 1.`
   */
  progress?: number;

  /**
   * Add a delay in ms before the toast appear.
   */
  delay?: number;
}


interface UpdateOptions extends ToastOptions {
  /**
   * Used to update a toast.
   * Pass any valid ReactNode(string, number, component)
   */
  render?: ToastContent;
}


interface ToastContainerProps extends CommonOptions {
  /**
   * Whether or not to display the newest toast on top.
   * `Default: false`
   */
  newestOnTop?: boolean;

  /**
   * An optional inline style to apply.
   */
  style?: object;

  /**
   * An optional css class for the toast.
   */
  toastClassName?: string | object;

  /**
   * Support right to left display.
   * `Default: false`
   */
  rtl?: boolean;
}