text:
import {
  ChangeDetectionStrategy, ChangeDetectorRef, Component, EventEmitter, Input, OnDestroy, OnInit,
  Output, ViewChild
} from '@angular/core';
import { AbstractControl, FormArray, FormControl, FormGroup } from '@angular/forms';
import { StreamDeployService } from '../../stream-deploy.service';
import { map } from 'rxjs/operators';
import { Observable, of } from 'rxjs';
import { StreamDeployValidator } from '../stream-deploy.validator';
import { Properties } from 'spring-flo';
import { NotificationService } from '../../../../shared/service/notification.service';
import { StreamDeployConfig } from '../../../../shared/model/stream.model';
import {
  GroupPropertiesSource, GroupPropertiesSources, PropertiesGroupsDialogComponent
} from '../../../../flo/shared/properties-groups/properties-groups-dialog.component';
import { App } from '../../../../shared/model/app.model';
import { PropertiesDialogComponent } from '../../../../flo/shared/properties/properties-dialog.component';
import { StreamAppPropertiesSource, StreamHead } from '../../../../flo/stream/properties/stream-properties-source';

export class AppPropertiesSource implements StreamAppPropertiesSource {

  private options: Array<any>;
  public confirm = new EventEmitter();

  constructor(options: Array<any>) {
    this.options = options;
  }

  getStreamHead(): StreamHead {
    return { presentStreamNames: [] };
  }

  getProperties(): Promise<Properties.Property[]> {
    return of(this.options).toPromise();
  }

  applyChanges(properties: Properties.Property[]): void {
    this.confirm.emit(properties);
  }

}

@Component({
  selector: 'app-stream-deploy-builder',
  templateUrl: 'builder.component.html',
  styleUrls: ['builder.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class BuilderComponent implements OnInit, OnDestroy {

  @ViewChild('appPropertiesModal', { static: true }) appPropertiesModal: PropertiesDialogComponent;
  @ViewChild('groupsPropertiesModal', { static: true }) groupsPropertiesModal: PropertiesGroupsDialogComponent;

  /**
   * Stream ID
   */
  @Input() id: string;

  /**
   * Emits on destroy component with the current value
   */
  @Output() update = new EventEmitter();

  /**
   * Emit for request export
   */
  @Output() exportProperties = new EventEmitter();

  /**
   * Emit for request deploy
   */
  @Output() deploy = new EventEmitter();

  /**
   * Emit for request copy
   */
  @Output() copyProperties = new EventEmitter();

  /**
   * Properties to load
   */
  @Input() properties: Array<string> = [];

  /**
   * Is Deployed
   */
  @Input() isDeployed = false;

  /**
   * Builder observable
   * Contains the form and the input data
   */
  builder$: Observable<any>;

  /**
   * Builder Reference
   */
  refBuilder;

  /**
   * States
   */
  state: any = {
    platform: true,
    deployer: true,
    app: true,
    specificPlatform: true
  };

  constructor(private streamDeployService: StreamDeployService,
              private changeDetector: ChangeDetectorRef,
              private notificationService: NotificationService) {
  }

  /**
   * On Init
   */
  ngOnInit() {
    this.builder$ = this.streamDeployService
      .config(this.id)
      .pipe(map((streamDeployConfig) => this.build(streamDeployConfig)))
      .pipe(map((builder) => this.populate(builder)))
      .pipe(map((builder) => this.populateApp(builder)));
  }

  /**
   * On Destroy
   */
  ngOnDestroy() {
    if (this.refBuilder) {
      this.update.emit(this.getProperties());
    }
  }

  /**
   * Return an array of properties
   * @returns {Array<string>}
   */
  private getProperties(): Array<string> {
    const result: Array<string> = [];
    const isEmpty = (control: AbstractControl) => !control || (control.value === '' || control.value === null);
    const deployers: FormArray = this.refBuilder.formGroup.get('deployers') as FormArray;
    const appsVersion: FormGroup = this.refBuilder.formGroup.get('appsVersion') as FormGroup;
    const global: FormArray = this.refBuilder.formGroup.get('global') as FormArray;
    const specificPlatform: FormArray = this.refBuilder.formGroup.get('specificPlatform') as FormArray;

    // Platform
    if (!isEmpty(this.refBuilder.formGroup.get('platform'))) {
      result.push(`spring.cloud.dataflow.skipper.platformName=${this.refBuilder.formGroup.get('platform').value}`);
    }

    // Deployers
    this.refBuilder.streamDeployConfig.deployers.forEach((deployer, index) => {
      if (!isEmpty(deployers.controls[index].get('global'))) {
        result.push(`deployer.*.${deployer.id}=${deployers.controls[index].get('global').value}`);
      }
      this.refBuilder.streamDeployConfig.apps.forEach((app) => {
        if (!isEmpty(deployers.controls[index].get(app.name))) {
          result.push(`deployer.${app.name}.${deployer.id}=${deployers.controls[index].get(app.name).value}`);
        }
      });
    });

    // Dynamic Form
    [specificPlatform, global].forEach((arr, index) => {
      const keyStart = (!index) ? 'deployer' : 'app';
      arr.controls.forEach((line: FormGroup) => {
        if (!isEmpty(line.get('property'))) {
          const key = line.get('property').value;
          if (!isEmpty(line.get('global'))) {
            result.push(`${keyStart}.*.${key}=${line.get('global').value}`);
          }
          this.refBuilder.streamDeployConfig.apps.forEach((app) => {
            if (!isEmpty(line.get(app.name))) {
              result.push(`${keyStart}.${app.name}.${key}=${line.get(app.name).value}`);
            }
          });
        }
      });
    });

    // Apps Version (appsVersion)
    this.refBuilder.streamDeployConfig.apps.forEach((app) => {
      if (!isEmpty(appsVersion.get(app.name))) {
        result.push(`version.${app.name}=${appsVersion.get(app.name).value}`);
      }
      // App deployment props set via modal
      this.getDeploymentProperties(this.refBuilder.builderDeploymentProperties, app.name).forEach((keyValue) => {
        result.push(`deployer.${app.name}.${keyValue.key.replace(/spring.cloud.deployer./, '')}=${keyValue.value}`);
      });
    });

    // Apps Properties
    Object.keys(this.refBuilder.builderAppsProperties).forEach((key: string) => {
      this.getAppProperties(this.refBuilder.builderAppsProperties, key).forEach((keyValue) => {
        result.push(`app.${key}.${keyValue.key}=${keyValue.value}`);
      });
    });

    // Global deployment props set via modal
    this.getDeploymentProperties(this.refBuilder.builderDeploymentProperties).forEach((keyValue) => {
      result.push(`deployer.*.${keyValue.key.replace(/spring.cloud.deployer./, '')}=${keyValue.value}`);
    });

    // Errors
    this.refBuilder.errors.global.forEach((error) => {
      result.push(error);
    });
    this.refBuilder.errors.app.forEach((error) => {
      result.push(error);
    });

    return result;
  }

  private updateFormArray(builder, array: FormArray, appKey: string, key: string, value) {
    let group: FormGroup;
    const lines = array.controls
      .filter((formGroup: FormGroup) => key === formGroup.get('property').value);

    if (lines.length > 0) {
      group = lines[0] as FormGroup;
    } else {
      group = new FormGroup({
        property: new FormControl('', [StreamDeployValidator.key]),
        global: new FormControl('')
      }, { validators: StreamDeployValidator.keyRequired });
      builder.streamDeployConfig.apps.forEach((app) => {
        group.addControl(app.name, new FormControl(''));
      });
      array.push(group);
    }
    group.get('property').setValue(key);
    group.get(appKey === '*' ? 'global' : appKey).setValue(value);
  }

  /**
   * Populate values app
   */
  private populateApp(builder?: any) {
    builder = builder || this.refBuilder;
    if (!builder) {
      return false;
    }
    builder.formGroup.get('global').controls = [];
    builder.errors.app = [];
    const appNames: Array<string> = builder.streamDeployConfig.apps.map((app, index) => {
      const appInfo = builder.streamDeployConfig.apps[index];
      builder.builderAppsProperties[app.name] = (appInfo && appInfo.options)
        ? builder.builderAppsProperties[app.name] = appInfo.options
          .map((property) => Object.assign({}, property))
        : [];
      return app.name;
    });
    const add = (array: FormArray) => {
      const group = new FormGroup({
        property: new FormControl('', [StreamDeployValidator.key]),
        global: new FormControl('')
      }, { validators: StreamDeployValidator.keyRequired });

      builder.streamDeployConfig.apps.forEach((app) => {
        group.addControl(app.name, new FormControl(''));
      });
      array.push(group);
    };
    this.properties.forEach((line: string) => {
      const arr = line.split(/=(.*)/);
      const key = arr[0] as string;
      const value = arr[1] as string;
      const appKey = key.split('.')[1];
      if (StreamDeployService.app.is(key)) {
        const keyReduce = StreamDeployService.app.extract(key);
        if ((appKey !== '*' && appNames.indexOf(appKey) === -1) || keyReduce === '') {
          // Error: app not found
          builder.errors.app.push(line);
        } else {
          let free = true;
          if (appNames.indexOf(appKey) > -1) {
            const appProperties = builder.streamDeployConfig.apps[appNames.indexOf(appKey)];
            if (appProperties.options && !appProperties.optionsState.isInvalid) {
              const option = builder.builderAppsProperties[appKey].find(opt => {
                return opt.name === keyReduce || opt.id === keyReduce;
              });
              if (option) {
                option.value = value;
                free = false;
              }
            }
          }
          if (free) {
            this.updateFormArray(builder, builder.formGroup.get('global') as FormArray, appKey, keyReduce, value);
          }
        }
      }
    });
    add(builder.formGroup.get('global'));
    return builder;
  }

  /**
   * Populate values
   */
  private populate(builder) {
    this.refBuilder = builder;

    const appNames: Array<string> = builder.streamDeployConfig.apps.map(app => app.name);
    const deployerKeys: Array<string> = builder.streamDeployConfig.deployers.map(deployer => deployer.name);
    builder.errors.global = [];

    // we need to iterate twice to get a possible platform name set
    // as it's needed later and we don't control order of these properties
    this.properties.some((line: string) => {
      const arr = line.split(/=(.*)/);
      const key = arr[0] as string;
      const value = arr[1] as string;
      if (StreamDeployService.platform.is(key)) {
        builder.formGroup.get('platform').setValue(value);
        const platform = builder.streamDeployConfig.platform.values.find(p => p.name === value);
        builder.builderDeploymentProperties.global = [];
        builder.streamDeployConfig.apps.forEach((app: any) => {
          builder.builderDeploymentProperties.apps[app.name] = [];
        });
        if (platform) {
          platform.options.forEach(o => {
            builder.builderDeploymentProperties.global.push(Object.assign({ isSemantic: true }, o));
            builder.streamDeployConfig.apps.forEach((app: any) => {
              builder.builderDeploymentProperties.apps[app.name].push(Object.assign({ isSemantic: true }, o));
            });
          });
        }
        // got it, break from loop
        return true;
      }
      return false;
    });

    this.properties.forEach((line: string) => {
      const arr = line.split(/=(.*)/);
      const key = arr[0] as string;
      const value = arr[1] as string;
      const appKey = key.split('.')[1];
      if (StreamDeployService.platform.is(key)) {
        // consume but don't do anything, otherwise error is added
        // platform value is set in first iteration
      } else if (StreamDeployService.deployer.is(key)) {
        // Deployer
        const keyReduce = StreamDeployService.deployer.extract(key);
        if ((appKey !== '*' && appNames.indexOf(appKey) === -1) || keyReduce === '') {
          // Error: app not found / * not found
          builder.errors.global.push(line);
        } else {
          if (deployerKeys.indexOf(keyReduce) > -1) {
            builder.formGroup.get('deployers')
              .controls[deployerKeys.indexOf(keyReduce)]
              .get(appKey === '*' ? 'global' : appKey).setValue(value);
          } else {
            const keymatch = 'spring.cloud.deployer.' + keyReduce;
            // go through deployment properties for global and apps and
            // mark match if it looks property is handled by modal, otherwise
            // it belong to form array
            let match = false;
            if (key.indexOf('deployer.*.') > -1) {
              builder.builderDeploymentProperties.global.forEach(p => {
                if (keymatch === p.id) {
                  match = true;
                  p.value = value;
                }
              });
            } else if (key.indexOf('deployer.' + appKey + '.') > -1) {
              builder.builderDeploymentProperties.apps[appKey].forEach(p => {
                if (keymatch === p.id) {
                  match = true;
                  p.value = value;
                }
              });
            }

            if (!match) {
              this.updateFormArray(builder, builder.formGroup.get('specificPlatform') as FormArray, appKey,
                keyReduce, value);
            }
          }
        }
      } else if (StreamDeployService.version.is(key)) {
        // Version
        if (appNames.indexOf(appKey) === -1) {
          // Error: app not found
          builder.errors.global.push(line);
        } else {
          const app = this.refBuilder.streamDeployConfig.apps.find((appConfig: any) => appConfig.name === appKey);
          // Populate if it's not the default version
          if (!app || app.version !== value) {
            builder.formGroup.get('appsVersion').get(appKey).setValue(value);
          }
        }
      } else if (!StreamDeployService.app.is(key)) {
        // Invalid Key
        builder.errors.global.push(line);
      }
    });
    return builder;
  }

  /**
   * Build the Group Form
   */
  private build(streamDeployConfig: StreamDeployConfig) {
    const formGroup: FormGroup = new FormGroup({});

    const getValue = (defaultValue) => !defaultValue ? '' : defaultValue;
    const builderAppsProperties = {};
    const builderDeploymentProperties = { global: [], apps: {} };

    // Platform
    const platformControl = new FormControl(getValue(streamDeployConfig.platform.defaultValue),
      (formControl: FormControl) => {
        if (this.isErrorPlatform(streamDeployConfig.platform.values, formControl.value)) {
          return { invalid: true };
        }
        if (streamDeployConfig.platform.values.length > 1 && !formControl.value) {
          return { invalid: true };
        }
        return null;
      });

    const defaultPlatform = streamDeployConfig.platform.values.length === 1 ?
      streamDeployConfig.platform.values[0] : null;

    const populateDeployerProperties = (value) => {
      builderDeploymentProperties.global = [];
      streamDeployConfig.apps.forEach((app: any) => {
        builderDeploymentProperties.apps[app.name] = [];
      });
      const platform = streamDeployConfig.platform.values.find(p => p.name === value);
      if (platform) {
        platform.options.forEach(o => {
          builderDeploymentProperties.global.push(Object.assign({ isSemantic: true }, o));
          streamDeployConfig.apps.forEach((app: any) => {
            builderDeploymentProperties.apps[app.name].push(Object.assign({ isSemantic: true }, o));
          });
        });
      }
    };

    if (defaultPlatform) {
      populateDeployerProperties(defaultPlatform.name);
    }

    platformControl.valueChanges.subscribe((value) => {
      if (!defaultPlatform) {
        populateDeployerProperties(value);
      }
    });

    formGroup.addControl('platform', platformControl);

    // Deployers
    const deployers = new FormArray([]);
    streamDeployConfig.deployers.forEach((deployer: any) => {
      const groupDeployer: FormGroup = new FormGroup({});
      const validators = [];
      if (deployer.type === 'java.lang.Integer') {
        validators.push(StreamDeployValidator.number);
      }
      groupDeployer.addControl('global', new FormControl(getValue(deployer.defaultValue), validators));
      streamDeployConfig.apps.forEach((app: any) => {
        groupDeployer.addControl(app.name, new FormControl('', validators));
      });
      deployers.push(groupDeployer);
    });

    // Applications
    const appsVersion = new FormGroup({});
    streamDeployConfig.apps.forEach((app: any) => {
      builderAppsProperties[app.name] = [];
      const control = new FormControl(null,
        (formControl: FormControl) => {
          if (this.isErrorVersion(app, formControl.value)) {
            return { invalid: true };
          }
          return null;
        });
      control.valueChanges.subscribe((value) => {
        builderAppsProperties[app.name] = [];
        if (this.isErrorVersion(app, value)) {
          app.optionsState.isInvalid = true;
          app.options = null;
          this.changeDetector.markForCheck();
        } else {
          app.optionsState.isInvalid = false;
          app.optionsState.isOnError = false;
          app.optionsState.isLoading = true;
          this.streamDeployService.appDetails(app.type, app.origin, value).subscribe((options) => {
            app.options = options;
          }, (error) => {
            app.options = [];
            app.optionsState.isOnError = true;
          }, () => {
            app.optionsState.isLoading = false;
            this.changeDetector.markForCheck();
            this.populateApp();
          });
        }
      });
      control.setValue(getValue(app.defaultValue));
      appsVersion.addControl(app.name, control);
    });

    // Useful methods for FormArray
    const add = (array: FormArray) => {
      const group = new FormGroup({
        property: new FormControl('', [StreamDeployValidator.key]),
        global: new FormControl('')
      }, { validators: StreamDeployValidator.keyRequired });

      streamDeployConfig.apps.forEach((app) => {
        group.addControl(app.name, new FormControl(''));
      });
      array.push(group);
    };
    const isEmpty = (dictionary): boolean => Object.entries(dictionary).every((a) => a[1] === '');
    const clean = (val: Array<any>, array: FormArray) => {
      const toRemove = val.map((a, index) =>
        ((index < (val.length - 1) && isEmpty(a)) ? index : null)).filter((a) => a != null);

      toRemove.reverse().forEach((a) => {
        array.removeAt(a);
      });
      if (!isEmpty(val[val.length - 1])) {
        return add(array);
      }
    };

    // Dynamic App properties
    const globalControls: FormArray = new FormArray([]);
    add(globalControls);
    globalControls.valueChanges.subscribe((val: Array<any>) => {
      clean(val, globalControls);
    });

    // Dynamic Platform properties
    const specificPlatformControls: FormArray = new FormArray([]);
    add(specificPlatformControls);
    specificPlatformControls.valueChanges.subscribe((val: Array<any>) => {
      clean(val, specificPlatformControls);
    });

    formGroup.addControl('deployers', deployers);
    formGroup.addControl('appsVersion', appsVersion);
    formGroup.addControl('global', globalControls);
    formGroup.addControl('specificPlatform', specificPlatformControls);

    return {
      formGroup,
      builderAppsProperties,
      builderDeploymentProperties,
      streamDeployConfig,
      errors: {
        global: [],
        app: []
      }
    };
  }

  /**
   * Return true if the version is not invalid
   *
   * @param {any} app
   * @param {string} version
   * @returns {boolean}
   */
  isErrorVersion(app: any, version: string): boolean {
    return version !== '' && !app.versions.find(v => v.version === version);
  }

  /**
   * Return true if the builder is valid
   * @param builder
   * @returns {boolean}
   */
  isSubmittable(builder): boolean {
    if (!builder) {
      return false;
    }
    return builder.formGroup.valid;
  }

  /**
   * Return true if the platform is on error
   *
   * @param {Array<any>} platforms
   * @param {string} platform
   * @returns {boolean}
   */
  isErrorPlatform(platforms: Array<any>, platform: string): boolean {
    return (platform !== '' && !platforms.find(p => p.key === platform))
      || (platform === '' && platforms.length > 1);
  }

  /**
   * Return true if the platform is invalid (invalid value)
   *
   * @param {Array<any>} platforms
   * @param {string} platform
   * @returns {boolean}
   */
  isInvalidPlatform(platforms: Array<any>, platform: string): boolean {
    return (platform !== '' && !platforms.find(p => p.key === platform));
  }

  /**
   * Generate a tooltip
   *
   * @param streamDeployConfig
   * @param control
   * @returns {string}
   */
  tooltip(streamDeployConfig, control: AbstractControl): string {
    const arr = [];
    if (control instanceof FormGroup) {
      if (control.get('property')) {
        if (control.get('property') && control.get('property').invalid) {
          arr.push(`The field "property" is not valid.`);
        }
      }
      if (control.get('global') && control.get('global').invalid) {
        arr.push(`The field "global" is not valid.`);
      }
      streamDeployConfig.apps.forEach((app) => {
        if (control.get(app.name).invalid) {
          arr.push(`The field "${app.name}" is not valid.`);
        }
      });
    } else {

    }
    return arr.join('<br />');
  }

  /**
   * Load the deployment properties of an app or global
   *
   * @param {{}} builderDeploymentProperties
   * @param {string} appId
   * @returns {Array}
   */
  getDeploymentProperties(builderDeploymentProperties: { global: any[], apps: any }, appId?: string): Array<{ key: string, value: any }> {
    const deploymentProperties = appId ? builderDeploymentProperties.apps[appId] : builderDeploymentProperties.global;
    if (!deploymentProperties) {
      return [];
    }

    return deploymentProperties.map((property: Properties.Property) => {
      if (property.value !== null && property.value !== undefined && property.value.toString() !== ''
        && property.value !== property.defaultValue) {
        return {
          key: `${property.id}`,
          value: property.value
        };
      }
      return null;
    }).filter((app) => app !== null);
  }

  /**
   * Open Deployment Properties modal for an app or global
   *
   * @param builder
   * @param {string} appId
   * @param app
   */
  openDeploymentProperties(builder, appId?: string) {
    const options = appId ? builder.builderDeploymentProperties.apps[appId] : builder.builderDeploymentProperties.global;

    // jee.foo.bar-xxx -> jee.foo
    const deduceKey = (key) => {
      return key.substring(0, key.lastIndexOf('.'));
    };

    // grouping all properties by a deduced key
    const groupBy = (items, key) => items.reduce(
      (result, item) => {
        const groupKey = deduceKey(item[key]);
        return ({
          ...result,
          [groupKey]: [...(result[groupKey] || []), item],
        });
      }, {}
    );

    // setup groups and sort alphabetically by group titles
    let groupedPropertiesSources: Array<GroupPropertiesSource> = [];
    const groupedEntries: { [s: string]: Array<any>; } = groupBy(options, 'id');
    Object.entries(groupedEntries).forEach(v => {
      const groupedPropertiesSource = new GroupPropertiesSource(Object.assign([], v[1]
        .map((property) => Object.assign({}, property))), v[0]);
      groupedPropertiesSources.push(groupedPropertiesSource);
    });
    groupedPropertiesSources = groupedPropertiesSources.sort(((a, b) => {
      return a.title === b.title ? 0 : a.title < b.title ? -1 : 1;
    }));
    const groupPropertiesSources = new GroupPropertiesSources(groupedPropertiesSources);

    // get new props from modal
    groupPropertiesSources.confirm.subscribe((properties: Array<any>) => {
      if (appId) {
        builder.builderDeploymentProperties.apps[appId] = properties;
      } else {
        builder.builderDeploymentProperties.global = properties;
      }
      this.changeDetector.markForCheck();
    });
    this.groupsPropertiesModal.setData(groupPropertiesSources);
    this.groupsPropertiesModal.title = `Deployment properties for platform`;
    this.groupsPropertiesModal.isOpen = true;
  }

  /**
   * Load the properties of an app
   *
   * @param {{}} builderAppsProperties
   * @param {string} appId
   * @returns {Array}
   */
  getAppProperties(builderAppsProperties: {}, appId: string): Array<{ key: string, value: any }> {
    const appProperties = builderAppsProperties[appId];
    if (!appProperties) {
      return [];
    }
    return appProperties.map((property: Properties.Property) => {
      if (property.value !== null && property.value !== undefined && property.value.toString() !== ''
        && property.value !== property.defaultValue) {
        if (property.id.startsWith(`${appId}.`)) {
          return {
            key: `${property.name}`,
            value: property.value
          };
        } else {
          return {
            key: `${property.id}`,
            value: property.value
          };
        }
      }
      return null;
    }).filter((app) => app !== null);
  }

  /**
   * Open Application Properties modal
   *
   * @param builder
   * @param app
   */
  openApp(builder, app: any) {
    const version = builder.formGroup.get('appsVersion').get(app.name).value || app.version;
    const options = builder.builderAppsProperties[app.name] ? builder.builderAppsProperties[app.name] : app.options;
    const appPropertiesSource = new AppPropertiesSource(Object.assign([], options
      .map((property) => Object.assign({}, property))));
    appPropertiesSource.confirm.subscribe((properties: Array<any>) => {
      builder.builderAppsProperties[app.name] = properties;
      this.changeDetector.markForCheck();
    });
    this.appPropertiesModal.app = new App();
    this.appPropertiesModal.app.name = app.name;
    this.appPropertiesModal.app.type = app.type;
    this.appPropertiesModal.app.version = version;
    this.appPropertiesModal.setData(appPropertiesSource);
    this.appPropertiesModal.isOpen = true;
  }

  /**
   * Remove an error property
   */
  removeError(value: { type: string, index: number }) {
    const errors = this.refBuilder.errors[value.type];
    if (errors[value.index]) {
      errors.splice(value.index, 1);
    }
    this.properties = this.getProperties();
  }

  /**
   * Emit a request deploy
   */
  deployStream() {
    if (!this.isSubmittable(this.refBuilder)) {
      this.notificationService.error('An error occurred', 'Some field(s) are invalid.');
    } else {
      this.deploy.emit(this.getProperties());
    }
  }

  /**
   * Emit a request export
   */
  exportProps() {
    this.exportProperties.emit(this.getProperties());
  }

  /**
   * Copye to clipboard
   */
  copyToClipboard() {
    this.copyProperties.emit(this.getProperties());
  }

}


text:
import os
import mock
import sys
import tempfile

import novaclient.shell
import novaclient.client
from novaclient import exceptions
from tests.v1_1 import fakes
from tests import utils

class ShellTest(utils.TestCase):

    # Patch os.environ to avoid required auth info.
    def setUp(self):
        """Run before each test."""
        self.old_environment = os.environ.copy()
        os.environ = {
            'NOVA_USERNAME': 'username',
            'NOVA_PASSWORD': 'password',
            'NOVA_PROJECT_ID': 'project_id',
            'NOVA_VERSION': '1.1',
            'NOVA_URL': 'http://no.where',
        }

        self.shell = novaclient.shell.OpenStackComputeShell()

        #HACK(bcwaldon): replace this when we start using stubs
        self.old_get_client_class = novaclient.client.get_client_class
        novaclient.client.get_client_class = lambda *_: fakes.FakeClient

    def tearDown(self):
        os.environ = self.old_environment
        # For some method like test_image_meta_bad_action we are
        # testing a SystemExit to be thrown and object self.shell has
        # no time to get instantatiated which is OK in this case, so
        # we make sure the method is there before launching it.
        if hasattr(self.shell, 'cs'):
            self.shell.cs.clear_callstack()

        #HACK(bcwaldon): replace this when we start using stubs
        novaclient.client.get_client_class = self.old_get_client_class

    def run_command(self, cmd):
        self.shell.main(cmd.split())

    def assert_called(self, method, url, body=None, **kwargs):
        return self.shell.cs.assert_called(method, url, body, **kwargs)

    def assert_called_anytime(self, method, url, body=None):
        return self.shell.cs.assert_called_anytime(method, url, body)

    def test_boot(self):
        self.run_command('boot --flavor 1 --image 1 some-server')
        self.assert_called_anytime(
            'POST', '/servers',
            {'server': {
                'flavorRef': '1',
                'name': 'some-server',
                'imageRef': '1',
                'min_count': 1,
                'max_count': 1,
                }},
        )

        self.run_command('boot --image 1 --flavor 1 --meta foo=bar'
                         ' --meta spam=eggs some-server ')
        self.assert_called_anytime(
            'POST', '/servers',
            {'server': {
                'flavorRef': '1',
                'name': 'some-server',
                'imageRef': '1',
                'metadata': {'foo': 'bar', 'spam': 'eggs'},
                'min_count': 1,
                'max_count': 1,
            }},
        )

    def test_boot_files(self):
        testfile = os.path.join(os.path.dirname(__file__), 'testfile.txt')
        expected_file_data = open(testfile).read().encode('base64')

        cmd = 'boot some-server --flavor 1 --image 1 ' \
              '--file /tmp/foo=%s --file /tmp/bar=%s'
        self.run_command(cmd % (testfile, testfile))

        self.assert_called_anytime(
            'POST', '/servers',
            {'server': {
                'flavorRef': '1',
                'name': 'some-server',
                'imageRef': '1',
                'min_count': 1,
                'max_count': 1,
                'personality': [
                   {'path': '/tmp/bar', 'contents': expected_file_data},
                   {'path': '/tmp/foo', 'contents': expected_file_data},
                ]},
            },
        )

    def test_boot_invalid_file(self):
        invalid_file = os.path.join(os.path.dirname(__file__),
                                    'asdfasdfasdfasdf')
        cmd = 'boot some-server --image 1 --file /foo=%s' % invalid_file
        self.assertRaises(exceptions.CommandError, self.run_command, cmd)

    def test_boot_key_auto(self):
        mock_exists = mock.Mock(return_value=True)
        mock_open = mock.Mock()
        mock_open.return_value = mock.Mock()
        mock_open.return_value.read = mock.Mock(return_value='SSHKEY')

        @mock.patch('os.path.exists', mock_exists)
        @mock.patch('__builtin__.open', mock_open)
        def test_shell_call():
            cmd = 'boot some-server --flavor 1 --image 1 --key_path'
            self.run_command(cmd)
            self.assert_called_anytime(
                'POST', '/servers',
                {'server': {
                    'flavorRef': '1',
                    'name': 'some-server',
                    'imageRef': '1',
                    'min_count': 1,
                    'max_count': 1,
                    'personality': [{
                        'path': '/root/.ssh/authorized_keys2',
                        'contents': ('SSHKEY').encode('base64')},
                    ]},
                },
            )

        test_shell_call()

    def test_boot_key_auto_no_keys(self):
        mock_exists = mock.Mock(return_value=False)

        @mock.patch('os.path.exists', mock_exists)
        def test_shell_call():
            cmd = 'boot some-server --flavor 1 --image 1 --key_path'
            self.assertRaises(exceptions.CommandError, self.run_command, cmd)

        test_shell_call()

    def test_boot_key_file(self):
        testfile = os.path.join(os.path.dirname(__file__), 'testfile.txt')
        expected_file_data = open(testfile).read().encode('base64')
        cmd = 'boot some-server --flavor 1 --image 1 --key_path %s'
        self.run_command(cmd % testfile)
        self.assert_called_anytime(
            'POST', '/servers',
            {'server': {
                'flavorRef': '1',
                'name': 'some-server',
                'imageRef': '1',
                'min_count': 1,
                'max_count': 1,
                'personality': [
                    {'path': '/root/.ssh/authorized_keys2',
                     'contents':expected_file_data},
                 ]},
            },
        )

    def test_boot_invalid_keyfile(self):
        invalid_file = os.path.join(os.path.dirname(__file__),
                                    'asdfasdfasdfasdf')
        cmd = 'boot some-server --flavor 1 --image 1 --key_path %s'
        self.assertRaises(exceptions.CommandError, self.run_command,
                          cmd % invalid_file)

    def test_flavor_list(self):
        self.run_command('flavor-list')
        self.assert_called_anytime('GET', '/flavors/detail')

    def test_image_show(self):
        self.run_command('image-show 1')
        self.assert_called('GET', '/images/1')

    def test_image_meta_set(self):
        self.run_command('image-meta 1 set test_key=test_value')
        self.assert_called('POST', '/images/1/metadata',
            {'metadata': {'test_key': 'test_value'}})

    def test_image_meta_del(self):
        self.run_command('image-meta 1 delete test_key=test_value')
        self.assert_called('DELETE', '/images/1/metadata/test_key')

    def test_image_meta_bad_action(self):
        tmp = tempfile.TemporaryFile()

        # Suppress stdout and stderr
        (stdout, stderr) = (sys.stdout, sys.stderr)
        (sys.stdout, sys.stderr) = (tmp, tmp)

        self.assertRaises(SystemExit, self.run_command,
                          'image-meta 1 BAD_ACTION test_key=test_value')

        # Put stdout and stderr back
        sys.stdout, sys.stderr = (stdout, stderr)

    def test_image_list(self):
        self.run_command('image-list')
        self.assert_called('GET', '/images/detail')

    def test_create_image(self):
        self.run_command('image-create sample-server mysnapshot')
        self.assert_called(
            'POST', '/servers/1234/action',
            {'createImage': {'name': 'mysnapshot', 'metadata': {}}},
        )

    def test_image_delete(self):
        self.run_command('image-delete 1')
        self.assert_called('DELETE', '/images/1')

    def test_list(self):
        self.run_command('list')
        self.assert_called('GET', '/servers/detail')

    def test_reboot(self):
        self.run_command('reboot sample-server')
        self.assert_called('POST', '/servers/1234/action',
                           {'reboot': {'type': 'SOFT'}})
        self.run_command('reboot sample-server --hard')
        self.assert_called('POST', '/servers/1234/action',
                           {'reboot': {'type': 'HARD'}})

    def test_rebuild(self):
        self.run_command('rebuild sample-server 1')
        # XXX need a way to test multiple calls
        #self.assert_called('POST', '/servers/1234/action',
        #                   {'rebuild': {'imageRef': 1}})
        self.assert_called('GET', '/images/2')

        self.run_command('rebuild sample-server 1 --rebuild_password asdf')
        # XXX need a way to test multiple calls
        #self.assert_called('POST', '/servers/1234/action',
        #                   {'rebuild': {'imageRef': 1, 'adminPass': 'asdf'}})
        self.assert_called('GET', '/images/2')

    def test_rename(self):
        self.run_command('rename sample-server newname')
        self.assert_called('PUT', '/servers/1234',
                           {'server': {'name': 'newname'}})

    def test_resize(self):
        self.run_command('resize sample-server 1')
        self.assert_called('POST', '/servers/1234/action',
                           {'resize': {'flavorRef': 1}})

    def test_resize_confirm(self):
        self.run_command('resize-confirm sample-server')
        self.assert_called('POST', '/servers/1234/action',
                           {'confirmResize': None})

    def test_resize_revert(self):
        self.run_command('resize-revert sample-server')
        self.assert_called('POST', '/servers/1234/action',
                           {'revertResize': None})

    @mock.patch('getpass.getpass', mock.Mock(return_value='p'))
    def test_root_password(self):
        self.run_command('root-password sample-server')
        self.assert_called('POST', '/servers/1234/action',
                           {'changePassword': {'adminPass': 'p'}})

    def test_show(self):
        self.run_command('show 1234')
        self.assert_called('GET', '/servers/1234', pos=-3)
        self.assert_called('GET', '/flavors/1', pos=-2)
        self.assert_called('GET', '/images/2')

    def test_show_bad_id(self):
        self.assertRaises(exceptions.CommandError,
                          self.run_command, 'show xxx')

    def test_delete(self):
        self.run_command('delete 1234')
        self.assert_called('DELETE', '/servers/1234')
        self.run_command('delete sample-server')
        self.assert_called('DELETE', '/servers/1234')

    def test_set_meta_set(self):
        self.run_command('meta 1234 set key1=val1 key2=val2')
        self.assert_called('POST', '/servers/1234/metadata',
                           {'metadata': {'key1': 'val1', 'key2': 'val2'}})

    def test_set_meta_delete_dict(self):
        self.run_command('meta 1234 delete key1=val1 key2=val2')
        self.assert_called('DELETE', '/servers/1234/metadata/key1')
        self.assert_called('DELETE', '/servers/1234/metadata/key2', pos=-2)

    def test_set_meta_delete_keys(self):
        self.run_command('meta 1234 delete key1 key2')
        self.assert_called('DELETE', '/servers/1234/metadata/key1')
        self.assert_called('DELETE', '/servers/1234/metadata/key2', pos=-2)

    def test_dns_create(self):
        self.run_command('dns-create 192.168.1.1 testname testdomain')
        self.assert_called('PUT',
                           '/os-floating-ip-dns/testdomain/entries/testname')

        self.run_command('dns-create 192.168.1.1 testname testdomain --type A')
        self.assert_called('PUT',
                           '/os-floating-ip-dns/testdomain/entries/testname')

    def test_dns_create_public_domain(self):
        self.run_command('dns-create-public-domain testdomain '
                         '--project test_project')
        self.assert_called('PUT', '/os-floating-ip-dns/testdomain')

    def test_dns_create_private_domain(self):
        self.run_command('dns-create-private-domain testdomain '
                         '--availability_zone av_zone')
        self.assert_called('PUT', '/os-floating-ip-dns/testdomain')

    def test_dns_delete(self):
        self.run_command('dns-delete testdomain testname')
        self.assert_called('DELETE',
                           '/os-floating-ip-dns/testdomain/entries/testname')

    def test_dns_delete_domain(self):
        self.run_command('dns-delete-domain testdomain')
        self.assert_called('DELETE', '/os-floating-ip-dns/testdomain')

    def test_dns_list(self):
        self.run_command('dns-list testdomain --ip 192.168.1.1')
        self.assert_called('GET',
                       '/os-floating-ip-dns/testdomain/entries?ip=192.168.1.1')

        self.run_command('dns-list testdomain --name testname')
        self.assert_called('GET',
                           '/os-floating-ip-dns/testdomain/entries/testname')

    def test_dns_domains(self):
        self.run_command('dns-domains')
        self.assert_called('GET', '/os-floating-ip-dns')

    def test_usage_list(self):
        self.run_command('usage-list --start 2000-01-20 --end 2005-02-01')
        self.assert_called('GET',
                           '/os-simple-tenant-usage?' +
                           'start=2000-01-20T00:00:00&' +
                           'end=2005-02-01T00:00:00&' +
                           'detailed=1')

    def test_flavor_delete(self):
        self.run_command("flavor-delete flavordelete")
        self.assert_called('DELETE', '/flavors/flavordelete')

    def test_flavor_create(self):
        self.run_command("flavor-create flavorcreate "
                         "1234 512 10 1 --swap 1024")

        body = {
            "flavor": {
                "name": "flavorcreate",
                "ram": 512,
                "vcpus": 1,
                "disk": 10,
                "id": 1234,
                "swap": 1024,
                "rxtx_factor": 1,
            }
        }

        self.assert_called('POST', '/flavors', body, pos=-2)
        self.assert_called('GET', '/flavors/1')

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Audiens\AdForm\Tests\Entity;

/**
 * Class CategoryHydratorTest
 */
class CategoryHydratorTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @test
     */
    public function hydratorWillReturnCategoryObject()
    {
        $stdClass = new \stdClass();
        $stdClass->id = 10;
        $stdClass->name = 'TestCategory';
        $stdClass->dataProviderId = 10000;
        $stdClass->parentId = 20000;
        $stdClass->createdAt = '2015-10-10';
        $stdClass->updatedAt = '2015-10-10';

        $category = \Audiens\AdForm\Entity\CategoryHydrator::fromStdClass($stdClass);

        $this->assertInstanceOf(\Audiens\AdForm\Entity\Category::class, $category);
    }
}


text:
var PERMISSIONS = {origins: ['https://api.stackexchange.com/']};
var URL = 'https://api.stackexchange.com/2.2/search?page=1&pagesize=10&order=desc&sort=activity&tagged=google-chrome-extension&site=stackoverflow';
var ROOT = 'https://api.stackexchange.com';

chrome.permissions.contains(PERMISSIONS, function(result) {
  if (!result) {
    // Open options page to request permissions.
    document.querySelector('#title').innerText =
        'Requires Stack Overflow permission';
    chrome.tabs.create({url: 'options.html'});
  } else {
    // Make the request to SO.
    makeRequest(function(data) {
      // Render the results.
      renderQuestions(JSON.parse(data));
    });
  }
});

function makeRequest(callback) {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', URL);
  xhr.addEventListener('load', function(e) {
    var result = xhr.responseText;
    callback(result);
  });
  xhr.send();
}

function renderQuestions(data) {
  var $results = document.querySelector('#results');
  var questions = data.items;
  for (var i = 0; i < Math.min(10, questions.length); i++) {
    var question = questions[i];
    var $question = document.createElement('li');
    var url = question.link;
    $question.innerHTML = '' +
        question.title + '';
    results.appendChild($question);
  }
  // Update title too.
  document.querySelector('#title').innerText = 'Top Chrome Extension Questions';
}


text: SomeClass::SomeClass() { }


text:
package com.zc.express.bean;

public class ItemBean {
    private int img;
    private String title;
    private boolean isUpdate=false;

    public ItemBean() {
    }

    public ItemBean(int img, String title, boolean isUpdate) {
        this.img = img;
        this.title = title;
        this.isUpdate = isUpdate;
    }

    public int getImg() {
        return img;
    }

    public void setImg(int img) {
        this.img = img;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public boolean isUpdate() {
        return isUpdate;
    }

    public void setIsUpdate(boolean isUpdate) {
        this.isUpdate = isUpdate;
    }

    @Override
    public String toString() {
        return "ItemBean{" +
                "img=" + img +
                ", title='" + title + '\'' +
                ", isUpdate=" + isUpdate +
                '}';
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>CSS2 Table Backgrounds Test Suite</title>
<link rel="stylesheet" type="text/css" href="common.css">

CSS2 Table Backgrounds Test Suite

Notes

This test suite is not endorsed or approved by the W3C or anyone besides fantasai. It tests conformance to fantasai's table background clarification proposal, not the official CSS2 specification. The intent is to demonstrate the proposal's effects under various styling conditions and to clarify any ambiguity in the proposal in preparation for a better-worded errata suggestion. It's not particularly well-designed, but it is comprehensive.

This test suite (this page and all pages linked from the table of contents below) and its background images (listed below) are in the public domain by assertion of their author. No rights reserved.

The images used as backgrounds are the following:

They are in GIF format, with transparency.

Each color band in the rainbow backgrounds is 20 pixels wide. Each stripe within the color band is two pixels wide.

The aqua and purple band is 10 pixels wide. Each stripe within the band is two pixels wide.

Many image background rules in this test suite are backed up with a 'black' background color.

This test suite assumes that the border edge for a table element in a table with collapsed borders is the middle of the border around the element, not the outer or inner edge. (This also needs to be addressed by CSS2.1.) It also assumes support for proper ordering of tables with <tfoot>.

Table of Contents

Background Area

Background on 'table'

Background on 'table-row-group'

Background on 'table-column-group'

Background on 'table-row'

Background on 'table-column'

Background on 'table-cell'

Background Position

Background on 'table'

Background on 'table-row-group'

Background on 'table-column-group'

Background on 'table-row'

Background on 'table-column'

Background on 'table-cell'

Background Layers

empty-cells: show

empty-cells: hide

Background with Borders

Background on 'table'

Background on 'table-row-group'

Background on 'table-column-group'

Background on 'table-row'

Background on 'table-column'

Background on 'table-cell'

Special Tests

Opacity

Fixed Backgrounds

<address>
  CSS2 Table Backgrounds Test Suite designed and written by fantasai <fantasai@escape.com>
</address>


text:
from pass.__main__ import main

def test_main():
    assert main([]) == 0


text:
var SMB = require( '../../smb' )
var Packet = require( '../../packet' )
var inherit = require( 'bloodline' )

/**
 * LockResponse Constructor
 * @return {LockResponse}
 */
function LockResponse( options ) {

  if( !(this instanceof LockResponse) )
    return new LockResponse( options )

  Packet.call( this )

}

/**
 * LockResponse Prototype
 * @type {Object}
 */
LockResponse.prototype = {

  constructor: LockResponse,

  parsePayload: function( buffer ) {

    return this

  },

  serialize: function() {
    return buffer
  },

}

inherit( LockResponse, Packet )
// Exports
module.exports = LockResponse


text:
package com.amazonaws.services.robomaker.model;

import javax.annotation.Generated;

/**
 * <p>
 * The request has failed due to a temporary failure of the server.
 * </p>
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ServiceUnavailableException extends com.amazonaws.services.robomaker.model.AWSRoboMakerException {
    private static final long serialVersionUID = 1L;

    /**
     * Constructs a new ServiceUnavailableException with the specified error message.
     *
     * @param message
     *        Describes the error encountered.
     */
    public ServiceUnavailableException(String message) {
        super(message);
    }

}


text:
#pragma once

#include "../Container/Str.h"

namespace Atomic
{

/// 32-bit hash value for a string.
class ATOMIC_API StringHash
{
public:
    /// Construct with zero value.
    StringHash() :
        value_(0)
    {
    }

    /// Copy-construct from another hash.
    StringHash(const StringHash& rhs) :
        value_(rhs.value_)
    {
    }

    /// Construct with an initial value.
    explicit StringHash(unsigned value) :
        value_(value)
    {
    }

    /// Construct from a C string case-insensitively.
    StringHash(const char* str);
    /// Construct from a string case-insensitively.
    StringHash(const String& str);

    /// Assign from another hash.
    StringHash& operator =(const StringHash& rhs)
    {
        value_ = rhs.value_;
        return *this;
    }

    /// Add a hash.
    StringHash operator +(const StringHash& rhs) const
    {
        StringHash ret;
        ret.value_ = value_ + rhs.value_;
        return ret;
    }

    /// Add-assign a hash.
    StringHash& operator +=(const StringHash& rhs)
    {
        value_ += rhs.value_;
        return *this;
    }

    // Test for equality with another hash.
    bool operator ==(const StringHash& rhs) const { return value_ == rhs.value_; }

    /// Test for inequality with another hash.
    bool operator !=(const StringHash& rhs) const { return value_ != rhs.value_; }

    /// Test if less than another hash.
    bool operator <(const StringHash& rhs) const { return value_ < rhs.value_; }

    /// Test if greater than another hash.
    bool operator >(const StringHash& rhs) const { return value_ > rhs.value_; }

    /// Return true if nonzero hash value.
    operator bool() const { return value_ != 0; }

    /// Return hash value.
    unsigned Value() const { return value_; }

    /// Return as string.
    String ToString() const;

    /// Return hash value for HashSet & HashMap.
    unsigned ToHash() const { return value_; }

    /// Calculate hash value case-insensitively from a C string.
    static unsigned Calculate(const char* str);

    /// Zero hash.
    static const StringHash ZERO;

private:
    /// Hash value.
    unsigned value_;
};

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CppSharp.AST;
using CppSharp.AST.Extensions;
using CppSharp.Types;
using Type = CppSharp.AST.Type;

namespace CppSharp.Generators.CSharp
{
    public enum CSharpMarshalKind
    {
        Unknown,
        NativeField
    }

    public class CSharpMarshalContext : MarshalContext
    {
        public CSharpMarshalContext(Driver driver)
            : base(driver)
        {
            Kind = CSharpMarshalKind.Unknown;
            ArgumentPrefix = new TextGenerator();
            Cleanup = new TextGenerator();
        }

        public CSharpMarshalKind Kind { get; set; }
        public QualifiedType FullType;

        public TextGenerator ArgumentPrefix { get; private set; }
        public TextGenerator Cleanup { get; private set; }
    }

    public abstract class CSharpMarshalPrinter : MarshalPrinter
    {
        public CSharpMarshalContext CSharpContext
        {
            get { return Context as CSharpMarshalContext; }
        }

        protected CSharpMarshalPrinter(CSharpMarshalContext context)
            : base(context)
        {
            Options.VisitFunctionParameters = false;
            Options.VisitTemplateArguments = false;
        }

        public override bool VisitMemberPointerType(MemberPointerType member,
            TypeQualifiers quals)
        {
            return false;
        }
    }

    public class CSharpMarshalNativeToManagedPrinter : CSharpMarshalPrinter
    {
        public CSharpMarshalNativeToManagedPrinter(CSharpMarshalContext context)
            : base(context)
        {
            Context.MarshalToManaged = this;
        }

        public static string QualifiedIdentifier(Declaration decl)
        {
            var names = new List<string> { decl.Name };

            var ctx = decl.Namespace;
            while (ctx != null)
            {
                if (!string.IsNullOrWhiteSpace(ctx.Name))
                    names.Add(ctx.Name);
                ctx = ctx.Namespace;
            }

            //if (Options.GenerateLibraryNamespace)
            //    names.Add(Options.OutputNamespace);

            names.Reverse();
            return string.Join(".", names);
        }

        public override bool VisitType(Type type, TypeQualifiers quals)
        {
            TypeMap typeMap;
            if (Context.Driver.TypeDatabase.FindTypeMap(type, out typeMap) && typeMap.DoesMarshalling)
            {
                typeMap.Type = type;
                typeMap.CSharpMarshalToManaged(Context);
                return false;
            }

            return true;
        }

        public override bool VisitDeclaration(Declaration decl)
        {
            TypeMap typeMap;
            if (Context.Driver.TypeDatabase.FindTypeMap(decl, out typeMap) && typeMap.DoesMarshalling)
            {
                typeMap.Declaration = decl;
                typeMap.CSharpMarshalToManaged(Context);
                return false;
            }

            return true;
        }

        public override bool VisitArrayType(ArrayType array, TypeQualifiers quals)
        {
            if (!VisitType(array, quals))
                return false;

            switch (array.SizeType)
            {
                case ArrayType.ArraySize.Constant:
                    var supportBefore = Context.SupportBefore;
                    string value = Generator.GeneratedIdentifier("value");
                    supportBefore.WriteLine("{0}[] {1} = null;", array.Type, value, array.Size);
                    supportBefore.WriteLine("if ({0} != null)", Context.ReturnVarName);
                    supportBefore.WriteStartBraceIndent();
                    supportBefore.WriteLine("{0} = new {1}[{2}];", value, array.Type, array.Size);
                    supportBefore.WriteLine("for (int i = 0; i < {0}; i++)", array.Size);
                    if (array.Type.IsPointerToPrimitiveType(PrimitiveType.Void))
                        supportBefore.WriteLineIndent("{0}[i] = new global::System.IntPtr({1}[i]);",
                            value, Context.ReturnVarName);
                    else
                        supportBefore.WriteLineIndent("{0}[i] = {1}[i];", value, Context.ReturnVarName);
                    supportBefore.WriteCloseBraceIndent();
                    Context.Return.Write(value);
                    break;
                case ArrayType.ArraySize.Variable:
                    Context.Return.Write("null");
                    break;
            }

            return true;
        }

        public override bool VisitPointerType(PointerType pointer, TypeQualifiers quals)
        {
            if (!VisitType(pointer, quals))
                return false;

            var pointee = pointer.Pointee.Desugar();

            if (CSharpTypePrinter.IsConstCharString(pointer))
            {
                Context.Return.Write(MarshalStringToManaged(Context.ReturnVarName,
                    pointer.Pointee.Desugar() as BuiltinType));
                return true;
            }

            PrimitiveType primitive;
            if (pointee.IsPrimitiveType(out primitive) || pointee.IsEnumType())
            {
                var param = Context.Parameter;
                if (param != null && (param.IsOut || param.IsInOut))
                {
                    Context.Return.Write("_{0}", param.Name);
                    return true;
                }

                Context.Return.Write(Context.ReturnVarName);
                return true;
            }

            return pointer.Pointee.Visit(this, quals);
        }

        private string MarshalStringToManaged(string varName, BuiltinType type)
        {
            var encoding = type.Type == PrimitiveType.Char ?
                Encoding.ASCII : Encoding.Unicode;

            if (Equals(encoding, Encoding.ASCII))
                encoding = Context.Driver.Options.Encoding;

            if (Equals(encoding, Encoding.ASCII))
                return string.Format("Marshal.PtrToStringAnsi({0})", varName);

            if (Equals(encoding, Encoding.Unicode) ||
                Equals(encoding, Encoding.BigEndianUnicode))
                return string.Format("Marshal.PtrToStringUni({0})", varName);

            throw new NotSupportedException(string.Format("{0} is not supported yet.",
                Context.Driver.Options.Encoding.EncodingName));
        }

        public override bool VisitPrimitiveType(PrimitiveType primitive, TypeQualifiers quals)
        {
            switch (primitive)
            {
                case PrimitiveType.Void:
                    return true;
                case PrimitiveType.Bool:
                case PrimitiveType.Char:
                case PrimitiveType.UChar:
                case PrimitiveType.Short:
                case PrimitiveType.UShort:
                case PrimitiveType.Int:
                case PrimitiveType.UInt:
                case PrimitiveType.Long:
                case PrimitiveType.ULong:
                case PrimitiveType.LongLong:
                case PrimitiveType.ULongLong:
                case PrimitiveType.Float:
                case PrimitiveType.Double:
                case PrimitiveType.WideChar:
                case PrimitiveType.Null:
                    Context.Return.Write(Context.ReturnVarName);
                    return true;
                case PrimitiveType.Char16:
                    return false;
            }

            throw new NotImplementedException();
        }

        public override bool VisitTypedefType(TypedefType typedef, TypeQualifiers quals)
        {
            if (!VisitType(typedef, quals))
                return false;

            var decl = typedef.Declaration;

            FunctionType function;
            if (decl.Type.IsPointerTo(out function))
            {
                var ptrName = Generator.GeneratedIdentifier("ptr") +
                    Context.ParameterIndex;

                Context.SupportBefore.WriteLine("var {0} = {1};", ptrName,
                    Context.ReturnVarName);

                Context.Return.Write("({1})Marshal.GetDelegateForFunctionPointer({0}, typeof({1}))",
                    ptrName, typedef.ToString());
                return true;
            }

            return decl.Type.Visit(this);
        }

        public override bool VisitFunctionType(FunctionType function, TypeQualifiers quals)
        {
            var ptrName = Generator.GeneratedIdentifier("ptr") + Context.ParameterIndex;

            Context.SupportBefore.WriteLine("var {0} = {1};", ptrName,
                Context.ReturnVarName);

            Context.Return.Write("({1})Marshal.GetDelegateForFunctionPointer({0}, typeof({1}))",
                ptrName, function.ToString());
            return true;
        }

        public override bool VisitClassDecl(Class @class)
        {
            var instance = Context.ReturnVarName;

            @class = @class.OriginalClass ?? @class;
            Type returnType = Context.ReturnType.Type.Desugar();

            var type = QualifiedIdentifier(@class) +
                (Context.Driver.Options.GenerateAbstractImpls && @class.IsAbstract ?
                    "Internal" : "");

            if (returnType.IsAddress())
                Context.Return.Write("({0} == IntPtr.Zero) ? {1} : {2}.{3}({0})", instance,
                    @class.IsRefType ? "null" : string.Format("new {0}()", type),
                    type, Helpers.CreateInstanceIdentifier);
            else
                Context.Return.Write("{0}.{1}({2})", type, Helpers.CreateInstanceIdentifier, instance);

            return true;
        }

        private static bool FindTypeMap(ITypeMapDatabase typeMapDatabase,
            Class @class, out TypeMap typeMap)
        {
            return typeMapDatabase.FindTypeMap(@class, out typeMap) ||
                   (@class.HasBase && FindTypeMap(typeMapDatabase, @class.Bases[0].Class, out typeMap));
        }

        public override bool VisitEnumDecl(Enumeration @enum)
        {
            Context.Return.Write("{0}", Context.ReturnVarName);
            return true;
        }

        public override bool VisitParameterDecl(Parameter parameter)
        {
            if (parameter.Usage == ParameterUsage.Unknown || parameter.IsIn)
                return base.VisitParameterDecl(parameter);

            var ctx = new CSharpMarshalContext(base.Context.Driver)
            {
                ReturnType = base.Context.ReturnType,
                ReturnVarName = base.Context.ReturnVarName
            };

            var marshal = new CSharpMarshalNativeToManagedPrinter(ctx);
            parameter.Type.Visit(marshal);

            if (!string.IsNullOrWhiteSpace(ctx.SupportBefore))
                Context.SupportBefore.WriteLine(ctx.SupportBefore);

            if (!string.IsNullOrWhiteSpace(ctx.Return))
            {
                Context.SupportBefore.WriteLine("var _{0} = {1};", parameter.Name,
                    ctx.Return);
            }

            Context.Return.Write("_{0}", parameter.Name);
            return true;
        }
    }

    public class CSharpMarshalManagedToNativePrinter : CSharpMarshalPrinter
    {
        public CSharpMarshalManagedToNativePrinter(CSharpMarshalContext context)
            : base(context)
        {
            Context.MarshalToNative = this;
        }

        public override bool VisitType(Type type, TypeQualifiers quals)
        {
            TypeMap typeMap;
            if (Context.Driver.TypeDatabase.FindTypeMap(type, out typeMap) && typeMap.DoesMarshalling)
            {
                typeMap.Type = type;
                typeMap.CSharpMarshalToNative(Context);
                return false;
            }

            return true;
        }

        public override bool VisitDeclaration(Declaration decl)
        {
            TypeMap typeMap;
            if (Context.Driver.TypeDatabase.FindTypeMap(decl, out typeMap) && typeMap.DoesMarshalling)
            {
                typeMap.Declaration = decl;
                typeMap.CSharpMarshalToNative(Context);
                return false;
            }

            return true;
        }

        public override bool VisitArrayType(ArrayType array, TypeQualifiers quals)
        {
            if (!VisitType(array, quals))
                return false;

            switch (array.SizeType)
            {
                case ArrayType.ArraySize.Constant:
                    var supportBefore = Context.SupportBefore;
                    supportBefore.WriteLine("if ({0} != null)", Context.ArgName);
                    supportBefore.WriteStartBraceIndent();
                    supportBefore.WriteLine("for (int i = 0; i < {0}; i++)", array.Size);
                    supportBefore.WriteLineIndent("{0}[i] = {1}[i]{2};",
                        Context.ReturnVarName, Context.ArgName,
                        array.Type.IsPointerToPrimitiveType(PrimitiveType.Void) ? ".ToPointer()" : string.Empty);
                    supportBefore.WriteCloseBraceIndent();
                    break;
                default:
                    Context.Return.Write("null");
                    break;
            }
            return true;
        }

        public bool VisitDelegateType(FunctionType function, string type)
        {
            Context.Return.Write("Marshal.GetFunctionPointerForDelegate({0})",
                Context.Parameter.Name);

            return true;
        }

        public override bool VisitPointerType(PointerType pointer, TypeQualifiers quals)
        {
            if (!VisitType(pointer, quals))
                return false;

            var pointee = pointer.Pointee.Desugar();

            if ((pointee.IsPrimitiveType(PrimitiveType.Char) ||
                pointee.IsPrimitiveType(PrimitiveType.WideChar)) &&
                pointer.QualifiedPointee.Qualifiers.IsConst)
            {
                if (Context.Parameter.IsOut)
                {
                    Context.Return.Write("IntPtr.Zero");
                    CSharpContext.ArgumentPrefix.Write("&");
                }
                else if (Context.Parameter.IsInOut)
                {
                    Context.Return.Write(MarshalStringToUnmanaged(Context.Parameter.Name));
                    CSharpContext.ArgumentPrefix.Write("&");
                }
                else
                {
                    Context.Return.Write(MarshalStringToUnmanaged(Context.Parameter.Name));
                    CSharpContext.Cleanup.WriteLine("Marshal.FreeHGlobal({0});", Context.ArgName);
                }
                return true;
            }

            if (pointee is FunctionType)
            {
                var function = pointee as FunctionType;
                return VisitDelegateType(function, function.ToString());
            }

            Class @class;
            if (pointee.TryGetClass(out @class) && @class.IsValueType)
            {
                if (Context.Parameter.Usage == ParameterUsage.Out)
                {
                    Context.SupportBefore.WriteLine("var {0} = new {1}.Internal();",
                        Generator.GeneratedIdentifier(Context.ArgName), @class.Name);
                }
                else
                {
                    Context.SupportBefore.WriteLine("var {0} = {1}.ToInternal();",
                            Generator.GeneratedIdentifier(Context.ArgName),
                            Context.Parameter.Name);
                }

                Context.Return.Write("new global::System.IntPtr(&{0})",
                    Generator.GeneratedIdentifier(Context.ArgName));
                return true;
            }

            PrimitiveType primitive;
            if (pointee.IsPrimitiveType(out primitive) || pointee.IsEnumType())
            {
                var param = Context.Parameter;

                // From MSDN: "note that a ref or out parameter is classified as a moveable
                // variable". This means we must create a local variable to hold the result
                // and then assign this value to the parameter.

                if (param.IsOut || param.IsInOut)
                {
                    var typeName = Type.TypePrinterDelegate(pointee);

                    if (param.IsInOut)
                        Context.SupportBefore.WriteLine("{0} _{1} = {1};", typeName, param.Name);
                    else
                        Context.SupportBefore.WriteLine("{0} _{1};", typeName, param.Name);

                    Context.Return.Write("&_{0}", param.Name);
                }
                else
                    Context.Return.Write(Context.Parameter.Name);

                return true;
            }

            return pointer.Pointee.Visit(this, quals);
        }

        private string MarshalStringToUnmanaged(string varName)
        {
            if (Equals(Context.Driver.Options.Encoding, Encoding.ASCII))
            {
                return string.Format("Marshal.StringToHGlobalAnsi({0})", varName);
            }
            if (Equals(Context.Driver.Options.Encoding, Encoding.Unicode) ||
                Equals(Context.Driver.Options.Encoding, Encoding.BigEndianUnicode))
            {
                return string.Format("Marshal.StringToHGlobalUni({0})", varName);
            }
            throw new NotSupportedException(string.Format("{0} is not supported yet.",
                Context.Driver.Options.Encoding.EncodingName));
        }

        public override bool VisitPrimitiveType(PrimitiveType primitive, TypeQualifiers quals)
        {
            switch (primitive)
            {
                case PrimitiveType.Void:
                    return true;
                case PrimitiveType.Bool:
                case PrimitiveType.Char:
                case PrimitiveType.UChar:
                case PrimitiveType.Short:
                case PrimitiveType.UShort:
                case PrimitiveType.Int:
                case PrimitiveType.UInt:
                case PrimitiveType.Long:
                case PrimitiveType.ULong:
                case PrimitiveType.LongLong:
                case PrimitiveType.ULongLong:
                case PrimitiveType.Float:
                case PrimitiveType.Double:
                case PrimitiveType.WideChar:
                    Context.Return.Write(Helpers.SafeIdentifier(Context.Parameter.Name));
                    return true;
                case PrimitiveType.Char16:
                    return false;
            }

            throw new NotImplementedException();
        }

        public override bool VisitTypedefType(TypedefType typedef, TypeQualifiers quals)
        {
            if (!VisitType(typedef, quals))
                return false;

            var decl = typedef.Declaration;

            FunctionType func;
            if (decl.Type.IsPointerTo<FunctionType>(out func))
            {
                VisitDelegateType(func, typedef.Declaration.OriginalName);
                return true;
            }

            return decl.Type.Visit(this);
        }

        public override bool VisitTemplateParameterType(TemplateParameterType param, TypeQualifiers quals)
        {
            Context.Return.Write(param.Parameter.Name);
            return true;
        }

        public override bool VisitClassDecl(Class @class)
        {
            if (!VisitDeclaration(@class))
                return false;

            if (@class.IsValueType)
            {
                MarshalValueClass();
            }
            else
            {
                MarshalRefClass(@class);
            }

            return true;
        }

        private void MarshalRefClass(Class @class)
        {
            var method = Context.Function as Method;
            if (method != null
                && method.Conversion == MethodConversionKind.FunctionToInstanceMethod
                && Context.ParameterIndex == 0)
            {
                Context.Return.Write("{0}", Helpers.InstanceIdentifier);
                return;
            }

            string param = Context.Parameter.Name;
            Type type = Context.Parameter.Type.Desugar();
            if (type.IsAddress())
            {
                Class decl;
                if (type.TryGetClass(out decl) && decl.IsValueType)
                    Context.Return.Write("{0}.{1}", param, Helpers.InstanceIdentifier);
                else
                    Context.Return.Write("{0} == ({2}) null ? global::System.IntPtr.Zero : {0}.{1}", param,
                        Helpers.InstanceIdentifier, type);
                return;
            }

            var qualifiedIdentifier = CSharpMarshalNativeToManagedPrinter.QualifiedIdentifier(
                @class.OriginalClass ?? @class);
            Context.Return.Write(
                "ReferenceEquals({0}, null) ? new {1}.Internal() : *({1}.Internal*) ({0}.{2})", param,
                qualifiedIdentifier, Helpers.InstanceIdentifier);
        }

        private void MarshalValueClass()
        {
            Context.Return.Write("{0}.ToInternal()", Context.Parameter.Name);
        }

        public override bool VisitFieldDecl(Field field)
        {
            if (!VisitDeclaration(field))
                return false;

            Context.Parameter = new Parameter
            {
                Name = Context.ArgName,
                QualifiedType = field.QualifiedType
            };

            return field.Type.Visit(this, field.QualifiedType.Qualifiers);
        }

        public override bool VisitProperty(Property property)
        {
            if (!VisitDeclaration(property))
                return false;

            Context.Parameter = new Parameter
            {
                Name = Context.ArgName,
                QualifiedType = property.QualifiedType
            };

            return base.VisitProperty(property);
        }

        public override bool VisitEnumDecl(Enumeration @enum)
        {
            Context.Return.Write(Helpers.SafeIdentifier(Context.Parameter.Name));
            return true;
        }

        public override bool VisitClassTemplateDecl(ClassTemplate template)
        {
            return VisitClassDecl(template.TemplatedClass);
        }

        public override bool VisitFunctionTemplateDecl(FunctionTemplate template)
        {
            return template.TemplatedFunction.Visit(this);
        }
    }

    public static class CSharpMarshalExtensions
    {
        public static void CSharpMarshalToNative(this QualifiedType type,
            CSharpMarshalManagedToNativePrinter printer)
        {
            (printer.Context as CSharpMarshalContext).FullType = type;
            type.Visit(printer);
        }

        public static void CSharpMarshalToNative(this Type type,
            CSharpMarshalManagedToNativePrinter printer)
        {
            CSharpMarshalToNative(new QualifiedType(type), printer);
        }

        public static void CSharpMarshalToNative(this ITypedDecl decl,
            CSharpMarshalManagedToNativePrinter printer)
        {
            CSharpMarshalToNative(decl.QualifiedType, printer);
        }

        public static void CSharpMarshalToManaged(this QualifiedType type,
            CSharpMarshalNativeToManagedPrinter printer)
        {
            (printer.Context as CSharpMarshalContext).FullType = type;
            type.Visit(printer);
        }

        public static void CSharpMarshalToManaged(this Type type,
            CSharpMarshalNativeToManagedPrinter printer)
        {
            CSharpMarshalToManaged(new QualifiedType(type), printer);
        }

        public static void CSharpMarshalToManaged(this ITypedDecl decl,
            CSharpMarshalNativeToManagedPrinter printer)
        {
            CSharpMarshalToManaged(decl.QualifiedType, printer);
        }
    }
}


text:
<?php

namespace App\Http\Requests\Admin;

use Illuminate\Foundation\Http\FormRequest;

class StoreOfficialDomainRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'country_code' => 'required|in:,'.implode(',', array_keys(trans('countries'))),
            'domain' => 'required'
        ];
    }
}


text:
from constant import BaseErrorCode, CheckSlotsErrorCode
"""
 QA 数据库
"""
from db import DB
from config import project_config as cfg

class Base(object):

    def __init__(self):
        self.db = DB()

    def save(self, qa):
        return self.db.save(qa.type_, qa.slots, qa.answer)

    def delete(self, qa):
        return self.db.delete(qa.type, qa.slots, qa.answer)

    def update(self, qa):
        return self.db.update(qa.type, qa.slots, qa.answer)

    def query(self, type_, slots):
        code, slots_lost = check_slots(type_, slots)
        if code is not CheckSlotsErrorCode.Success:
            return CheckSlotsErrorCode.LossInSlots, slots_lost
        r = self.db.query(type_, slots)
        if len(r) == 0:
            return BaseErrorCode.NoAnswer, None
        if len(r) > 1:
            return BaseErrorCode.MoreThanOne, r
        return BaseErrorCode.Success, r[0]

    def add_exception(self, exception):
        return self.db.save_exception(exception.text, exception.type_)

def check_slots(type_, slots):
    need_slots = cfg['types'][type_]['slots']
    if len(need_slots) == len(slots):
        return CheckSlotsErrorCode.Success, 'success'
    missing_type = [slot for slot in need_slots if slot not in need_slots]
    return CheckSlotsErrorCode.LossInSlots, missing_type

class QA(object):
    """
        slots: []
    """
    def __init__(self, type_, slots, answer):
        self.type_ = type_
        self.slots = slots
        self.answer = answer

class QException(object):
    def __init__(self, text, type_):
        self.type_ = type_
        self.text = text

if __name__ == '__main__':
    qas = [
        QA('map', {'location': '骨科'}, '三楼'),
        QA('map', {'location': '内科'}, '二楼'),
        QA('consult', {'phenomenon': '头痛'}, '神经科'),
        QA('consult', {'phenomenon': '感冒'}, '内科'),
        QA('information', {'info': '挂号'}, '上午九点到下午三点'),
        QA('information', {'info': '急诊'}, '每天都有')
    ]
    for qa in qas:
        Base().save(qa)


text:
// Test BigInt functions
let bigintVal: bigint = BigInt(123);
bigintVal = BigInt("456");
new BigInt(123); // should error
bigintVal = BigInt.asIntN(8, 0xFFFFn);
bigintVal = BigInt.asUintN(8, 0xFFFFn);
bigintVal = bigintVal.valueOf();
let stringVal: string = bigintVal.toString();
stringVal = bigintVal.toString(2);
stringVal = bigintVal.toLocaleString();
stringVal = bigintVal.toLocaleString('de-DE');
stringVal = bigintVal.toLocaleString('de-DE', { style: 'currency' });
stringVal = bigintVal.toLocaleString('de-DE', { style: 'currency', currency: 'EUR' })

// Test BigInt64Array
let bigIntArray: BigInt64Array = new BigInt64Array();
bigIntArray = new BigInt64Array(10);
bigIntArray = new BigInt64Array([1n, 2n, 3n]);
bigIntArray = new BigInt64Array([1, 2, 3]); // should error
bigIntArray = new BigInt64Array(new ArrayBuffer(80));
bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8);
bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8, 3);
let len: number = bigIntArray.length;
bigIntArray.length = 10; // should error
let arrayBufferLike: ArrayBufferView = bigIntArray;

// Test BigUint64Array
let bigUintArray: BigUint64Array = new BigUint64Array();
bigUintArray = new BigUint64Array(10);
bigUintArray = new BigUint64Array([1n, 2n, 3n]);
bigUintArray = new BigUint64Array([1, 2, 3]); // should error
bigUintArray = new BigUint64Array(new ArrayBuffer(80));
bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8);
bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8, 3);
len = bigIntArray.length;
bigIntArray.length = 10; // should error
arrayBufferLike = bigIntArray;

// Test added DataView methods
const dataView = new DataView(new ArrayBuffer(80));
dataView.setBigInt64(1, -1n);
dataView.setBigInt64(1, -1n, true);
dataView.setBigInt64(1, -1); // should error
dataView.setBigUint64(2, 123n);
dataView.setBigUint64(2, 123n, true);
dataView.setBigUint64(2, 123); // should error
bigintVal = dataView.getBigInt64(1);
bigintVal = dataView.getBigInt64(1, true);
bigintVal = dataView.getBigUint64(2);
bigintVal = dataView.getBigUint64(2, true);

// Test emitted declarations files
const w = 12n; // should emit as const w = 12n
const x = -12n; // should emit as const x = -12n
const y: 12n = 12n; // should emit type 12n
let z = 12n; // should emit type bigint in declaration file

// Test Intl methods with new parameter type
new Intl.NumberFormat("fr").format(3000n);
new Intl.NumberFormat("fr").format(bigintVal);


text:
<?xml version="1.0" encoding="UTF-8"?>
<config version="3.1.3" id="e204eb32bf6043da93001b25fd108e51" rev="82d8ea9c3dc14c56ba4b40ab31e755e9">
  <features>
    <optional>MULTIDOMAIN</optional>
    <optional>SKIP_GROUPS</optional>
    <optional>SKIP_SUSPENDING_ADMINS</optional>
    <optional>MD5_PASSWORD</optional>
    <optional>GOOGLE_ORGUNITS</optional>
    <optional>ALIAS_SYNCHRONIZATION</optional>
    <optional>SUSPEND_USERS</optional>
    <optional>DYNAMIC_GROUPS</optional>
    <optional>SHA1_PASSWORD</optional>
    <optional>SKIP_SHARED_CONTACTS</optional>
    <optional>GROUP_DESCRIPTION</optional>
    <optional>GOOGLE_QUOTA</optional>
    <optional>GIVEN_NAME</optional>
    <optional>FAMILY_NAME</optional>
    <optional>SKIP_ORGUNIT_PROVISIONING</optional>
    <optional>INDEPENDENT_GROUP_SYNC</optional>
    <optional>NON_ADDRESS_PRIMARY_KEY</optional>
    <optional>BASE64_PASSWORD</optional>
    <optional>SKIP_USER_PROFILES</optional>
    <optional>SKIP_EXISTING_PASSWORDS</optional>
    <optional>FORCE_PASSWORD_CHANGE</optional>
    <optional>GROUP_OWNER</optional>
    <optional>SKIP_CALENDAR_RESOURCES</optional>
    <required>SUPPRESS_DOMAIN</required>
  </features>
  <logging>
    <defaultLogLevel>INFO</defaultLogLevel>
    <format>[%d{ISO8601}] [%t] [%p] [%C{3}] %m%n</format>
    <logFile>Z:\logs\google-apps-sync.log</logFile>
    <maximumLogBytes>2147483648</maximumLogBytes>
    <logFileCount>1</logFileCount>
  </logging>
  <notification>
    <smtpRelay>aspmx.l.google.com</smtpRelay>
    <fromAddress>hagelk@tukwila.wednet.edu</fromAddress>
    <toAddress>accountcheck@tukwila.wednet.edu</toAddress>
    <ignoreRetrievalInfo>false</ignoreRetrievalInfo>
    <ignoreRetrievalWarnings>false</ignoreRetrievalWarnings>
    <ignoreRetrievalErrors>false</ignoreRetrievalErrors>
  </notification>
  <eventLimits>
    <deleteUserLimitPCT>5</deleteUserLimitPCT>
    <suspendUserLimitPCT>50</suspendUserLimitPCT>
    <deleteGroupLimitPCT>5</deleteGroupLimitPCT>
    <deleteOrgunitLimitPCT>5</deleteOrgunitLimitPCT>
    <deleteSharedContactLimitPCT>5</deleteSharedContactLimitPCT>
    <deleteCalendarResourceLimitPCT>5</deleteCalendarResourceLimitPCT>
  </eventLimits>
  <maxCacheLifetime>691200</maxCacheLifetime>
  <plugins>
    <remote>
      <plugin class="com.google.usersyncapp.plugin.google.GooglePlugin">
        <config version="0.2">
          <domain>tukwila.wednet.edu</domain>
          <loginMethod>OAUTH2</loginMethod>
          <oAuth2RefreshToken></oAuth2RefreshToken>
          <googleUsersSyncThreads>30</googleUsersSyncThreads>
          <googleProfilesSyncThreads>30</googleProfilesSyncThreads>
          <googleContactsSyncThreads>15</googleContactsSyncThreads>
          <nonAddressPrimaryKeyMapFile>nonAddressPrimaryKeyFile.tsv</nonAddressPrimaryKeyMapFile>
          <passwordTimestampFile>passwordTimestampCache.tsv</passwordTimestampFile>
        </config>
      </plugin>
    </remote>
    <local>
      <plugin class="com.google.usersyncapp.plugin.ldap.LDAPPlugin">
        <config version="0.2">
          <serverType>ACTIVE_DIRECTORY</serverType>
          <connectMethod>STANDARD</connectMethod>
          <hostname>10.30.30.2</hostname>
          <port>389</port>
          <basedn>ou=TSD,dc=tsd,dc=int</basedn>
          <authType>SIMPLE</authType>
          <authUser>CN=kris hagel,CN=Users,DC=tsd,DC=int</authUser>
          <authCredentialsEncrypted></authCredentialsEncrypted>
          <nonAddressPrimaryKeyAttrName>objectGUID</nonAddressPrimaryKeyAttrName>
          <emailAttrName>mail</emailAttrName>
          <aliasAttrName>proxyAddresses</aliasAttrName>
          <dominoWhiteSpaceReplaceChar>.</dominoWhiteSpaceReplaceChar>
          <givenNameAttrName>givenName</givenNameAttrName>
          <familyNameAttrName>sn</familyNameAttrName>
          <defaultPasswordEncrypted></defaultPasswordEncrypted>
          <generatedPasswordLength>8</generatedPasswordLength>
          <resultsPageSize>1000</resultsPageSize>
          <orgunits>
            <search>
              <priority>1</priority>
              <scope>SUBTREE</scope>
              <filter>(objectClass=organizationalUnit)</filter>
              <descriptionAttrName>description</descriptionAttrName>
            </search>
          </orgunits>
          <users>
            <search>
              <priority>1</priority>
              <basedn>OU=FOS,OU=Students,OU=TSD,DC=tsd,DC=int</basedn>
              <suspended>false</suspended>
              <scope>SUBTREE</scope>
              <orgName>Foster/Students</orgName>
              <filter>(&(objectCategory=person)(objectClass=user)(mail=*)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))</filter>
            </search>
            <search>
              <priority>2</priority>
              <basedn>OU=SHO,OU=Students,OU=TSD,DC=tsd,DC=int</basedn>
              <suspended>false</suspended>
              <scope>SUBTREE</scope>
              <orgName>Showalter/Students</orgName>
              <filter>(&(objectCategory=person)(objectClass=user)(mail=*)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))</filter>
            </search>
            <search>
              <priority>3</priority>
              <basedn>OU=CAS,OU=Students,OU=TSD,DC=tsd,DC=int</basedn>
              <suspended>false</suspended>
              <scope>SUBTREE</scope>
              <orgName>Cascade/Students</orgName>
              <filter>(&(objectCategory=person)(objectClass=user)(mail=*)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))</filter>
            </search>
            <search>
              <priority>4</priority>
              <basedn>OU=THO,OU=Students,OU=TSD,DC=tsd,DC=int</basedn>
              <suspended>false</suspended>
              <scope>SUBTREE</scope>
              <orgName>Thorndyke/Students</orgName>
              <filter>(&(objectCategory=person)(objectClass=user)(mail=*)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))</filter>
            </search>
            <search>
              <priority>5</priority>
              <basedn>OU=TUK,OU=Students,OU=TSD,DC=tsd,DC=int</basedn>
              <suspended>false</suspended>
              <scope>SUBTREE</scope>
              <orgName>Tukwila/Students</orgName>
              <filter>(&(objectCategory=person)(objectClass=user)(mail=*)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))</filter>
            </search>
            <search>
              <priority>6</priority>
              <basedn>OU=Staff,OU=TSDTukwila,OU=TSD,DC=tsd,DC=int</basedn>
              <suspended>false</suspended>
              <scope>SUBTREE</scope>
              <orgName>Tukwila</orgName>
              <filter>(&(objectCategory=person)(objectClass=user)(mail=*)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))</filter>
            </search>
            <search>
              <priority>7</priority>
              <basedn>OU=Staff,OU=TSDThorndyke,OU=TSD,DC=tsd,DC=int</basedn>
              <suspended>false</suspended>
              <scope>SUBTREE</scope>
              <orgName>Thorndyke</orgName>
              <filter>(&(objectCategory=person)(objectClass=user)(mail=*)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))</filter>
            </search>
            <search>
              <priority>8</priority>
              <basedn>OU=Staff,OU=TSDShowalter,OU=TSD,DC=tsd,DC=int</basedn>
              <suspended>false</suspended>
              <scope>SUBTREE</scope>
              <orgName>Showalter</orgName>
              <filter>(&(objectCategory=person)(objectClass=user)(mail=*)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))</filter>
            </search>
            <search>
              <priority>9</priority>
              <basedn>OU=Staff,OU=TSDFoster,OU=TSD,DC=tsd,DC=int</basedn>
              <suspended>false</suspended>
              <scope>SUBTREE</scope>
              <orgName>Foster</orgName>
              <filter>(&(objectCategory=person)(objectClass=user)(mail=*)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))</filter>
            </search>
            <search>
              <priority>10</priority>
              <basedn>OU=Staff,OU=TSDCascadeView,OU=TSD,DC=tsd,DC=int</basedn>
              <suspended>false</suspended>
              <scope>SUBTREE</scope>
              <orgName>Cascade</orgName>
              <filter>(&(objectCategory=person)(objectClass=user)(mail=*)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))</filter>
            </search>
            <search>
              <priority>11</priority>
              <basedn>OU=Staff,OU=TSDAdmin,OU=TSD,DC=tsd,DC=int</basedn>
              <suspended>false</suspended>
              <scope>SUBTREE</scope>
              <orgName>Admin</orgName>
              <filter>(&(objectCategory=person)(objectClass=user)(mail=*)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))</filter>
            </search>
            <search>
              <priority>12</priority>
              <basedn>OU=Staff,OU=Inactive Accounts,OU=TSD,DC=tsd,DC=int</basedn>
              <suspended>false</suspended>
              <scope>SUBTREE</scope>
              <orgName>Inactives</orgName>
              <filter>(&(objectCategory=person)(objectClass=user)(mail=*))</filter>
            </search>
            <search>
              <priority>13</priority>
              <basedn>OU=ServiceAccounts,OU=Inactive Accounts,OU=TSD,DC=tsd,DC=int</basedn>
              <suspended>false</suspended>
              <scope>SUBTREE</scope>
              <orgName>Admin/Other</orgName>
              <filter>(&(objectCategory=person)(objectClass=user)(mail=*))</filter>
            </search>
          </users>
          <groups>
            <search>
              <priority>1</priority>
              <basedn>OU=Groups,OU=CAS,OU=Students,OU=TSD,DC=tsd,DC=int</basedn>
              <scope>SUBTREE</scope>
              <filter>(&(objectClass=group)(cn=*))</filter>
              <memberAttrName>member</memberAttrName>
              <groupIdentifierAttr>mail</groupIdentifierAttr>
              <groupDisplayNameAttribute>name</groupDisplayNameAttribute>
              <groupDescriptionAttribute>description</groupDescriptionAttribute>
              <ownerDnAttribute>managedBy</ownerDnAttribute>
              <userEmailAttribute>mail</userEmailAttribute>
            </search>
            <search>
              <priority>2</priority>
              <basedn>OU=Groups,OU=FOS,OU=Students,OU=TSD,DC=tsd,DC=int</basedn>
              <scope>SUBTREE</scope>
              <filter>(&(objectClass=group)(cn=*))</filter>
              <memberAttrName>member</memberAttrName>
              <groupIdentifierAttr>mail</groupIdentifierAttr>
              <groupDisplayNameAttribute>name</groupDisplayNameAttribute>
              <groupDescriptionAttribute>description</groupDescriptionAttribute>
              <ownerDnAttribute>managedBy</ownerDnAttribute>
              <userEmailAttribute>mail</userEmailAttribute>
            </search>
            <search>
              <priority>3</priority>
              <basedn>OU=Groups,OU=SHO,OU=Students,OU=TSD,DC=tsd,DC=int</basedn>
              <scope>SUBTREE</scope>
              <filter>(&(objectClass=group)(cn=*))</filter>
              <memberAttrName>member</memberAttrName>
              <groupIdentifierAttr>mail</groupIdentifierAttr>
              <groupDisplayNameAttribute>name</groupDisplayNameAttribute>
              <groupDescriptionAttribute>description</groupDescriptionAttribute>
              <ownerDnAttribute>managedBy</ownerDnAttribute>
              <userEmailAttribute>mail</userEmailAttribute>
            </search>
            <search>
              <priority>4</priority>
              <basedn>OU=Groups,OU=THO,OU=Students,OU=TSD,DC=tsd,DC=int</basedn>
              <scope>SUBTREE</scope>
              <filter>(&(objectClass=group)(cn=*))</filter>
              <memberAttrName>member</memberAttrName>
              <groupIdentifierAttr>mail</groupIdentifierAttr>
              <groupDisplayNameAttribute>name</groupDisplayNameAttribute>
              <groupDescriptionAttribute>description</groupDescriptionAttribute>
              <ownerDnAttribute>managedBy</ownerDnAttribute>
              <userEmailAttribute>mail</userEmailAttribute>
            </search>
            <search>
              <priority>5</priority>
              <basedn>OU=Groups,OU=TUK,OU=Students,OU=TSD,DC=tsd,DC=int</basedn>
              <scope>SUBTREE</scope>
              <filter>(&(objectClass=group)(cn=*))</filter>
              <memberAttrName>member</memberAttrName>
              <groupIdentifierAttr>mail</groupIdentifierAttr>
              <groupDisplayNameAttribute>name</groupDisplayNameAttribute>
              <groupDescriptionAttribute>description</groupDescriptionAttribute>
              <ownerDnAttribute>managedBy</ownerDnAttribute>
              <userEmailAttribute>mail</userEmailAttribute>
            </search>
          </groups>
          <sharedContacts>
            <search>
              <priority>1</priority>
              <scope>SUBTREE</scope>
              <companyNameAttrName>company</companyNameAttrName>
              <departmentAttrName>department</departmentAttrName>
              <jobTitleAttrName>title</jobTitleAttrName>
              <fullNameAttrName>displayName</fullNameAttrName>
              <officeLocationAttrName>physicalDeliveryOfficeName</officeLocationAttrName>
              <assistantAttrName>assistant</assistantAttrName>
              <managerAttrName>manager</managerAttrName>
              <syncKeyAttrName>objectGUID</syncKeyAttrName>
              <notesAttrName>info</notesAttrName>
              <workAddressStreetAttrName>streetAddress</workAddressStreetAttrName>
              <workAddressPoboxAttrName>postOfficeBox</workAddressPoboxAttrName>
              <workAddressCityAttrName>l</workAddressCityAttrName>
              <workAddressStateAttrName>st</workAddressStateAttrName>
              <workAddressPostalCodeAttrName>postalCode</workAddressPostalCodeAttrName>
              <workAddressCountryAttrName>co</workAddressCountryAttrName>
              <workEmailAddressesAttrName>mail</workEmailAddressesAttrName>
              <employeeIdsAttrName>employeeID</employeeIdsAttrName>
              <faxNumbersAttrName>facsimileTelephoneNumber</faxNumbersAttrName>
              <homePhonesAttrName>homePhone</homePhonesAttrName>
              <mobilePhonesAttrName>mobile</mobilePhonesAttrName>
              <workMobilePhonesAttrName>pager</workMobilePhonesAttrName>
              <workPhonesAttrName>telephoneNumber</workPhonesAttrName>
              <assistantPhoneAttrName>telephoneAssistant</assistantPhoneAttrName>
              <webPageAddressesAttrName>wWWHomePage</webPageAddressesAttrName>
              <filter>(objectClass=contact)</filter>
            </search>
          </sharedContacts>
          <userProfiles>
            <search>
              <priority>1</priority>
              <scope>SUBTREE</scope>
              <companyNameAttrName>company</companyNameAttrName>
              <departmentAttrName>department</departmentAttrName>
              <jobTitleAttrName>title</jobTitleAttrName>
              <officeLocationAttrName>physicalDeliveryOfficeName</officeLocationAttrName>
              <primaryEmailAddressAttrName>mail</primaryEmailAddressAttrName>
              <assistantAttrName>assistant</assistantAttrName>
              <managerAttrName>manager</managerAttrName>
              <notesAttrName>info</notesAttrName>
              <workAddressStreetAttrName>streetAddress</workAddressStreetAttrName>
              <workAddressPoboxAttrName>postOfficeBox</workAddressPoboxAttrName>
              <workAddressCityAttrName>l</workAddressCityAttrName>
              <workAddressStateAttrName>st</workAddressStateAttrName>
              <workAddressPostalCodeAttrName>postalCode</workAddressPostalCodeAttrName>
              <workAddressCountryAttrName>co</workAddressCountryAttrName>
              <employeeIdsAttrName>employeeID</employeeIdsAttrName>
              <faxNumbersAttrName>facsimileTelephoneNumber</faxNumbersAttrName>
              <homePhonesAttrName>homePhone</homePhonesAttrName>
              <mobilePhonesAttrName>mobile</mobilePhonesAttrName>
              <workMobilePhonesAttrName>pager</workMobilePhonesAttrName>
              <workPhonesAttrName>telephoneNumber</workPhonesAttrName>
              <assistantPhoneAttrName>telephoneAssistant</assistantPhoneAttrName>
              <webPageAddressesAttrName>wWWHomePage</webPageAddressesAttrName>
              <filter>(&(objectCategory=person)(objectClass=user)(mail=*)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))</filter>
            </search>
          </userProfiles>
          <calendarResources>
            <search>
              <priority>1</priority>
              <scope>SUBTREE</scope>
              <resourceIdAttrName>[objectGUID]</resourceIdAttrName>
              <displayNameAttrName>[displayName]</displayNameAttrName>
              <descriptionAttrName>[description]</descriptionAttrName>
              <filter>(&(mailNickName=*)(msExchUserAccountControl=2))</filter>
            </search>
          </calendarResources>
          <mailingLists />
        </config>
      </plugin>
    </local>
  </plugins>
</config>


text:
import FeatureNameStatistics from 'goog:proto.featureStatistics.FeatureNameStatistics';
import * as utils from '../../common/utils';

Polymer({
  is: 'facets-overview-row-legend',

  properties: {
    numeric: Boolean,
    showWeighted: Boolean,
    hasCustom: Boolean,
    dataModel: Object,
    _entries: {
      type: Array,
      computed: '_getEntries(numeric, showWeighted, hasCustom)'
    },
  },
  _getEntries: function(numeric: boolean, showWeighted: boolean,
                        hasCustom: boolean) {
    return utils.getLegendEntries(numeric, showWeighted, hasCustom);
  },
});


text:
@interface ALViewController () <ALTimeIntervalPickerViewDelegate>

@property (weak, nonatomic) IBOutlet ALTimeIntervalPickerView *pickerView;

@end

@implementation ALViewController

- (void)setPickerView:(ALTimeIntervalPickerView *)pickerView
{
	_pickerView = pickerView;
	_pickerView.delegate = self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)timeIntervalPickerView:(ALTimeIntervalPickerView *)timeIntervalPickerView
		didSelectTimeInterval:(NSTimeInterval)timeInterval
{
	NSLog(@"Selected: %lf",timeInterval);
}

@end