text:
import {OpaqueToken} from '@angular/core/src/di';
import {ListWrapper, StringMapWrapper} from '@angular/facade/src/collection';
import {BaseException, WrappedException} from '@angular/facade/src/exceptions';
import {Math, NumberWrapper, StringWrapper, isBlank, isPresent} from '@angular/facade/src/lang';

import {Options} from '../common_options';
import {Metric} from '../metric';
import {PerfLogFeatures, WebDriverExtension} from '../web_driver_extension';

/**
 * A metric that reads out the performance log
 */
export class PerflogMetric extends Metric {
  // TODO(tbosch): use static values when our transpiler supports them
  static get PROVIDERS(): any[] { return _PROVIDERS; }
  // TODO(tbosch): use static values when our transpiler supports them
  static get SET_TIMEOUT(): OpaqueToken { return _SET_TIMEOUT; }

  /** @internal */
  private _remainingEvents: Array<{[key: string]: any}>;
  /** @internal */
  private _measureCount: number;
  /** @internal */
  private _perfLogFeatures: PerfLogFeatures;

  /**
   * @param driverExtension
   * @param setTimeout
   * @param microMetrics Name and description of metrics provided via console.time / console.timeEnd
   **/
  constructor(
      /** @internal */
      private _driverExtension: WebDriverExtension,
      /** @internal */
      private _setTimeout: Function,
      /** @internal */
      private _microMetrics: {[key: string]: any},
      /** @internal */
      private _forceGc: boolean,
      /** @internal */
      private _captureFrames: boolean,
      /** @internal */
      private _receivedData: boolean,
      /** @internal */
      private _requestCount: boolean) {
    super();

    this._remainingEvents = [];
    this._measureCount = 0;
    this._perfLogFeatures = _driverExtension.perfLogFeatures();
    if (!this._perfLogFeatures.userTiming) {
      // User timing is needed for navigationStart.
      this._receivedData = false;
      this._requestCount = false;
    }
  }

  describe(): {[key: string]: any} {
    var res = {
      'scriptTime': 'script execution time in ms, including gc and render',
      'pureScriptTime': 'script execution time in ms, without gc nor render'
    };
    if (this._perfLogFeatures.render) {
      res['renderTime'] = 'render time in ms';
    }
    if (this._perfLogFeatures.gc) {
      res['gcTime'] = 'gc time in ms';
      res['gcAmount'] = 'gc amount in kbytes';
      res['majorGcTime'] = 'time of major gcs in ms';
      if (this._forceGc) {
        res['forcedGcTime'] = 'forced gc time in ms';
        res['forcedGcAmount'] = 'forced gc amount in kbytes';
      }
    }
    if (this._receivedData) {
      res['receivedData'] = 'encoded bytes received since navigationStart';
    }
    if (this._requestCount) {
      res['requestCount'] = 'count of requests sent since navigationStart';
    }
    if (this._captureFrames) {
      if (!this._perfLogFeatures.frameCapture) {
        var warningMsg = 'WARNING: Metric requested, but not supported by driver';
        // using dot syntax for metric name to keep them grouped together in console reporter
        res['frameTime.mean'] = warningMsg;
        res['frameTime.worst'] = warningMsg;
        res['frameTime.best'] = warningMsg;
        res['frameTime.smooth'] = warningMsg;
      } else {
        res['frameTime.mean'] = 'mean frame time in ms (target: 16.6ms for 60fps)';
        res['frameTime.worst'] = 'worst frame time in ms';
        res['frameTime.best'] = 'best frame time in ms';
        res['frameTime.smooth'] = 'percentage of frames that hit 60fps';
      }
    }
    StringMapWrapper.forEach(
        this._microMetrics, (desc, name) => { StringMapWrapper.set(res, name, desc); });
    return res;
  }

  beginMeasure(): Promise<any> {
    var resultPromise = Promise.resolve(null);
    if (this._forceGc) {
      resultPromise = resultPromise.then((_) => this._driverExtension.gc());
    }
    return resultPromise.then((_) => this._beginMeasure());
  }

  endMeasure(restart: boolean): Promise<{[key: string]: any}> {
    if (this._forceGc) {
      return this._endPlainMeasureAndMeasureForceGc(restart);
    } else {
      return this._endMeasure(restart);
    }
  }

  /** @internal */
  private _endPlainMeasureAndMeasureForceGc(restartMeasure: boolean) {
    return this._endMeasure(true).then((measureValues) => {
      // disable frame capture for measurements during forced gc
      var originalFrameCaptureValue = this._captureFrames;
      this._captureFrames = false;
      return this._driverExtension.gc()
          .then((_) => this._endMeasure(restartMeasure))
          .then((forceGcMeasureValues) => {
            this._captureFrames = originalFrameCaptureValue;
            StringMapWrapper.set(measureValues, 'forcedGcTime', forceGcMeasureValues['gcTime']);
            StringMapWrapper.set(measureValues, 'forcedGcAmount', forceGcMeasureValues['gcAmount']);
            return measureValues;
          });
    });
  }

  /** @internal */
  private _beginMeasure(): Promise<any> {
    return this._driverExtension.timeBegin(this._markName(this._measureCount++));
  }

  /** @internal */
  private _endMeasure(restart: boolean): Promise<{[key: string]: any}> {
    var markName = this._markName(this._measureCount - 1);
    var nextMarkName = restart ? this._markName(this._measureCount++) : null;
    return this._driverExtension.timeEnd(markName, nextMarkName)
        .then((_) => this._readUntilEndMark(markName));
  }

  /** @internal */
  private _readUntilEndMark(markName: string, loopCount: number = 0, startEvent = null) {
    if (loopCount > _MAX_RETRY_COUNT) {
      throw new BaseException(`Tried too often to get the ending mark: ${loopCount}`);
    }
    return this._driverExtension.readPerfLog().then((events) => {
      this._addEvents(events);
      var result = this._aggregateEvents(this._remainingEvents, markName);
      if (isPresent(result)) {
        this._remainingEvents = events;
        return result;
      }
      var resolve: (result: any) => void;
      var promise = new Promise(res => { resolve = res; });
      this._setTimeout(() => resolve(this._readUntilEndMark(markName, loopCount + 1)), 100);
      return promise;
    });
  }

  /** @internal */
  private _addEvents(events: {[key: string]: string}[]) {
    var needSort = false;
    events.forEach(event => {
      if (StringWrapper.equals(event['ph'], 'X')) {
        needSort = true;
        var startEvent = {};
        var endEvent = {};
        StringMapWrapper.forEach(event, (value, prop) => {
          startEvent[prop] = value;
          endEvent[prop] = value;
        });
        startEvent['ph'] = 'B';
        endEvent['ph'] = 'E';
        endEvent['ts'] = startEvent['ts'] + startEvent['dur'];
        this._remainingEvents.push(startEvent);
        this._remainingEvents.push(endEvent);
      } else {
        this._remainingEvents.push(event);
      }
    });
    if (needSort) {
      // Need to sort because of the ph==='X' events
      ListWrapper.sort(this._remainingEvents, (a, b) => {
        var diff = a['ts'] - b['ts'];
        return diff > 0 ? 1 : diff < 0 ? -1 : 0;
      });
    }
  }

  /** @internal */
  private _aggregateEvents(events: Array<{[key: string]: any}>, markName): {[key: string]: any} {
    var result = {'scriptTime': 0, 'pureScriptTime': 0};
    if (this._perfLogFeatures.gc) {
      result['gcTime'] = 0;
      result['majorGcTime'] = 0;
      result['gcAmount'] = 0;
    }
    if (this._perfLogFeatures.render) {
      result['renderTime'] = 0;
    }
    if (this._captureFrames) {
      result['frameTime.mean'] = 0;
      result['frameTime.best'] = 0;
      result['frameTime.worst'] = 0;
      result['frameTime.smooth'] = 0;
    }
    StringMapWrapper.forEach(this._microMetrics, (desc, name) => { result[name] = 0; });
    if (this._receivedData) {
      result['receivedData'] = 0;
    }
    if (this._requestCount) {
      result['requestCount'] = 0;
    }

    var markStartEvent = null;
    var markEndEvent = null;
    var gcTimeInScript = 0;
    var renderTimeInScript = 0;

    var frameTimestamps = [];
    var frameTimes = [];
    var frameCaptureStartEvent = null;
    var frameCaptureEndEvent = null;

    var intervalStarts: {[key: string]: any} = {};
    var intervalStartCount: {[key: string]: number} = {};
    events.forEach((event) => {
      var ph = event['ph'];
      var name = event['name'];
      var microIterations = 1;
      var microIterationsMatch = name.match(_MICRO_ITERATIONS_REGEX);
      if (isPresent(microIterationsMatch)) {
        name = microIterationsMatch[1];
        microIterations = NumberWrapper.parseInt(microIterationsMatch[2], 10);
      }

      if (StringWrapper.equals(ph, 'b') && StringWrapper.equals(name, markName)) {
        markStartEvent = event;
      } else if (StringWrapper.equals(ph, 'e') && StringWrapper.equals(name, markName)) {
        markEndEvent = event;
      }

      let isInstant = StringWrapper.equals(ph, 'I') || StringWrapper.equals(ph, 'i');
      if (this._requestCount && StringWrapper.equals(name, 'sendRequest')) {
        result['requestCount'] += 1;
      } else if (this._receivedData && StringWrapper.equals(name, 'receivedData') && isInstant) {
        result['receivedData'] += event['args']['encodedDataLength'];
      } else if (StringWrapper.equals(name, 'navigationStart')) {
        // We count data + requests since the last navigationStart
        // (there might be chrome extensions loaded by selenium before our page, so there
        // will likely be more than one navigationStart).
        if (this._receivedData) {
          result['receivedData'] = 0;
        }
        if (this._requestCount) {
          result['requestCount'] = 0;
        }
      }
      if (isPresent(markStartEvent) && isBlank(markEndEvent) &&
          event['pid'] === markStartEvent['pid']) {
        if (StringWrapper.equals(ph, 'b') && StringWrapper.equals(name, _MARK_NAME_FRAME_CAPUTRE)) {
          if (isPresent(frameCaptureStartEvent)) {
            throw new BaseException('can capture frames only once per benchmark run');
          }
          if (!this._captureFrames) {
            throw new BaseException(
                'found start event for frame capture, but frame capture was not requested in benchpress');
          }
          frameCaptureStartEvent = event;
        } else if (
            StringWrapper.equals(ph, 'e') && StringWrapper.equals(name, _MARK_NAME_FRAME_CAPUTRE)) {
          if (isBlank(frameCaptureStartEvent)) {
            throw new BaseException('missing start event for frame capture');
          }
          frameCaptureEndEvent = event;
        }

        if (isInstant) {
          if (isPresent(frameCaptureStartEvent) && isBlank(frameCaptureEndEvent) &&
              StringWrapper.equals(name, 'frame')) {
            frameTimestamps.push(event['ts']);
            if (frameTimestamps.length >= 2) {
              frameTimes.push(
                  frameTimestamps[frameTimestamps.length - 1] -
                  frameTimestamps[frameTimestamps.length - 2]);
            }
          }
        }

        if (StringWrapper.equals(ph, 'B') || StringWrapper.equals(ph, 'b')) {
          if (isBlank(intervalStarts[name])) {
            intervalStartCount[name] = 1;
            intervalStarts[name] = event;
          } else {
            intervalStartCount[name]++;
          }
        } else if (
            (StringWrapper.equals(ph, 'E') || StringWrapper.equals(ph, 'e')) &&
            isPresent(intervalStarts[name])) {
          intervalStartCount[name]--;
          if (intervalStartCount[name] === 0) {
            var startEvent = intervalStarts[name];
            var duration = (event['ts'] - startEvent['ts']);
            intervalStarts[name] = null;
            if (StringWrapper.equals(name, 'gc')) {
              result['gcTime'] += duration;
              var amount =
                  (startEvent['args']['usedHeapSize'] - event['args']['usedHeapSize']) / 1000;
              result['gcAmount'] += amount;
              var majorGc = event['args']['majorGc'];
              if (isPresent(majorGc) && majorGc) {
                result['majorGcTime'] += duration;
              }
              if (isPresent(intervalStarts['script'])) {
                gcTimeInScript += duration;
              }
            } else if (StringWrapper.equals(name, 'render')) {
              result['renderTime'] += duration;
              if (isPresent(intervalStarts['script'])) {
                renderTimeInScript += duration;
              }
            } else if (StringWrapper.equals(name, 'script')) {
              result['scriptTime'] += duration;
            } else if (isPresent(this._microMetrics[name])) {
              result[name] += duration / microIterations;
            }
          }
        }
      }
    });
    if (!isPresent(markStartEvent) || !isPresent(markEndEvent)) {
      // not all events have been received, no further processing for now
      return null;
    }

    if (isPresent(markEndEvent) && isPresent(frameCaptureStartEvent) &&
        isBlank(frameCaptureEndEvent)) {
      throw new BaseException('missing end event for frame capture');
    }
    if (this._captureFrames && isBlank(frameCaptureStartEvent)) {
      throw new BaseException(
          'frame capture requested in benchpress, but no start event was found');
    }
    if (frameTimes.length > 0) {
      this._addFrameMetrics(result, frameTimes);
    }
    result['pureScriptTime'] = result['scriptTime'] - gcTimeInScript - renderTimeInScript;
    return result;
  }

  /** @internal */
  private _addFrameMetrics(result: {[key: string]: any}, frameTimes: any[]) {
    result['frameTime.mean'] = frameTimes.reduce((a, b) => a + b, 0) / frameTimes.length;
    var firstFrame = frameTimes[0];
    result['frameTime.worst'] = frameTimes.reduce((a, b) => a > b ? a : b, firstFrame);
    result['frameTime.best'] = frameTimes.reduce((a, b) => a < b ? a : b, firstFrame);
    result['frameTime.smooth'] =
        frameTimes.filter(t => t < _FRAME_TIME_SMOOTH_THRESHOLD).length / frameTimes.length;
  }

  /** @internal */
  private _markName(index) { return `${_MARK_NAME_PREFIX}${index}`; }
}

var _MICRO_ITERATIONS_REGEX = /(.+)\*(\d+)$/;

var _MAX_RETRY_COUNT = 20;
var _MARK_NAME_PREFIX = 'benchpress';
var _SET_TIMEOUT = new OpaqueToken('PerflogMetric.setTimeout');

var _MARK_NAME_FRAME_CAPUTRE = 'frameCapture';
// using 17ms as a somewhat looser threshold, instead of 16.6666ms
var _FRAME_TIME_SMOOTH_THRESHOLD = 17;

var _PROVIDERS = [
  {
    provide: PerflogMetric,
    useFactory: (driverExtension, setTimeout, microMetrics, forceGc, captureFrames, receivedData,
                 requestCount) =>
                    new PerflogMetric(
                        driverExtension, setTimeout, microMetrics, forceGc, captureFrames,
                        receivedData, requestCount),
    deps: [
      WebDriverExtension, _SET_TIMEOUT, Options.MICRO_METRICS, Options.FORCE_GC,
      Options.CAPTURE_FRAMES, Options.RECEIVED_DATA, Options.REQUEST_COUNT
    ]
  },
  {provide: _SET_TIMEOUT, useValue: (fn, millis) => <any>setTimeout(fn, millis)}
];


text:
zhk
===

Zookeeper haskell bindings (http://zookeeper.apache.org/)

redpajama_set_name: RedPajamaGithub


text:
export const ADD_MESSAGE = 'ADD_MESSAGE';
export const REMOTE_MESSAGE = 'REMOTE_MESSAGE';
export const CHANGE_USER_NAME = 'CHANGE_USER_NAME';
export const CHANGE_USER_COLOR = 'CHANGE_USER_COLOR';
export const FRAME_UPDATE = 'FRAME_UPDATE';
export const SHOW_OPTIONS = 'SHOW_OPTIONS';
export const SOCKET_CONNECTED = 'SOCKET_CONNECTED';
export const SOCKET_DISCONNECTED = 'SOCKET_DISCONNECTED';
export const PLAYER_COUNT_UPDATE = 'PLAYER_COUNT_UPDATE';
export const SHOW_KEYS = 'SHOW_KEYS';


text:
package org.apache.hive.hcatalog.data;

import java.util.List;

import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.StandardStructObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.StructField;

public class HCatRecordObjectInspector extends StandardStructObjectInspector {

  protected HCatRecordObjectInspector(List<String> structFieldNames,
                    List<ObjectInspector> structFieldObjectInspectors) {
    super(structFieldNames, structFieldObjectInspectors);
  }

  @Override
  public Object getStructFieldData(Object data, StructField fieldRef) {
    if (data == null) {
      return new IllegalArgumentException("Data passed in to get field from was null!");
    }

    int fieldID = ((MyField) fieldRef).getFieldID();
    if (!(fieldID >= 0 && fieldID < fields.size())) {
      throw new IllegalArgumentException("Invalid field index [" + fieldID + "]");
    }

    return ((HCatRecord) data).get(fieldID);
  }

  @Override
  public List<Object> getStructFieldsDataAsList(Object o) {
    return ((HCatRecord) o).getAll();
  }

}


text:
# `renv`: Tasks related to `renv`

## Includes

Other `Taskfile`s included:

- [`gitignore`](gitignore.md)
- [`r`](r.md)

## Tasks

### `detect` : Detect which `renv` related tasks are needed

Adds the `renv:install` task if there is a `renv.lock` file.

#### Command

```sh
test -f renv.lock && echo renv:install >> .stencila/tasks/detected
```

### `ensure` : Ensure `renv` is installed

Checks whether the R package `renv` is installed and installs it if necessary.

#### Commands

1. [`r:install`](r.md#install)

2. `R --slave -e "install.packages('renv', repos = 'https://cloud.r-project.org')"`

### `gitignore` : Update `.gitignore` for use with `renv`

Adds a line to the local `.gitignore` file (creating one if necessary) so that
the `renv` folder is ignored by Git.

#### Command

1. [`gitignore:add`](gitignore.md#add) `PATTERNS=renv`

### `init` : Initialize `renv` in a directory

#### Commands

1. [`ensure`](#ensure)

2. [`gitignore`](#gitignore)

3. `R --slave -e "renv::init(repos = c( ...`

### `add` : Add an R package using `renv`

#### Commands

1. [`ensure`](#ensure)

2. [`init`](#init)

3. [`gitignore`](#gitignore)

4. `R --slave -e "renv::install('{{.PACKAGE}}'); renv::snapshot(type='all')"`

### `remove` : Remove an R package using `renv`

#### Commands

1. [`ensure`](#ensure)

2. [`init`](#init)

3. `R --slave -e "renv::remove('{{.PACKAGE}}'); renv::snapshot(type='all')"`

### `install` : Install all R packages in `renv.lock` using `renv`

#### Commands

1. [`ensure`](#ensure)

2. [`init`](#init)

3. [`gitignore`](#gitignore)

4. `R --slave -e "renv::install()"`

### `update` : Update all R packages in `renv.lock` using `renv`

#### Commands

1. [`ensure`](#ensure)

2. [`init`](#init)

3. [`gitignore`](#gitignore)

4. `R --slave -e "renv::update()"`

### `clean` : Delete package installation artifacts created by `renv`

Removes the `renv` directory.

#### Command

```sh
rm -rf renv
```

### `purge` : Remove `renv` and associated files from the project

Deletes `renv.lock` and `renv`.

#### Commands

1. `rm -f renv.lock`

2. [`clean`](#clean)


text:
Authors
=======

* benoit barthelet


text: a


text:
package dockergen

import (
	"bufio"
	"io"
	"os"
	"strings"
	"unicode"
)

func GetEndpoint(endpoint string) (string, error) {
	defaultEndpoint := "unix:///var/run/docker.sock"
	if os.Getenv("DOCKER_HOST") != "" {
		defaultEndpoint = os.Getenv("DOCKER_HOST")
	}

	if endpoint != "" {
		defaultEndpoint = endpoint
	}

	_, _, err := parseHost(defaultEndpoint)
	if err != nil {
		return "", err
	}

	return defaultEndpoint, nil
}

// splitKeyValueSlice takes a string slice where values are of the form
// KEY, KEY=, KEY=VALUE  or KEY=NESTED_KEY=VALUE2, and returns a map[string]string where items
// are split at their first `=`.
func splitKeyValueSlice(in []string) map[string]string {
	env := make(map[string]string)
	for _, entry := range in {
		parts := strings.SplitN(entry, "=", 2)
		if len(parts) != 2 {
			parts = append(parts, "")
		}
		env[parts[0]] = parts[1]
	}
	return env

}

func isBlank(str string) bool {
	for _, r := range str {
		if !unicode.IsSpace(r) {
			return false
		}
	}
	return true
}

func removeBlankLines(reader io.Reader, writer io.Writer) {
	breader := bufio.NewReader(reader)
	bwriter := bufio.NewWriter(writer)

	for {
		line, err := breader.ReadString('\n')

		if !isBlank(line) {
			bwriter.WriteString(line)
		}

		if err != nil {
			break
		}
	}

	bwriter.Flush()
}

// pathExists returns whether the given file or directory exists or not
func pathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}


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

import com.google.common.base.Preconditions;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Multimap;
import com.google.devtools.build.lib.skylarkinterface.SkylarkCallable;
import com.google.devtools.build.lib.skylarkinterface.SkylarkModule;
import com.google.devtools.build.lib.skylarkinterface.SkylarkSignature;
import java.text.Collator;
import java.util.Collection;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;

/**
 * A class representing a Skylark built-in object with its {@link SkylarkSignature} annotation
 * and the {@link SkylarkCallable} methods it might have.
 */
public final class SkylarkModuleDoc extends SkylarkDoc {
  private final SkylarkModule module;
  private final Class<?> classObject;
  private final Map<String, SkylarkBuiltinMethodDoc> builtinMethodMap;
  private final Multimap<String, SkylarkJavaMethodDoc> javaMethods;
  private TreeMap<String, SkylarkMethodDoc> methodMap;
  private final String title;

  public SkylarkModuleDoc(SkylarkModule module, Class<?> classObject) {
    this.module = Preconditions.checkNotNull(
        module, "Class has to be annotated with SkylarkModule: %s", classObject);
    this.classObject = classObject;
    this.builtinMethodMap = new TreeMap<>(Collator.getInstance(Locale.US));
    this.methodMap = new TreeMap<>(Collator.getInstance(Locale.US));
    this.javaMethods = HashMultimap.<String, SkylarkJavaMethodDoc>create();
    if (module.title().isEmpty()) {
      this.title = module.name();
    } else {
      this.title = module.title();
    }
  }

  @Override
  public String getName() {
    return module.name();
  }

  @Override
  public String getDocumentation() {
    return module.doc();
  }

  public String getTitle() {
    return title;
  }

  public SkylarkModule getAnnotation() {
    return module;
  }

  public Class<?> getClassObject() {
    return classObject;
  }

  public void addMethod(SkylarkBuiltinMethodDoc method) {
    methodMap.put(method.getName(), method);
    builtinMethodMap.put(method.getName(), method);
  }

  public void addMethod(SkylarkJavaMethodDoc method) {
    if (!method.documented()) {
      return;
    }

    String shortName = method.getName();
    Collection<SkylarkJavaMethodDoc> overloads = javaMethods.get(shortName);
    if (!overloads.isEmpty()) {
      method.setOverloaded(true);
      // Overload information only needs to be updated if we're discovering the first overload
      // (= the second method of the same name).
      if (overloads.size() == 1) {
        Iterables.getOnlyElement(overloads).setOverloaded(true);
      }
    }
    javaMethods.put(shortName, method);
    // If the method is overloaded, getName() now returns a longer, unique name including
    // the names of the parameters.
    String uniqueName = method.getName();
    Preconditions.checkState(
        !methodMap.containsKey(uniqueName),
        "There are multiple overloads of %s with the same signature!",
        uniqueName);
    methodMap.put(uniqueName, method);
  }

  public boolean javaMethodsNotCollected() {
    return javaMethods.isEmpty();
  }

  public Map<String, SkylarkBuiltinMethodDoc> getBuiltinMethods() {
    return builtinMethodMap;
  }

  public Collection<SkylarkJavaMethodDoc> getJavaMethods() {
    return javaMethods.values();
  }

  public Collection<SkylarkMethodDoc> getMethods() {
    return methodMap.values();
  }
}


text:
import * as React from 'react';
import { useSelector } from 'react-redux';
import { RootState } from '../../../js/store';

interface Props {
  key: string;
  label: string;
}

const InfoTabView = (props: Props) => {
  const { activeTab, tabViewVisible } = useSelector(
    (store: RootState) => store.appState.leftPanel
  );
  const { language, narrative, alternativeNarrative } = useSelector(
    (store: RootState) => store.appSettings
  );
  const { selectedLanguage } = useSelector(
    (store: RootState) => store.appState
  );

  const narrativeContent =
    selectedLanguage === language ? narrative : alternativeNarrative;

  const tabViewIsVisible = tabViewVisible && activeTab === props.label;
  return (
    <>
      {tabViewIsVisible && (
        <div
          className="info-content-container"
          dangerouslySetInnerHTML={{ __html: narrativeContent }}
        />
      )}
    </>
  );
};

export default InfoTabView;


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:orientation="vertical" >

    <com.lingganhezi.myapp.ui.Topbar
        style="@style/Topbar"
        app:title="@string/about_topbar_title" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:gravity="center"
        android:orientation="vertical"
        android:paddingLeft="@dimen/login_registe_padding"
        android:paddingRight="@dimen/login_registe_padding" >

        <ImageView
            android:layout_width="@dimen/login_logo_size"
            android:layout_height="@dimen/login_logo_size"
            android:src="@drawable/logo" />

        <TextView
            android:layout_marginTop="40dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="@string/about_company_name"
            android:textSize="@dimen/font_size_title" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="@string/about_company_info"
            android:textColor="@color/default_light_grey_color" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="@string/about_copyright"
            android:textColor="@color/default_light_grey_color" />
    </LinearLayout>

</LinearLayout>


text:
function SegmentQuery() {
	var $container = $('
  Add Filter ...
');
	var me = this;
	this.query = function () {
		var $children = $container.parent().children();
		var query = [];

		for (var i = 0; i < $children.length; i++) {

			var $child = $($children[i]);
			if ($child.hasClass('hidden')) continue;
			var ele = {};
			//type: "purchase", f: "avg", field: "amount", operator: ">", value: 5,
			//conditions: ["amount", ">", 2, "and", "price", "==", 40]
			if ($child.attr('data-type') == 'action') {
				ele.type = $child.data('id');
				ele.f = $child.data('f');
				ele.fields = [];
				var $conds = $child.find('.id_condition');
				for (var t = 0; t < $conds.length; t++) if ($conds.hasOwnProperty(t)) {
					var $cond = $($conds[t]);

					//jump over deleted condition
					if ($cond.hasClass('hidden')) continue;

					if (ele.fields.length !== 0) ele.fields.push('and');
					ele.fields.push($cond.find('.id_fi').val());
					ele.fields.push($cond.find('.id_op').val());
					ele.fields.push($cond.find('.id_val').val());
				}
				ele.operator = $child.find('.id_fop').find('.id_op').val();
				ele.value = $child.find('.id_fop').find('.id_val').val();
				query.push(ele);
			}
			else if ($child.attr('data-type') == 'prop') {
				ele.type = undefined;
				ele.field = $child.data('code');
				ele.operator = $child.find('.id_fop').find('.id_op').val();
				ele.value = $child.find('.id_fop').find('.id_val').val();
				query.push(ele);
			}
			else {
				//do nothing
			}
		}
		var out = [query[0]];
		for (var i in query) {
			if (i > 0) {
				out.push('and');
				out.push(query[i]);
			}
		}

		return out;
	};

	this.produce = function (callback, data) {
		var $data = $('
');
		var $action2level = $('

Total of occours

Sum

Average

');

		//find item by name
		function find(name) {
			for (var i in data) {
				if (data[i].type == 'action' && data[i].name == name) {
					return data[i];
				}
			}
			return null;
		}

		//convert data to better form
		for (var i  in data) {
			var item = data[i];
			var $litem = $('
');

			if (item.type == 'action') {
				$litem.attr('data-type', 'action');
				$litem.attr('data-value', item.name);
				$litem.attr('data-id', item.id);
				var $a = $('' + he.encode(item.name) + '');
				$litem.append($a);
				$litem.append($action2level.clone());
			}
			else {
				$litem.attr('data-type', 'prop');
				$litem.attr('data-id', he.encode(item.name));
				$litem.attr('data-value', he.encode(item.dpname));
				var $a = $('' + he.encode(item.dpname) + '');
				$litem.append($a);
			}
			$data.append($litem)
		}

		var segmentop = new SegmentOp();

		$container.find('.id_largequery').menu({
			content: $data[0].outerHTML,
			flyOut: true,
			showSpeed: 0,
			selback: largequeryselback
		});

		function remove() {
			$container.addClass('hidden');
		}

		function largequeryselback(values) {
			//make sure 2nd level is selected
			if (values.length == 1 && values[0].type === 'action') return;

			$container.find('.id_rmbtn').unbind('click', remove).bind('click', remove);
			//check if user change select or create a new one
			if ($container.data('edited') !== 'true') //change
			{
				//append another query
				var seg = new SegmentQuery();
				seg.produce(function (html) {
					$container.after(html);
				}, data);
			}

			//mark that list has been edited
			$container.data('edited', 'true');
			$container.find('.id_rmbtn').removeClass('hidden');
			if (values[0].type === 'action') {
				$container.attr('data-id', values[0].id);
				$container.attr('data-type', 'action');
				if (values[1].value == 'count') {
					$container.attr('data-f', 'count');
					$container.find('.id_largequery').html('Has done ' + values[0].value);

					//make a operator select
					$container.append(segmentop.produce({fields: find(values[0].value).fields}));
				}
				else if (values[1].value == 'sum') {
					$container.attr('data-f', 'sum');
					$container.find('.id_largequery').html('Has done  ' + values[0].value + " which sum of");

					//make a operator select
					$container.append(segmentop.produce({
						data: find(values[0].value).fields,
						fields: find(values[0].value).fields
					}));
				}
				else if (values[1].value == 'avg') {
					$container.attr('data-f', 'avg');
					$container.find('.id_largequery').html('Has done ' + values[0].value + ' which average of ');

					//make a operator select
					$container.append(segmentop.produce({
						data: find(values[0].value).fields,
						fields: find(values[0].value).fields
					}));
				}
				else
					throw "wrong data";

				//$container.find('.id_rmbtn').removeClass('hidden');
				//segmentop.destroy();

			}
			else if (values[0].type === 'prop') {
				$container.attr('data-type', 'prop');
				$container.attr('data-code', values[0].id);
				$container.find('.id_largequery').html('Has ' + values[0].value);

				segmentop.destroy();
				$container.append(segmentop.produce({canadd: false}));
			}

		}

		callback($container);
	}

}

function FieldOp() {
	var $container = $('');

	this.destroy = function () {
		$container.empty();
	};

	this.produce = function (options) {
		options = options || {};
		var field = "";
		if (options.data) {
			field = '<select class="form-control id_fi">';
			for (var i in options.data) {
				var f = options.data[i];
				field += '<option value="' + he.encode(f.code) + '">' + he.encode(f.name) + '</option>';
			}

			field += '</select> \
			<select class="form-control id_op mr5"> \
				<option value="less">less than</option> \
				<option value="greater">greater than</option> \
				<option value="equal">equal</option> \
				<option value="contain">contains</option> \
				<option value="startswith">starts with</option> \
				<option value="endswith">ends with</option> \
				<option value ="not">not equal</option> \
				<option value="from">from</option> \
				<option value ="fromto">from ... to ...</option> \
			</select> <input type="text" class="id_val form-control" />';
		}
		else { //for master field creation
			field += '\
			<select class="form-control id_op mr5"> \
				<option value="less">less than</option> \
				<option value="greater">greater than</option> \
				<option value="equal">equal</option> \
				<option value="contain">contains</option> \
				<option value="startswith">starts with</option> \
				<option value="endswith">ends with</option> \
				<option value ="not">not equal</option> \
				<option value="from">from</option> \
				<option value ="fromto">from ... to ...</option> \
			</select> <input type="text" class="id_val form-control" />';
		}

		if (field !== '' && options.defop !== undefined) {
			field = $(field).val(options.defop)[0].outerHTML;
		}
		var $fiselect = $('
' + field + '
');

		if (options.class !== undefined) {
			$fiselect.addClass(options.class);
		}

		if (options.canremove === false) {
			$fiselect.find('.id_rmbt').addClass('hidden');
		}

		$fiselect.find('.id_rmbt').click(function () {
			$fiselect.addClass('hidden');
		});

		$fiselect.change(function () {
			var val = $(this).val();

			if (val == 'from') {

			}
			else if (val == 'fromto') {

			}
			else if (val == 'isset' || val == 'isnotset') {

			}
			else {
				//cac phep toan thong thuong on string, number
			}

		});

		return $fiselect;
	};

	this.val = function () {
		if (val == 'from') {

		}
		else if (val == 'fromto') {

		}
		else if (val == 'isset' || val == 'isnotset') {

		}
		else {
			//cac phep toan thong thuong on string, number
		}
	};
}

function SegmentOp() {
	var $container = $('');
	var data, fields;

	//clear
	this.destroy = function () {
		$addBtn.detach();
		$container.empty();
		//$container = $('');
	};

	var $addBtn = $('');

	$addBtn.click(function () {
		var field = new FieldOp();
		var $field = field.produce({data: fields, class: "id_condition"});

		$container.append($field);
		$field.append($addBtn);
	});

	var field = new FieldOp();

	this.produce = function (options) {
		options = options || {};

		if (options.canadd == false) $addBtn.addClass('hidden');
		defop = options.defop;
		data = options.data;
		fields = options.fields;

		if (data !== undefined) {
			$container.append(field.produce({
				data: data,
				defop: options.defop,
				canremove: false,
				type: 'number',
				class: 'id_fop'
			}))
		}
		else {
			$container.append(field.produce({
				defop: options.defop,
				canremove: false,
				class: 'id_fop'
			}))
		}

		$container.append($addBtn);
		return $container;
	};

}


text:
module Desk
  # Custom error class for rescuing from all Desk.com errors
  class Error < StandardError
    attr_reader :http_headers

    def initialize(message, http_headers)
      http_headers ||= {}
      @http_headers = Hash[http_headers]
      super message
    end

    def ratelimit_reset
      Time.at(@http_headers.values_at('x-ratelimit-reset', 'X-RateLimit-Reset').detect {|value| value }.to_i)
    end

    def ratelimit_limit
      @http_headers.values_at('x-ratelimit-limit', 'X-RateLimit-Limit').detect {|value| value }.to_i
    end

    def ratelimit_remaining
      @http_headers.values_at('x-ratelimit-limit', 'X-RateLimit-Limit').detect {|value| value }.to_i
    end

    def retry_after
      [(ratelimit_reset - Time.now).ceil, 0].max
    end
  end

  # Raised when Desk returns the HTTP status code 400
  class BadRequest < Error; end

  # Raised when Desk returns the HTTP status code 401
  class Unauthorized < Error; end

  # Raised when Desk returns the HTTP status code 403
  class Forbidden < Error; end

  # Raised when Desk returns the HTTP status code 404
  class NotFound < Error; end

  # Raised when Desk returns the HTTP status code 406
  class NotAcceptable < Error; end

  # Raised when Desk returns the HTTP status code 420
  class EnhanceYourCalm < Error
    # The number of seconds your application should wait before requesting date from the Search API again
    #
    # @see http://dev.desk.com/pages/rate-limiting
    def retry_after
      @http_headers.values_at('retry-after', 'Retry-After').detect {|value| value }.to_i
    end
  end

  # Raised when Desk max_requests is reached and use_max_requests is set to true
  class TooManyRequests < StandardError; end

  # Raised when Desk returns the HTTP status code 500
  class InternalServerError < Error; end

  # Raised when Desk returns the HTTP status code 502
  class BadGateway < Error; end

  # Raised when Desk returns the HTTP status code 503
  class ServiceUnavailable < Error; end

  # Gem Specific Errors
  class DeskError < StandardError; end

  class SupportEmailNotSet < DeskError; end
end


text:
<button ng-click="count = count + 1" ng-init="count=0">
  Increment
</button>
<span>
  count: {{count}}
</span>


text:
package consts

const (
	// TestListUpdateCommitSubjectPrefix is the commit message prefix on commits
	// that update the full test lists results.
	TestListUpdateCommitSubjectPrefix = "Regres: Update test lists @ "
)


text:
#include "defs.h"

#include <glib.h>
#include <glib/gprintf.h>
#include <gtk/gtk.h>

#include <stdio.h>
#include <sys/stat.h>

#if WITH_LIBAPPINDICATOR
  #include <libappindicator/app-indicator.h>
#endif
#if WITH_LIBNOTIFY
  #include <libnotify/notify.h>
#endif

#include "sylmain.h"
#include "plugin.h"
#include "procmsg.h"
#include "procmime.h"
#include "utils.h"
#include "alertpanel.h"
#include "prefs_common.h"
#include "foldersel.h"
#include "account.h"
#include "unmime.h"
#include "../res/growl.xpm"
#include "../res/growlx.xpm"

#include <glib.h>
#include <glib/gi18n-lib.h>
#include <locale.h>

#include "copying.h"
#include "sylplugin_factory.h"
#include "sylnotify.h"

#define PLUGIN_NAME N_("SylNotify - notifier plug-in for Sylpheed")
#define PLUGIN_DESC N_("notifier plug-in for Sylpheed")

static SylPluginInfo info = {
  N_(PLUGIN_NAME),
  VERSION,
  "HAYASHI Kentaro",
  N_(PLUGIN_DESC)
};

static SylNotifyOption sylnotify_option;

void plugin_load(void)
{
  GtkWidget *mainwin;
  gchar *pattern;
  void *option;

  SYLPF_START_FUNC;

  syl_init_gettext(SYLNOTIFY, "lib/locale");

  debug_print(gettext("SylNotify notify support Plug-in"));
  debug_print(dgettext("SylNotify", "Notify support Plug-in"));

  syl_plugin_add_menuitem("/Tools", _("SylNotify Settings [SylNotify]"),
                          exec_sylnotify_menu_cb, NULL);

  g_signal_connect(syl_app_get(), "add-msg", G_CALLBACK(exec_sylnotify_cb), NULL);
  g_signal_connect(syl_app_get(), "init-done", G_CALLBACK(init_done_cb), NULL);
  g_signal_connect(syl_app_get(), "app-exit", G_CALLBACK(app_exit_cb), NULL);
  g_signal_connect(syl_app_get(), "app-force-exit", G_CALLBACK(app_force_exit_cb), NULL);

  syl_plugin_signal_connect("inc-mail-start", G_CALLBACK(inc_start_cb), NULL);
  syl_plugin_signal_connect("inc-mail-finished", G_CALLBACK(inc_finished_cb), NULL);

  mainwin = syl_plugin_main_window_get();

  option = &sylnotify_option;
  sylpf_setup_plugin_onoff_switch((SylPluginFactoryOption*)option,
                                  G_CALLBACK(exec_sylnotify_onoff_cb),
                                  (const char**)growl,
                                  (const char**)growlx);

  info.name = g_strdup(_(PLUGIN_NAME));
  info.description = g_strdup(_(PLUGIN_DESC));

  sylnotify_option.rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, SYLNOTIFYRC, NULL);
  sylnotify_option.rcfile = g_key_file_new();

  if (g_key_file_load_from_file(sylnotify_option.rcfile, sylnotify_option.rcpath, G_KEY_FILE_KEEP_COMMENTS, NULL)){
    sylnotify_option.startup_flag = GET_RC_BOOLEAN(SYLNOTIFY, "startup");
    debug_print("startup:%s", sylnotify_option.startup_flag ? "true" : "false");

    sylnotify_option.plugin_enabled = sylnotify_option.startup_flag;

    exec_sylnotify_onoff_cb();

    sylnotify_option.growl_flag=GET_RC_BOOLEAN(SYLNOTIFY, "growl");
    debug_print("use growl:%s\n", sylnotify_option.growl_flag ? "true" : "false");
    sylnotify_option.snarl_flag=GET_RC_BOOLEAN(SYLNOTIFY, "snarl");
    debug_print("use snarl:%s\n", sylnotify_option.snarl_flag ? "true" : "false");

    pattern = g_key_file_get_string(sylnotify_option.rcfile, SYLNOTIFY, "pattern", NULL);
    if (pattern != NULL) {
      if (strcmp(pattern, "summary") == 0) {
        sylnotify_option.pattern_summary_flag = TRUE;
        sylnotify_option.pattern_all_flag = FALSE;
      } else if (strcmp(pattern, "all") == 0) {
        sylnotify_option.pattern_summary_flag = FALSE;
        sylnotify_option.pattern_all_flag = TRUE;
      } else {
        sylnotify_option.pattern_summary_flag = TRUE;
        sylnotify_option.pattern_all_flag = FALSE;
      }
    } else {
      sylnotify_option.pattern_summary_flag = TRUE;
      sylnotify_option.pattern_all_flag = FALSE;
    }

    /* Growl */
    sylnotify_option.growl_option.use_gntp=GET_RC_BOOLEAN(SYLNOTIFY_GROWL, "gntp");
    debug_print("use gntp:%s\n", sylnotify_option.growl_option.use_gntp ? "true" : "false");
    sylnotify_option.growl_option.use_growlnotify=GET_RC_BOOLEAN(SYLNOTIFY_GROWL, "growlnotify");
    debug_print("use growlnotify:%s\n", sylnotify_option.growl_option.use_growlnotify ? "true" : "false");

    /* Snarl */
    sylnotify_option.snarl_option.use_snp=GET_RC_BOOLEAN(SYLNOTIFY_SNARL, "snp");
    debug_print("use snp:%s\n", sylnotify_option.snarl_option.use_snp ? "true" : "false");
    sylnotify_option.snarl_option.use_gntp=GET_RC_BOOLEAN(SYLNOTIFY_SNARL, "gntp");
    debug_print("use gntp:%s\n", sylnotify_option.snarl_option.use_gntp ? "true" : "false");
    sylnotify_option.snarl_option.use_heysnarl=GET_RC_BOOLEAN(SYLNOTIFY_SNARL, "heysnarl");
    debug_print("use heysnarl:%s\n", sylnotify_option.snarl_option.use_heysnarl ? "true" : "false");
    sylnotify_option.snarl_option.use_snarlcmd=GET_RC_BOOLEAN(SYLNOTIFY_SNARL, "snarlcmd");
    debug_print("use snarlcmd:%s\n", sylnotify_option.snarl_option.use_snarlcmd ? "true" : "false");

  } else {
      /**/
      sylnotify_option.startup_flag = FALSE;

      sylnotify_option.growl_option.active = TRUE;
      sylnotify_option.snarl_option.active = FALSE;

      sylnotify_option.growl_option.use_growlnotify = TRUE;
      sylnotify_option.snarl_option.use_snarlcmd = TRUE;
  }

#if WITH_LIBAPPINDICATOR
  create_app_indicator(&sylnotify_option);
#endif

  SYLPF_END_FUNC;
}

void plugin_unload(void)
{
  SYLPF_START_FUNC;

  g_free(sylnotify_option.rcpath);

  SYLPF_END_FUNC;
}

SylPluginInfo *plugin_info(void)
{
  return &info;
}

gint plugin_interface_version(void)
{
  /* sylpheed 3.2 or later since r3005 */
  return 0x0109;
}

static void init_done_cb(GObject *obj, gpointer data)
{
  gchar *cmdline;
  gint ret;

  SYLPF_START_FUNC;

  debug_print("[DEBUG init_done_cb");
  if (sylnotify_option.snarl_flag != FALSE) {
    if (sylnotify_option.snarl_option.use_heysnarl != FALSE) {
      cmdline = g_strdup_printf("\"%s\" \"register?app-sig=app/Sylpheed&title=%s&icon=%s\"",
                                       "C:\\Program Files (x86)\\full phat\\Snarl\\tools\\heysnarl.exe",
                                       "Sylpheed",
                                       "http://sylpheed.sraoss.jp/images/sylpheed.png"
                                       );
      ret = execute_command_line(cmdline, FALSE);
      debug_print("ret:%d", ret);
      switch (ret) {
      case SNARL_ERROR_TIMED_OUT:
        debug_print("[DEBUG] ret:%d timeout\n", ret);
        break;
      case SNARL_ERROR_FAILED:
        debug_print("[DEBUG] ret:%d failed\n", ret);
        break;
      case SNARL_ERROR_NOT_RUNNING:
        debug_print("[DEBUG] ret:%d not running\n", ret);
        break;
      default:
        break;
      }
    }
  }
  SYLPF_END_FUNC;
}

static void app_exit_cb(GObject *obj, gpointer data)
{
}
static void app_force_exit_cb(GObject *obj, gpointer data)
{
}

/**
 *
 */
static void prefs_ok_cb(GtkWidget *widget, gpointer data)
{
  gboolean flg;
  const gchar *buf;
  gsize sz;

  SYLPF_START_FUNC;

    g_key_file_load_from_file(sylnotify_option.rcfile, sylnotify_option.rcpath, G_KEY_FILE_KEEP_COMMENTS, NULL);

    flg = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(sylnotify_option.startup));
    SET_RC_BOOLEAN(SYLNOTIFY, "startup", flg);
    debug_print("startup:%s\n", flg ? "true" : "false");

    flg = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(sylnotify_option.snarl));
    SET_RC_BOOLEAN(SYLNOTIFY, "snarl", flg);
    debug_print("use snarl:%s\n", flg ? "true" : "false");

    flg = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(sylnotify_option.growl));
    SET_RC_BOOLEAN(SYLNOTIFY, "growl", flg);
    debug_print("use growl:%s\n", flg ? "true" : "false");

    flg = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(sylnotify_option.pattern_summary));
    if (flg != FALSE) {
      g_key_file_set_string (sylnotify_option.rcfile, SYLNOTIFY, "pattern", "summary");
      debug_print("use pattern:summary\n");
    }

    flg = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(sylnotify_option.pattern_all));
    if (flg != FALSE) {
      g_key_file_set_string (sylnotify_option.rcfile, SYLNOTIFY, "pattern", "all");
      debug_print("use pattern:all\n");
    }

    flg = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(sylnotify_option.snarl_option.snp));
    SET_RC_BOOLEAN(SYLNOTIFY_SNARL, "snp", flg);
    debug_print("use snarl snp:%s\n", flg ? "true" : "false");

    flg = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(sylnotify_option.snarl_option.gntp));
    SET_RC_BOOLEAN(SYLNOTIFY_SNARL, "gntp", flg);
    debug_print("use snarl gntp:%s\n", flg ? "true" : "false");

    flg = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(sylnotify_option.snarl_option.heysnarl));
    SET_RC_BOOLEAN(SYLNOTIFY_SNARL, "heysnarl", flg);
    debug_print("use heysnarl:%s\n", flg ? "true" : "false");

    flg = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(sylnotify_option.snarl_option.snarlcmd));
    SET_RC_BOOLEAN(SYLNOTIFY_SNARL, "snarlcmd", flg);
    debug_print("use snarlcmd:%s\n", flg ? "true" : "false");

    buf = gtk_entry_get_text(GTK_ENTRY(sylnotify_option.snarl_option.heysnarl_path));
    g_key_file_set_string (sylnotify_option.rcfile, SYLNOTIFY_SNARL, "heysnarl_path", buf);
    debug_print("use heysnarl path:%s\n", buf);

    buf = gtk_entry_get_text(GTK_ENTRY(sylnotify_option.snarl_option.snarlcmd_path));
    g_key_file_set_string (sylnotify_option.rcfile, SYLNOTIFY_SNARL, "snarlcmd_path", buf);
    debug_print("use snarlcmd path:%s\n", buf);

    flg = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(sylnotify_option.growl_option.gntp));
    SET_RC_BOOLEAN(SYLNOTIFY_GROWL, "gntp", flg);
    debug_print("use growl gntp:%s\n", flg ? "true" : "false");

    flg = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(sylnotify_option.growl_option.growlnotify));
    SET_RC_BOOLEAN(SYLNOTIFY_GROWL, "growlnotify", flg);
    debug_print("use growlnotify:%s\n", flg ? "true" : "false");

    buf = gtk_entry_get_text(GTK_ENTRY(sylnotify_option.growl_option.growlnotify_path));
    g_key_file_set_string (sylnotify_option.rcfile, SYLNOTIFY_GROWL, "growlnotify_path", buf);
    debug_print("use growlnotify path:%s\n", buf);

    buf=g_key_file_to_data(sylnotify_option.rcfile, &sz, NULL);
    g_file_set_contents(sylnotify_option.rcpath, buf, sz, NULL);

    gtk_widget_destroy(GTK_WIDGET(data));
  SYLPF_END_FUNC;
}
static void prefs_cancel_cb(GtkWidget *widget, gpointer data)
{
  SYLPF_START_FUNC;

    gtk_widget_destroy(GTK_WIDGET(data));

  SYLPF_END_FUNC;
}

#ifdef DEBUG
static void prefs_test_cb(GtkWidget *widget, gpointer data)
{
#if G_OS_WIN32
  gint ret;
  gchar *cmdline;
#endif

  SYLPF_START_FUNC;
#if 0
    gint sock = fd_connect_inet(SYLSNARL_PORT);
    gchar *buf = conv_unmime_header("SNP/3.0\r\nregister?app-sig=app/Sylpheed&title=Sylpheed\r\nnotify?app-sig=app/Sylpheed&title=From:&text=From:\nSubject:\ntext...\r\nEND\r\n", "UTF-8");
    debug_print("buf:%s", buf);
    fd_write_all(sock, buf, strlen(buf));
    fd_close(sock);
#endif
#if 0
    gint sock = fd_connect_inet(SYLGNTP_PORT);
    gchar *buf = "GNTP/1.0 REGISTER NONE\r\nApplication-Name:Sylpheed\r\nApplication-Icon:http://sylpheed.sraoss.jp/images/sylpheed.png\r\nNotifications-Count:1\r\n\r\nApplication-Name:Sylpheed\r\nNotification-Name:Sylpheed\r\nNotification-Title:title\r\nNotification-Text:text\r\n\r\n\r\n";
    debug_print("buf:%s", buf);
    fd_write_all(sock, buf, strlen(buf));
    fd_close(sock);
#endif

#if DEBUG
    sylnotify_option.growl_option.use_growlnotify = TRUE;
    if (sylnotify_option.growl_option.use_growlnotify != FALSE) {
      cmdline = g_strdup_printf("\"%s\" /a:%s /ai:%s /r:\"%s\" \"%s\"",
                                       "C:\\WinApp\\growlnotify\\growlnotify.exe",
                                       "Sylpheed",
                                       "http://sylpheed.sraoss.jp/images/sylpheed.png",
                                       "New Mail",
                                       "dummy"
                                       );
      ret = execute_command_line(cmdline, FALSE);
      cmdline = g_strdup_printf("\"%s\" /a:%s /n:\"%s\" /t:\"%s\" \"%s\"",
                                "C:\\WinApp\\growlnotify\\growlnotify.exe",
                                "Sylpheed",
                                "New Mail",
                                "件名",
                                "本文"
                                );
      ret = execute_command_line(cmdline, FALSE);
    }
    if (sylnotify_option.snarl_option.use_heysnarl != FALSE) {
      cmdline = g_strdup_printf("\"%s\" \"register?app-sig=app/Sylpheed&title=%s&icon=%s\"",
                                       "C:\\Program Files (x86)\\full phat\\Snarl\\tools\\heysnarl.exe",
                                       "Sylpheed",
                                       "http://sylpheed.sraoss.jp/images/sylpheed.png"
                                       );
      ret = execute_command_line(cmdline, FALSE);
      if (ret >= 0) {
        cmdline = g_strdup_printf("\"%s\" \"notify?app-sig=app/Sylpheed&title=%s&text=%s\"",
                                         "C:\\Program Files (x86)\\full phat\\Snarl\\tools\\heysnarl.exe",
                                         "subject",
                                         /*"http://sylpheed.sraoss.jp/images/sylpheed.png",*/
                                         "bodynextnext2hoge");
        execute_command_line(cmdline, FALSE);
      }
    }
#endif
  SYLPF_END_FUNC;
}
#endif

#ifdef G_OS_WIN32
static void snp_mail_cb( GtkButton *widget,
                     gpointer   data )
{
  SYLPF_START_FUNC;

  gtk_widget_set_sensitive(GTK_WIDGET(sylnotify_option.snarl_option.gntp), FALSE);

  SYLPF_END_FUNC;
}

static void gntp_mail_cb( GtkButton *widget,
                          gpointer   data )
{
  SYLPF_START_FUNC;

  gtk_widget_set_sensitive(GTK_WIDGET(sylnotify_option.snarl.snp), FALSE);

  SYLPF_END_FUNC;
}
#endif

static void exec_sylnotify_menu_cb(void)
{

  /* show modal dialog */
  GtkWidget *window;
  GtkWidget *vbox;
  GtkWidget *confirm_area;
  GtkWidget *ok_btn;
  GtkWidget *cancel_btn;
  GtkWidget *notebook;
  gchar *buf;

#if DEBUG
  GtkWidget *test_btn;
#endif

  SYLPF_START_FUNC;

  window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  gtk_container_set_border_width(GTK_CONTAINER(window), 8);
  gtk_widget_set_size_request(window, 400, 300);
  gtk_window_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
  gtk_window_set_modal(GTK_WINDOW(window), TRUE);
  gtk_window_set_policy(GTK_WINDOW(window), FALSE, TRUE, FALSE);
  gtk_widget_realize(window);

  vbox = gtk_vbox_new(FALSE, 6);
  gtk_widget_show(vbox);
  gtk_container_add(GTK_CONTAINER(window), vbox);

  /* notebook */
  notebook = gtk_notebook_new();
  /* main tab */
  create_config_main_page(notebook, sylnotify_option.rcfile);
#ifdef G_OS_WIN32
  /* Growl sylnotify_option tab */
  create_config_growl_page(notebook, sylnotify_option.rcfile);
  /* Snarl sylnotify_option tab */
  create_config_snarl_page(notebook, sylnotify_option.rcfile);
#endif
#ifdef G_OS_UNIX
  create_config_gol_page(notebook, sylnotify_option.rcfile);
#endif

  /* about, copyright tab */
  create_config_about_page(notebook, sylnotify_option.rcfile);

  gtk_widget_show(notebook);
  gtk_box_pack_start(GTK_BOX(vbox), notebook, TRUE, TRUE, 0);

  confirm_area = gtk_hbutton_box_new();
  gtk_button_box_set_layout(GTK_BUTTON_BOX(confirm_area), GTK_BUTTONBOX_END);
  gtk_box_set_spacing(GTK_BOX(confirm_area), 6);

  ok_btn = gtk_button_new_from_stock(GTK_STOCK_OK);
  GTK_WIDGET_SET_FLAGS(ok_btn, GTK_CAN_DEFAULT);
  gtk_box_pack_start(GTK_BOX(confirm_area), ok_btn, FALSE, FALSE, 0);
  gtk_widget_show(ok_btn);

  cancel_btn = gtk_button_new_from_stock(GTK_STOCK_CANCEL);
  GTK_WIDGET_SET_FLAGS(cancel_btn, GTK_CAN_DEFAULT);
  gtk_box_pack_start(GTK_BOX(confirm_area), cancel_btn, FALSE, FALSE, 0);
  gtk_widget_show(cancel_btn);

#if DEBUG
  test_btn = gtk_button_new_from_stock(GTK_STOCK_NETWORK);
  GTK_WIDGET_SET_FLAGS(cancel_btn, GTK_CAN_DEFAULT);
  gtk_box_pack_start(GTK_BOX(confirm_area), test_btn, FALSE, FALSE, 0);
  gtk_widget_show(test_btn);
#endif

  gtk_widget_show(confirm_area);

  gtk_box_pack_end(GTK_BOX(vbox), confirm_area, FALSE, FALSE, 0);
  gtk_widget_grab_default(ok_btn);

  gtk_window_set_title(GTK_WINDOW(window), _("SylNotify Settings [SylNotify]"));

  g_signal_connect(G_OBJECT(ok_btn), "clicked",
                   G_CALLBACK(prefs_ok_cb), window);
  g_signal_connect(G_OBJECT(cancel_btn), "clicked",
                   G_CALLBACK(prefs_cancel_cb), window);
#if DEBUG
  g_signal_connect(G_OBJECT(test_btn), "clicked",
                   G_CALLBACK(prefs_test_cb), window);
#endif

  /* load settings */
  if (g_key_file_load_from_file(sylnotify_option.rcfile, sylnotify_option.rcpath, G_KEY_FILE_KEEP_COMMENTS, NULL)){
    sylnotify_option.startup_flag = GET_RC_BOOLEAN(SYLNOTIFY, "startup");
    debug_print("startup:%s\n", sylnotify_option.startup_flag ? "true" : "false");
    if (sylnotify_option.startup_flag){
      gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(sylnotify_option.startup), TRUE);
    }

    sylnotify_option.snarl_flag = GET_RC_BOOLEAN(SYLNOTIFY, "snarl");
    debug_print("use snarl:%s\n", sylnotify_option.snarl_flag ? "true" : "false");
    if (sylnotify_option.snarl_flag != FALSE){
      gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(sylnotify_option.snarl), TRUE);
    }

    sylnotify_option.growl_flag = GET_RC_BOOLEAN(SYLNOTIFY, "growl");
    debug_print("use growl:%s\n", sylnotify_option.growl_flag ? "true" : "false");
    if (sylnotify_option.growl_flag != FALSE){
      gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(sylnotify_option.growl), TRUE);
    }

    sylnotify_option.snarl_option.use_snp = GET_RC_BOOLEAN(SYLNOTIFY_SNARL, "snp");
    debug_print("use snp:%s\n", sylnotify_option.snarl_option.use_snp ? "true" : "false");
    if (sylnotify_option.snarl_option.use_snp){
      gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(sylnotify_option.snarl_option.snp), TRUE);
    }

    sylnotify_option.snarl_option.use_gntp = GET_RC_BOOLEAN(SYLNOTIFY_SNARL, "gntp");
    debug_print("use gntp:%s\n", sylnotify_option.snarl_option.use_gntp ? "true" : "false");
    if (sylnotify_option.snarl_option.use_gntp){
      gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(sylnotify_option.snarl_option.gntp), TRUE);
    }

    sylnotify_option.snarl_option.use_heysnarl = GET_RC_BOOLEAN(SYLNOTIFY_SNARL, "heysnarl");
    debug_print("use heysnarl:%s\n", sylnotify_option.snarl_option.use_heysnarl ? "true" : "false");
    if (sylnotify_option.snarl_option.use_heysnarl != FALSE){
      gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(sylnotify_option.snarl_option.heysnarl), TRUE);
    }

    buf = g_key_file_get_string(sylnotify_option.rcfile, SYLNOTIFY_SNARL, "heysnarl_path", NULL);
    if (sylnotify_option.snarl_option.use_heysnarl != FALSE && buf != NULL){
      debug_print("use heysnarl path:%s\n", buf);
      gtk_entry_set_text(GTK_ENTRY(sylnotify_option.snarl_option.heysnarl_path), buf);
    }

    sylnotify_option.snarl_option.use_snarlcmd = GET_RC_BOOLEAN(SYLNOTIFY_SNARL, "snarlcmd");
    debug_print("use snarlcmd:%s\n", sylnotify_option.snarl_option.use_snarlcmd ? "true" : "false");
    if (sylnotify_option.snarl_option.use_snarlcmd != FALSE){
      gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(sylnotify_option.snarl_option.snarlcmd), TRUE);
    }

    buf = g_key_file_get_string(sylnotify_option.rcfile, SYLNOTIFY_SNARL, "snarlcmd_path", NULL);
    if (sylnotify_option.snarl_option.use_snarlcmd != FALSE && buf != NULL){
      debug_print("use snarl_cmd path:%s\n", buf);
      gtk_entry_set_text(GTK_ENTRY(sylnotify_option.snarl_option.snarlcmd_path), buf);
    }

    sylnotify_option.growl_option.use_gntp = GET_RC_BOOLEAN(SYLNOTIFY_GROWL, "gntp");
    debug_print("use growl gntp:%s\n", sylnotify_option.growl_option.use_gntp ? "true" : "false");
    if (sylnotify_option.growl_option.use_gntp != FALSE){
      gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(sylnotify_option.growl_option.gntp), TRUE);
    }

    sylnotify_option.growl_option.use_growlnotify = GET_RC_BOOLEAN(SYLNOTIFY_GROWL, "growlnotify");
    debug_print("use growlnotify:%s\n", sylnotify_option.growl_option.use_growlnotify ? "true" : "false");
    if (sylnotify_option.growl_option.use_growlnotify != FALSE){
      gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(sylnotify_option.growl_option.growlnotify), TRUE);
    }

    buf = g_key_file_get_string(sylnotify_option.rcfile, SYLNOTIFY_GROWL, "growlnotify_path", NULL);
    if (sylnotify_option.growl_option.use_growlnotify != FALSE && buf != NULL){
      debug_print("use growlnotify path:%s\n", buf);
      gtk_entry_set_text(GTK_ENTRY(sylnotify_option.growl_option.growlnotify_path), buf);
    }
  }else{
    /* default settings */
    sylnotify_option.startup_flag = FALSE;
  }

  gtk_widget_show(window);

  SYLPF_END_FUNC;
}

static SylNotifyAppEntry notification_applications[] = {
  {SYLNOTIFY_APP_NONE, "None"},
  {SYLNOTIFY_APP_GFW, "Growl for Windows"},
  {SYLNOTIFY_APP_SNARL, "Snarl"},
  {SYLNOTIFY_APP_GFL, "Growl For Linux"},
  {SYLNOTIFY_APP_LIBNOTIFY, "Libnotify"},
  {SYLNOTIFY_APP_LIBAPPINDICATOR, "AppIndicator"},
};

static GtkWidget *create_config_main_page(GtkWidget *notebook, GKeyFile *pkey)
{

  GtkWidget *vbox, *startup_align, *startup_frm, *startup_frm_align;
  GtkWidget *app_combo;
  gint i;
  GtkWidget *app_align;
  GtkWidget *app_frm;
  GtkWidget *app_frm_align;
  GtkWidget *vbox_app;
  GtkWidget *pattern_align;
  GtkWidget *pattern_frm;
  GtkWidget *pattern_frm_align;
  GtkWidget *vbox_pattern;
  GtkWidget *pattern_lbl;
  GtkWidget *general_lbl;

  SYLPF_START_FUNC;

  debug_print("create_config_main_page\n");
  if (notebook == NULL){
    return NULL;
  }
  /* startup */
  if (pkey!=NULL){
  }
  vbox = gtk_vbox_new(FALSE, 0);

  /**/
  startup_align = gtk_alignment_new(0, 0, 1, 1);
  gtk_alignment_set_padding(GTK_ALIGNMENT(startup_align), ALIGN_TOP, ALIGN_BOTTOM, ALIGN_LEFT, ALIGN_RIGHT);

  startup_frm = gtk_frame_new(_("Startup Sylnotify_Option"));
  startup_frm_align = gtk_alignment_new(0, 0, 1, 1);
  gtk_alignment_set_padding(GTK_ALIGNMENT(startup_frm_align), ALIGN_TOP, ALIGN_BOTTOM, ALIGN_LEFT, ALIGN_RIGHT);

  sylnotify_option.startup = gtk_check_button_new_with_label(_("Enable plugin on startup."));
  gtk_container_add(GTK_CONTAINER(startup_frm_align), sylnotify_option.startup);
  gtk_container_add(GTK_CONTAINER(startup_frm), startup_frm_align);
  gtk_container_add(GTK_CONTAINER(startup_align), startup_frm);

  gtk_widget_show(sylnotify_option.startup);

  /* Application */
  app_align = gtk_alignment_new(0, 0, 1, 1);
  gtk_alignment_set_padding(GTK_ALIGNMENT(app_align), ALIGN_TOP, ALIGN_BOTTOM, ALIGN_LEFT, ALIGN_RIGHT);

  app_frm = gtk_frame_new(_("Application"));
  app_frm_align = gtk_alignment_new(0, 0, 1, 1);
  gtk_alignment_set_padding(GTK_ALIGNMENT(app_frm_align), ALIGN_TOP, ALIGN_BOTTOM, ALIGN_LEFT, ALIGN_RIGHT);

  sylnotify_option.growl = gtk_radio_button_new_with_label(NULL, _("Growl"));
  sylnotify_option.snarl = gtk_radio_button_new_with_label_from_widget(GTK_RADIO_BUTTON (sylnotify_option.growl), _("Snarl"));

  vbox_app = gtk_vbox_new(FALSE, BOX_SPACE);
#if GTK_CHECK_VERSION(2, 24, 0)
  app_combo = gtk_combo_box_text_new();
#else
  app_combo = gtk_combo_box_new_text();
#endif
  for (i = 0; i < sizeof(notification_applications)/sizeof(SylNotifyAppEntry); i++) {
    switch (notification_applications[i].app_type) {
#if defined(G_OS_WIN32)
    case SYLNOTIFY_APP_NONE:
    case SYLNOTIFY_APP_GFW:
    case SYLNOTIFY_APP_SNARL:
#if GTK_CHECK_VERSION(2, 24, 0)
      gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(app_combo),
                                     notification_applications[i].app_desc);
#else
      gtk_combo_box_append_text(app_combo,
                                notification_applications[i].app_desc);
#endif
      break;
#endif
#if defined(G_OS_UNIX)
    case SYLNOTIFY_APP_NONE:
    case SYLNOTIFY_APP_GFL:
    case SYLNOTIFY_APP_LIBNOTIFY:
#if GTK_CHECK_VERSION(2, 24, 0)
      gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(app_combo),
                                     notification_applications[i].app_desc);
#else
      gtk_combo_box_append_text(app_combo,
                                notification_applications[i].app_desc);
      break;
#endif
    default:
      break;
    }
#endif
  }
  gtk_box_pack_start(GTK_BOX(vbox_app), app_combo, FALSE, FALSE, 0);

  gtk_container_add(GTK_CONTAINER(app_frm_align), vbox_app);
  gtk_container_add(GTK_CONTAINER(app_frm), app_frm_align);
  gtk_container_add(GTK_CONTAINER(app_align), app_frm);

  /* disable snarl */
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(sylnotify_option.growl), sylnotify_option.growl_flag);
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(sylnotify_option.snarl), sylnotify_option.snarl_flag);

  /* Notification */
  pattern_align = gtk_alignment_new(0, 0, 1, 1);
  gtk_alignment_set_padding(GTK_ALIGNMENT(pattern_align), ALIGN_TOP, ALIGN_BOTTOM, ALIGN_LEFT, ALIGN_RIGHT);
  pattern_frm = gtk_frame_new(_("Notification"));
  pattern_frm_align = gtk_alignment_new(0, 0, 1, 1);
  gtk_alignment_set_padding(GTK_ALIGNMENT(pattern_frm_align), ALIGN_TOP, ALIGN_BOTTOM, ALIGN_LEFT, ALIGN_RIGHT);

  sylnotify_option.pattern_summary = gtk_radio_button_new_with_label(NULL, _("Summary only (when receiving mail and finished)"));
  sylnotify_option.pattern_all = gtk_radio_button_new_with_label_from_widget(GTK_RADIO_BUTTON (sylnotify_option.pattern_summary),
                                                                  _("All (1 notification per new mail)"));
  pattern_lbl = gtk_label_new(_("Note: IMAP4 is not supported yet."));

  vbox_pattern = gtk_vbox_new(TRUE, BOX_SPACE);
  gtk_box_pack_start(GTK_BOX(vbox_pattern), sylnotify_option.pattern_summary, FALSE, FALSE, 0);
  gtk_box_pack_start(GTK_BOX(vbox_pattern), sylnotify_option.pattern_all, FALSE, FALSE, 0);
  gtk_box_pack_start(GTK_BOX(vbox_pattern), pattern_lbl, FALSE, FALSE, 0);

  gtk_container_add(GTK_CONTAINER(pattern_frm_align), vbox_pattern);
  gtk_container_add(GTK_CONTAINER(pattern_frm), pattern_frm_align);
  gtk_container_add(GTK_CONTAINER(pattern_align), pattern_frm);

  /**/
  gtk_box_pack_start(GTK_BOX(vbox), startup_align, FALSE, FALSE, 0);
  gtk_box_pack_start(GTK_BOX(vbox), app_align, FALSE, FALSE, 0);
  gtk_box_pack_start(GTK_BOX(vbox), pattern_align, TRUE, TRUE, 0);

  general_lbl = gtk_label_new(_("General"));
  gtk_notebook_append_page(GTK_NOTEBOOK(notebook), vbox, general_lbl);
  gtk_widget_show_all(notebook);

  SYLPF_END_FUNC;

  return NULL;
}

#ifdef G_OS_WIN32
static GtkWidget *create_config_snarl_page(GtkWidget *notebook, GKeyFile *pkey)
{
  SYLPF_START_FUNC;

  GtkWidget *vbox = gtk_vbox_new(FALSE, 6);

  GtkWidget *proto_align = gtk_alignment_new(0, 0, 1, 1);
  gtk_alignment_set_padding(GTK_ALIGNMENT(proto_align), ALIGN_TOP, ALIGN_BOTTOM, ALIGN_LEFT, ALIGN_RIGHT);

  GtkWidget *proto_frm = gtk_frame_new(_("Notification Method"));
  GtkWidget *proto_frm_align = gtk_alignment_new(0, 0, 1, 1);
  gtk_alignment_set_padding(GTK_ALIGNMENT(proto_frm_align), ALIGN_TOP, ALIGN_BOTTOM, ALIGN_LEFT, ALIGN_RIGHT);

  /* HeySnarl or NTP or GNTP or HeySnarl or */
  sylnotify_option.snarl_snp = gtk_radio_button_new_with_label(NULL, _("SNP (Snarl Network Protocol)"));
  sylnotify_option.snarl_gntp = gtk_radio_button_new_with_label_from_widget (GTK_RADIO_BUTTON (sylnotify_option.snarl_snp),
                                                                  _("GNTP (Growl Notification Transport Protocol)"));
  sylnotify_option.snarl_heysnarl = gtk_radio_button_new_with_label_from_widget(GTK_RADIO_BUTTON (sylnotify_option.snarl_snp),
                                                         _("HeySnarl (Command line tool)"));
  sylnotify_option.snarl_snarlcmd = gtk_radio_button_new_with_label_from_widget(GTK_RADIO_BUTTON (sylnotify_option.snarl_snp),
                                                         _("Snarl_CMD (Command line tool)"));

  /* HeySnarl command */
  GtkWidget *hbox = gtk_hbox_new(FALSE, 0);
  GtkWidget *lbl = gtk_label_new(_("Command Path:"));
  sylnotify_option.snarl_heysnarl_path = gtk_entry_new();
  GtkWidget *cmd_btn = gtk_button_new_from_stock(GTK_STOCK_OPEN);
  gtk_box_pack_start(GTK_BOX(hbox), lbl, FALSE, FALSE, 0);
  gtk_box_pack_start(GTK_BOX(hbox), sylnotify_option.snarl_heysnarl_path, TRUE, TRUE, 0);
  gtk_box_pack_start(GTK_BOX(hbox), cmd_btn, FALSE, FALSE, 0);

  g_signal_connect(GTK_BUTTON(cmd_btn), "clicked",
                   G_CALLBACK(command_path_clicked), sylnotify_option.snarl_heysnarl_path);

  /* Snarl_CMD.exe */
  GtkWidget *hbox2 = gtk_hbox_new(FALSE, 0);
  lbl = gtk_label_new(_("Command Path:"));
  sylnotify_option.snarl_snarlcmd_path = gtk_entry_new();
  cmd_btn = gtk_button_new_from_stock(GTK_STOCK_OPEN);
  gtk_box_pack_start(GTK_BOX(hbox2), lbl, FALSE, FALSE, 0);
  gtk_box_pack_start(GTK_BOX(hbox2), sylnotify_option.snarl_snarlcmd_path, TRUE, TRUE, 0);
  gtk_box_pack_start(GTK_BOX(hbox2), cmd_btn, FALSE, FALSE, 0);

  g_signal_connect(GTK_BUTTON(cmd_btn), "clicked",
                   G_CALLBACK(command_path_clicked), sylnotify_option.snarl_snarlcmd_path);

  GtkWidget *vbox_cond = gtk_vbox_new(FALSE, 0);

  /* enable or disable control */
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(sylnotify_option.snarl_snp), FALSE);
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(sylnotify_option.snarl_gntp), FALSE);
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(sylnotify_option.snarl_heysnarl), FALSE);
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(sylnotify_option.snarl_snarlcmd), TRUE);

  /* currently does not support snarl */
  gtk_widget_set_sensitive(GTK_WIDGET(sylnotify_option.snarl_snp), FALSE);
  gtk_widget_set_sensitive(GTK_WIDGET(sylnotify_option.snarl_gntp), FALSE);
  gtk_widget_set_sensitive(GTK_WIDGET(sylnotify_option.snarl_heysnarl), FALSE);

  gtk_box_pack_start(GTK_BOX(vbox_cond), sylnotify_option.snarl_snp, FALSE, FALSE, 0);
  gtk_box_pack_start(GTK_BOX(vbox_cond), sylnotify_option.snarl_gntp, FALSE, FALSE, 0);
  gtk_box_pack_start(GTK_BOX(vbox_cond), sylnotify_option.snarl_heysnarl, FALSE, FALSE, 0);
  gtk_box_pack_start(GTK_BOX(vbox_cond), hbox, FALSE, FALSE, 0);
  gtk_box_pack_start(GTK_BOX(vbox_cond), sylnotify_option.snarl_snarlcmd, FALSE, FALSE, 0);
  gtk_box_pack_start(GTK_BOX(vbox_cond), hbox2, FALSE, FALSE, 0);

  gtk_widget_show_all(vbox_cond);

  g_signal_connect(GTK_BUTTON(sylnotify_option.snarl_snp), "clicked",
                   G_CALLBACK(snp_mail_cb), NULL);

  g_signal_connect(GTK_BUTTON(sylnotify_option.snarl_gntp), "clicked",
                   G_CALLBACK(gntp_mail_cb), NULL);

  gtk_container_add(GTK_CONTAINER(proto_frm_align), vbox_cond);
  gtk_container_add(GTK_CONTAINER(proto_frm), proto_frm_align);
  gtk_container_add(GTK_CONTAINER(proto_align), proto_frm);

  gtk_box_pack_start(GTK_BOX(vbox), proto_align, FALSE, FALSE, 0);

  GtkWidget *general_lbl = gtk_label_new(_("Snarl"));
  gtk_notebook_append_page(GTK_NOTEBOOK(notebook), vbox, general_lbl);
  gtk_widget_show_all(notebook);

  SYLPF_END_FUNC;

  return NULL;
}

/**
 *
 */
static GtkWidget *create_config_growl_page(GtkWidget *notebook, GKeyFile *pkey)
{
  SYLPF_START_FUNC;

  GtkWidget *vbox = gtk_vbox_new(FALSE, 6);

  GtkWidget *proto_align = gtk_alignment_new(0, 0, 1, 1);
  gtk_alignment_set_padding(GTK_ALIGNMENT(proto_align), ALIGN_TOP, ALIGN_BOTTOM, ALIGN_LEFT, ALIGN_RIGHT);

  GtkWidget *proto_frm = gtk_frame_new(_("Notification Method"));
  GtkWidget *proto_frm_align = gtk_alignment_new(0, 0, 1, 1);
  gtk_alignment_set_padding(GTK_ALIGNMENT(proto_frm_align), ALIGN_TOP, ALIGN_BOTTOM, ALIGN_LEFT, ALIGN_RIGHT);

  /* GNTP or growlnotify */
  sylnotify_option.growl_gntp = gtk_radio_button_new_with_label(NULL, _("GNTP (Growl Notification Transport Protocol)"));
  sylnotify_option.growl_growlnotify = gtk_radio_button_new_with_label_from_widget (GTK_RADIO_BUTTON (sylnotify_option.growl_gntp),
                                                                  _("growlnotify (Command line tool)"));

  /* disable gntp and enable growlnotify */
  gtk_widget_set_sensitive(GTK_WIDGET(sylnotify_option.growl_gntp), FALSE);
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(sylnotify_option.growl_growlnotify), TRUE);

  GtkWidget *hbox = gtk_hbox_new(FALSE, 0);
  GtkWidget *lbl = gtk_label_new(_("Command Path:"));
  sylnotify_option.growl_growlnotify_path = gtk_entry_new();
  GtkWidget *cmd_btn = gtk_button_new_from_stock(GTK_STOCK_OPEN);
  gtk_box_pack_start(GTK_BOX(hbox), lbl, FALSE, FALSE, 0);
  gtk_box_pack_start(GTK_BOX(hbox), sylnotify_option.growl_growlnotify_path, TRUE, TRUE, 0);
  gtk_box_pack_start(GTK_BOX(hbox), cmd_btn, FALSE, FALSE, 0);

  GtkWidget *vbox_cond = gtk_vbox_new(FALSE, 0);

  gtk_box_pack_start(GTK_BOX(vbox_cond), sylnotify_option.growl_gntp, FALSE, FALSE, 0);
  gtk_box_pack_start(GTK_BOX(vbox_cond), sylnotify_option.growl_growlnotify, FALSE, FALSE, 0);
  gtk_box_pack_start(GTK_BOX(vbox_cond), hbox, FALSE, FALSE, 0);

  g_signal_connect(GTK_BUTTON(sylnotify_option.growl_gntp), "clicked",
                   G_CALLBACK(snp_mail_cb), NULL);

  g_signal_connect(GTK_BUTTON(sylnotify_option.growl_growlnotify), "clicked",
                   G_CALLBACK(gntp_mail_cb), NULL);

  g_signal_connect(GTK_BUTTON(cmd_btn), "clicked",
                   G_CALLBACK(command_path_clicked), sylnotify_option.growl_growlnotify_path);

  gtk_container_add(GTK_CONTAINER(proto_frm_align), vbox_cond);
  gtk_container_add(GTK_CONTAINER(proto_frm), proto_frm_align);
  gtk_container_add(GTK_CONTAINER(proto_align), proto_frm);

  gtk_box_pack_start(GTK_BOX(vbox), proto_align, FALSE, FALSE, 0);

  GtkWidget *general_lbl = gtk_label_new(_("Growl"));
  gtk_notebook_append_page(GTK_NOTEBOOK(notebook), vbox, general_lbl);
  gtk_widget_show_all(notebook);
  SYLPF_END_FUNC;

  return NULL;
}
#endif

#ifdef G_OS_UNIX
static void create_config_gol_page(GtkWidget *notebook, GKeyFile *pkey)
{
  GtkWidget *vbox;
  GtkWidget *page;
  GtkWidget *command_frame;
  GtkWidget *label;

  SYLPF_START_FUNC;

  vbox = gtk_vbox_new(FALSE, 0);
  page = gtk_vbox_new(FALSE, 0);

  command_frame = sylpf_pack_widget_with_aligned_frame(vbox, _("Growl for Linux"));
  gtk_box_pack_start(GTK_BOX(page), command_frame, FALSE, FALSE, 0);

  label = gtk_label_new(_("Gol"));
  gtk_notebook_append_page(GTK_NOTEBOOK(notebook), page, label);
  gtk_widget_show_all(notebook);

  SYLPF_END_FUNC;
}
#endif

/* about, copyright tab */
static GtkWidget *create_config_about_page(GtkWidget *notebook, GKeyFile *pkey)
{
  GtkWidget *hbox;
  GtkWidget *vbox;
  GtkWidget *lbl;
  GtkWidget *desc;
  GtkWidget *scrolled;
  GtkTextBuffer *tbuffer;
  GtkWidget *tview;
  GtkWidget *general_lbl;

  SYLPF_START_FUNC;

  debug_print("create_config_about_page\n");
  if (notebook == NULL){
    return NULL;
  }
  hbox = gtk_hbox_new(TRUE, 6);
  vbox = gtk_vbox_new(FALSE, 6);

  lbl = gtk_label_new(_("SylNotify"));
  desc = gtk_label_new(PLUGIN_DESC);

  /* copyright */
  scrolled = gtk_scrolled_window_new(NULL, NULL);

  gtk_box_pack_start(GTK_BOX(vbox), lbl, FALSE, TRUE, 6);
  gtk_box_pack_start(GTK_BOX(vbox), desc, FALSE, TRUE, 6);
  gtk_box_pack_start(GTK_BOX(vbox), scrolled, TRUE, TRUE, 6);
  gtk_box_pack_start(GTK_BOX(hbox), vbox, TRUE, TRUE, 6);

  tbuffer = gtk_text_buffer_new(NULL);
  gtk_text_buffer_set_text(tbuffer, _(copyright), strlen(copyright));
  tview = gtk_text_view_new_with_buffer(tbuffer);
  gtk_text_view_set_editable(GTK_TEXT_VIEW(tview), FALSE);
  gtk_container_add(GTK_CONTAINER(scrolled), tview);

  gtk_box_pack_start(GTK_BOX(vbox), scrolled, TRUE, TRUE, 6);

  /**/
  general_lbl = gtk_label_new(_("About"));
  gtk_notebook_append_page(GTK_NOTEBOOK(notebook), hbox, general_lbl);
  gtk_widget_show_all(notebook);

  SYLPF_END_FUNC;

  return NULL;
}

static void exec_sylnotify_onoff_cb(void)
{
  SylNotifyOption *option = &sylnotify_option;

  SYLPF_START_FUNC;

  if (option->plugin_enabled != TRUE) {
    if (!option->use_alertpanel) {
      syl_plugin_alertpanel_message(_("SylNotify"),
                                  _("SylNotify plugin is enabled."),
                                  ALERT_NOTICE);
    }
    option->plugin_enabled = TRUE;
    gtk_widget_hide(option->plugin_off);
    gtk_widget_show(option->plugin_on);
    gtk_tooltips_set_tip(option->plugin_tooltip, option->plugin_switch,
                         _("SylNotify is enabled. Click the icon to disable plugin."),
                         NULL);
  } else {
    if (option->use_alertpanel) {
      syl_plugin_alertpanel_message(_("SylNotify"),
                                    _("SylNotify plugin is disabled."),
                                    ALERT_NOTICE);
    }
    option->plugin_enabled = FALSE;
    gtk_widget_hide(option->plugin_on);
    gtk_widget_show(option->plugin_off);
    gtk_tooltips_set_tip(option->plugin_tooltip, option->plugin_switch,
                         _("SylNotify is disabled. Click the icon to enable plugin."),
                         NULL);
  }

  SYLPF_END_FUNC;
}

void exec_sylnotify_cb(GObject *obj, FolderItem *item, const gchar *file, guint num)
{
  PrefsCommon *prefs_common;
  PrefsAccount *ac;
  MsgInfo *msginfo;
  gint ret;
  gchar *path, *cmdline;

  SYLPF_START_FUNC;

  if (sylnotify_option.plugin_enabled != TRUE) {
    debug_print("[DEBUG] disabled sylnotify plugin\n");
    return;
  }
  if (item->stype != F_NORMAL && item->stype != F_INBOX) {
    debug_print("[DEBUG] not F_NORMAL and F_INBOX %d\n", item->stype);
    if (item->folder) {
      if (item->folder->klass) {
        SYLPF_DEBUG_STR("item->name", item->name);
        SYLPF_DEBUG_VAL("FolderType", item->folder->klass->type);
      }
    }
    return;
  }

  prefs_common = prefs_common_get();
  if (prefs_common->online_mode != TRUE) {
    debug_print("[DEBUG] not online\n");
    return;
  }

  if (sylnotify_option.pattern_all_flag != TRUE ||
      sylnotify_option.pattern_summary_flag != FALSE) {
    debug_print("[DEBUG] notify summary only.\n");
    return;
  }

  ac = (PrefsAccount*)account_get_default();
  g_return_if_fail(ac != NULL);

  /* check item->path for filter */
  g_print("%s\n", item->name);
  g_print("%s\n", item->path);

  msginfo = folder_item_get_msginfo(item, num);
  SYLPF_DEBUG_VAL("UNREAD", MSG_UNREAD);
  SYLPF_DEBUG_VAL("NEW", MSG_NEW);
  SYLPF_DEBUG_VAL("MARKED", MSG_MARKED);
  debug_print("[DEBUG] perm_flags:%08x \n", msginfo->flags.perm_flags);
  debug_print("[DEBUG] tmp_flags:%08x \n", msginfo->flags.tmp_flags);

  g_key_file_load_from_file(sylnotify_option.rcfile,
                            sylnotify_option.rcpath, G_KEY_FILE_KEEP_COMMENTS, NULL);

#ifdef DEBUG
  debug_print("[DEBUG] item->path:%s\n", item->path);
#endif

  ret = -1;
  if (sylnotify_option.snarl_flag != FALSE) {
    if (sylnotify_option.snarl_option.use_snp != FALSE) {
      debug_print("[DEBUG] snarl snp mode\n");
#ifdef G_OS_WIN32
      send_notification_by_snarl_snp(sylnotify_option.rcpath, msginfo);
#endif
    } else if (sylnotify_option.snarl_option.use_gntp != FALSE) {
      debug_print("[DEBUG] snarl gntp mode\n");
    } else if (sylnotify_option.snarl_option.use_heysnarl != FALSE) {
      debug_print("[DEBUG] snarl heysnarl mode\n");
      /**/
    } else if (sylnotify_option.snarl_option.use_snarlcmd != FALSE) {
      debug_print("[DEBUG] snarl snarlcmd mode\n");
      path = g_key_file_get_string(sylnotify_option.rcfile, SYLNOTIFY_SNARL, "snarlcmd_path", NULL);
      if (path != NULL) {
        cmdline = g_strdup_printf("\"%s\" snShowMessage %d \"%s\" \"%s\" \"%s\"",
                                         path,
                                         5,
                                         msginfo->from,
                                         unmime_header(msginfo->subject),
                                         "http://sylpheed.sraoss.jp/images/sylpheed.png");
        ret = execute_command_line(cmdline, FALSE);
      }
    }
  } else if (sylnotify_option.growl_flag != FALSE) {
    if (sylnotify_option.growl_option.use_growlnotify != FALSE) {
#ifdef G_OS_WIN32
      send_notifycation_by_growlnotify(sylnotify_option.rcfile,
                                       msginfo->from, msginfo->subject);
#endif
    }
  } else {
    /* nop */
  }
  SYLPF_END_FUNC;
}

#ifdef G_OS_WIN32
static void command_path_clicked(GtkWidget *widget, gpointer data)
{
  GtkWidget *dialog;
  gchar *filename;

  SYLPF_START_FUNC;

  dialog = gtk_file_chooser_dialog_new(NULL, NULL,
                                       GTK_FILE_CHOOSER_ACTION_OPEN,
                                       GTK_STOCK_OPEN,GTK_RESPONSE_ACCEPT,
                                       GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
                                       NULL);
  if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) {
    filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog));
    if (filename) {
      gtk_entry_set_text(GTK_ENTRY(data), filename);
      g_free(filename);
    }
  }
  gtk_widget_destroy(dialog);

  SYLPF_END_FUNC;
}
#endif

static void inc_start_cb(GObject *obj, PrefsAccount *ac)
{
  SYLPF_START_FUNC;

#if 1
  if (ac)
    g_print("test: receive start: account: %s\n", ac->account_name);
  else
    g_print("test: receive start: all accounts\n");
#else
  gint ret;
  if (sylnotify_option.snarl_flag != FALSE) {
    if (sylnotify_option.snarl_snarlcmd_flag != FALSE) {
      debug_print("[DEBUG] snarl snarlcmd mode\n");
      send_notification_by_snarl(sylnotify_option.rcfile,
                                 ac ? ac->account_name : "All",
                                 _("receive start"));
    }
  } else if (sylnotify_option.growl_flag != FALSE) {
    if (sylnotify_option.growl_growlnotify_flag != FALSE) {
      send_notification_by_growlnotify(sylnotify_option.rcfile,
    }
  }
#endif
  SYLPF_END_FUNC;
#undef SYLPF_FUNC_NAME
}

static void inc_finished_cb(GObject *obj, gint new_messages)
{
#define SYLPF_FUNC_NAME "inc_finished_cb"
  SYLPF_START_FUNC;

  g_print("test: received %d new messages\n", new_messages);
#if 0
  gint ret = 0;
  if (sylnotify_option.snarl_flag != FALSE) {
    if (sylnotify_option.snarl_snarlcmd_flag != FALSE) {
      debug_print("[DEBUG] snarl snarlcmd mode\n");
      send_notifycation_by_snarl(sylnotify_option.rcfile,
                                 _("receive finished"),
                                 g_sprintf("%d new messages", new_messages));
      }
    }
  } else if (sylnotify_option.growl_flag != FALSE) {
    if (sylnotify_option.growl_growlnotify_flag != FALSE) {
      send_notifycation_by_growlnotify(sylnotify_option.rcfile,
                                       _("receive finished"),
                                       g_sprintf("%d new messages", new_messages));

    }
  }
  SYLPF_END_FUNC;
#endif
}

#ifdef G_OS_WIN32
static gint send_notification_by_growlnotify(GKeyFile *rcfile,
                                             gchar *from,
                                             gchar *subject)
{

  gchar *path;
  gchar *cmdline;
  gint ret;

  SYLPF_START_FUNC;

  path = g_key_file_get_string(rcfile, SYLNOTIFY_GROWL,
                               "growlnotify_path", NULL);
  if (path != NULL) {
    cmdline = g_strdup_printf("\"%s\" /a:%s /ai:%s /r:\"%s\" \"%s\"",
                              path,
                              "Sylpheed",
                              "http://sylpheed.sraoss.jp/images/sylpheed.png",
                              "New Mail",
                              "dummy");
    ret = execute_command_line(cmdline, FALSE);
    g_free(cmdline);
    if (ret >= 0) {
      cmdline = g_strdup_printf("\"%s\" /a:%s /n:\"%s\" /t:\"%s\" \"%s\"",
                                path,
                                "Sylpheed",
                                "New Mail",
                                from,
                                subject);
      ret = execute_command_line(cmdline, FALSE);
      g_free(cmdline);
    }
  }
  SYLPF_END_FUNC;

  return ret;
}

static gint send_notification_by_snarl(GKeyFile *rcfile,
                                       const gchar *title,
                                       const gchar *message)
{

  gchar *path;
  gchar *cmdline;
  gint ret;

  SYLPF_START_FUNC;

  path = g_key_file_get_string(rcfile, SYLNOTIFY_SNARL,
                               "snarlcmd_path", NULL);
  if (path != NULL) {
    cmdline = g_strdup_printf("\"%s\" snShowMessage %d \"%s\" \"%s\" \"%s\"",
                              path,
                              5,
                              title,
                              message,
                              "http://sylpheed.sraoss.jp/images/sylpheed.png");
    ret = execute_command_line(cmdline, FALSE);
    g_free(cmdline);
  }
  SYLPF_END_FUNC;
  return ret;
}

static gint send_notification_by_snarl_snp(GKeyFile *rcfile,
                                           const MsgInfo *msginfo)
{

  gint sock;
  gint ret;
  gchar *buf;

  SYLPF_START_FUNC;

  sock = fd_connect_inet(SYLSNARL_PORT);
  debug_print("[DEBUG] sock:%d\n", sock);
  if (sock < 0) {
    debug_print("[DEBUG] sock error:%d\n", sock);
    return -1;
  }

  buf = g_strdup_printf("%s\r\n%s\r\n%s&title=%s&text=Date:%s\\nFrom:%s\\nTo:%s\\nSubject:%s\r\nEND\r\n",
                        "SNP/3.0",
                        "register?app-sig=app/Sylpheed&title=Sylpheed",
                        "notify?app-sig=app/Sylpheed",
                        conv_unmime_header(msginfo->subject, "UTF-8"),
                        msginfo->date,
                        msginfo->from,
                        msginfo->to,
                        conv_unmime_header(msginfo->subject, "UTF-8"));
  debug_print("[DEBUG] msg:%s\n", buf);
  ret = fd_write_all(sock, buf, strlen(buf));
  g_free(buf);
  fd_close(sock);

  SYLPF_END_FUNC;
  return ret;
}
#endif

static void create_app_indicator(SylNotifyOption *option)
{
  GtkWidget *tray_menu;
  GtkWidget *menu_item;
  AppIndicator *indicator;

  indicator = app_indicator_new(SYLPF_ID,
                                "orca",
                                APP_INDICATOR_CATEGORY_APPLICATION_STATUS);

  app_indicator_set_status(indicator, APP_INDICATOR_STATUS_ACTIVE);

  tray_menu = gtk_menu_new();
  menu_item = gtk_image_menu_item_new_from_stock(GTK_STOCK_ABOUT, NULL);
  g_signal_connect((GObject*)menu_item, "activate",
                   (GCallback)exec_sylnotify_menu_cb, NULL);
  gtk_menu_shell_append((GtkMenuShell*)tray_menu, menu_item);
  app_indicator_set_menu(indicator, GTK_MENU(tray_menu));
  gtk_widget_show_all(tray_menu);
}


text:
package org.apache.commons.compress.archivers.zip;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import org.hamcrest.core.IsInstanceOf;
import org.junit.jupiter.api.Test;

public class ZipClassCoverageTest {

    @Test
    public void testConstructZip64RequiredException() {
        final Zip64RequiredException e = new Zip64RequiredException("critique of pure");
        assertNotNull(e);
    }
    @Test
    public void testMessageException() {
        final ZipArchiveEntry ze = new ZipArchiveEntry("hello");
        final String entryTooBigMessage = Zip64RequiredException.getEntryTooBigMessage(ze);
        assertEquals("hello's size exceeds the limit of 4GByte.",
            entryTooBigMessage);
    }

    @Test
    public void testConstantConstructor()
        throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        final Class<ZipConstants> clazz = ZipConstants.class;
        final Constructor<ZipConstants> constructor = clazz.getDeclaredConstructor();
        assertFalse(constructor.isAccessible());
        constructor.setAccessible(true);
        final Object o = constructor.newInstance();
        assertThat(o, IsInstanceOf.instanceOf(clazz));
        constructor.setAccessible(false);

    }

}


text:
root = "/var/www/skype-chats.com/current"
working_directory root
pid "#{root}/tmp/pids/unicorn.pid"
stderr_path "#{root}/log/unicorn.log"
stdout_path "#{root}/log/unicorn.log"

listen "/tmp/unicorn.skype-chats.com.sock"
worker_processes 2
timeout 30

# Force the bundler gemfile environment variable to
# reference the capistrano "current" symlink
before_exec do |_|
  ENV["BUNDLE_GEMFILE"] = File.join(root, 'Gemfile')
end


text:
help:
	@echo "Usage:"
	@echo "    make help: prints this help."
	@echo "    make test: runs the tests."

test:
	python manage.py test cbv


text:
// Copyright 2016 Henrik Steffen Gaßmann
//
// Licensed under the MIT License.
// See LICENSE file in the project root for full license information.
//
//#include "precompiled.hpp"
#include "boost-unit-test.hpp"
#include <boost/throw_exception.hpp>

using namespace boost::unit_test;

// we can't use the macros to specify the module name, because the
// defining header is already included in the precompiled header...
bool init_unit_test()
{
    framework::master_test_suite().p_name.value = "sexpr-cpp test suite";
    return true;
}

// this way we don't have to care whether Boost.Test was compiled with
// BOOST_TEST_ALTERNATIVE_INIT_API defined or not.
test_suite * init_unit_test_suite(int /*argc*/, char* /*argv*/[])
{
    if (!init_unit_test())
    {
        BOOST_THROW_EXCEPTION(framework::setup_error("init_unit_test failed."));
    }
    return nullptr;
}


text:
import Ember from 'ember';
const { htmlSafe } = Ember.String;

export default Ember.Helper.extend({
  init() {
    this._super.apply(this, arguments);
    this.environment = Ember.getOwner(this).resolveRegistration('config:environment').environment;
  },
  compute(messages) {
    if (this.environment === 'production') {
      return;
    }

    let message = messages.join(' ');
    if (this.environment === 'development') {
      return htmlSafe(`<div style="color: red">${message}</div>`);
    }

    throw new Error(message);
  }
});


text:
"""
This script runs a policy gradient algorithm
"""

from gym.envs import make
from modular_rl import *
import argparse, sys, cPickle
from tabulate import tabulate
import shutil, os, logging
import gym
import opensim as osim
from osim.env import *
from multiprocessing import Pool

def animate_rollout_save(agent, seed, iffilter, n_timesteps=1000, delay=.01):
    total_reward = 0.
    env = RunEnv(False)
    ob = env.reset(seed=seed)
    if iffilter==2:
        ofd = FeatureInducer(env.observation_space)
    elif iffilter==1:
        ofd = ConcatPrevious(env.observation_space)
    for i in range(n_timesteps):
        ob = ofd(ob)
        ob = agent.obfilt(ob)
        a, _info = agent.act(ob)
        ob, _rew, done, _info = env.step(a)
        total_reward += _rew
        ob = np.array(ob)
        if done:
            print(("terminated after %s timesteps"%i))
            break
        time.sleep(delay)
    print("Reward={}, Seed={}, Timesteps={}".format(total_reward, seed, i))

def parallel_animate((agent, seed, iffilter)):
    animate_rollout_save(agent, seed, iffilter, 1000)

def read_seeds_file(filename='seed_res.txt'):
    f = map(str.strip, open(filename).readlines())
    seed_dict = {'Reward': [], 'Seed': []}
    for i in f:
        seed_dict['Reward'].append(float(i.split(',')[0].split('=')[-1]))
        seed_dict['Seed'].append(int(i.split(',')[1].split('=')[-1]))
    print(seed_dict)
    return seed_dict

def make_env(args):
    env = RunEnv(False)
    env_spec = env.spec

    mondir = args.outfile + ".dir"
    if args.load_snapshot:
        env = gym.wrappers.Monitor(env, mondir, video_callable=None if args.video else VIDEO_NEVER, resume=True)
    else:
        if os.path.exists(mondir): shutil.rmtree(mondir)
        os.mkdir(mondir)
        env = gym.wrappers.Monitor(env, mondir, video_callable=None if args.video else VIDEO_NEVER)

    if args.filter==2:
        ofd = FeatureInducer(env.observation_space)
        env = FilteredEnv(env, ob_filter=ofd)
    elif args.filter==1:
        ofd = ConcatPrevious(env.observation_space)
        env = FilteredEnv(env, ob_filter=ofd)
    return env

if __name__ == "__main__":
    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    update_argument_parser(parser, GENERAL_OPTIONS)
    parser.add_argument("--env",required=True)
    parser.add_argument("--agent",required=True)
    parser.add_argument("--plot",action="store_true")
    parser.add_argument("--train", action="store_true")
    args,_ = parser.parse_known_args([arg for arg in sys.argv[1:] if arg not in ('-h', '--help')])

    agent_ctor = get_agent_cls(args.agent)
    update_argument_parser(parser, agent_ctor.options)
    args = parser.parse_args()
    if args.timestep_limit == 0:
        args.timestep_limit = 1000 #env_spec.timestep_limit
    # np.random.seed(args.seed)

    if args.use_hdf:
        if args.load_snapshot:
            hdf = load_h5_file(args)
            key = hdf["agent_snapshots"].keys()[-1]
            latest_snapshot = hdf["agent_snapshots"][key]
            agent = cPickle.loads(latest_snapshot.value)

            if not args.train:
                agent.stochastic=False
                args_list = [(agent,
                      seed,
                      args.filter
                      ) for seed in np.random.randint(1, 5000, 3000)]

                # p = Pool(args.parallel)
                # p.map(parallel_animate, args_list)
                for i in args_list:
                    parallel_animate(i)
            elif args.train:
                seed_dict = read_seeds_file()
                seed_iter = get_seed_iter(seed_dict)
                COUNTER = int(key)

                env = make_env(args)
                def callback(stats):
                    global COUNTER
                    COUNTER += 1
                    # Print stats
                    print("*********** Iteration %i ****************" % COUNTER)
                    print(tabulate([k_v for k_v in list(stats.items()) if np.asarray(k_v[1]).size==1])) #pylint: disable=W0110
                    # Store to hdf5
                    if args.use_hdf:
                        if not args.load_snapshot:
                            for (stat,val) in list(stats.items()):
                                if np.asarray(val).ndim==0:
                                    diagnostics[stat].append(val)
                                else:
                                    assert val.ndim == 1
                                    diagnostics[stat].extend(val)
                        if args.snapshot_every and ((COUNTER % args.snapshot_every==0) or (COUNTER==args.n_iter)):
                            print("Saving model at COUNTER=", COUNTER)
                            hdf['/agent_snapshots/%0.4i'%COUNTER] = np.array(cPickle.dumps(agent,-1))
                            print("Model saving done")
                    # Plot
                    if args.plot:
                        animate_rollout(env, agent, min(1000, args.timestep_limit))

                run_policy_gradient_algorithm_hardmining(env, agent, callback=callback, usercfg = cfg)
                env.close()


text:
using System.Collections.Generic;
using System.Reflection;
using System.Composition.Convention;

namespace System.Composition.TypedParts.Util
{
    internal class DirectAttributeContext : AttributedModelProvider
    {
        public override IEnumerable<Attribute> GetCustomAttributes(Type reflectedType, Reflection.MemberInfo member)
        {
            if (reflectedType == null) throw new ArgumentNullException(nameof(reflectedType));
            if (member == null) throw new ArgumentNullException(nameof(member));

            if (!(member is TypeInfo) && member.DeclaringType != reflectedType)
                return Array.Empty<Attribute>();

            return Attribute.GetCustomAttributes(member, false);
        }

        public override IEnumerable<Attribute> GetCustomAttributes(Type reflectedType, Reflection.ParameterInfo parameter)
        {
            if (reflectedType == null) throw new ArgumentNullException(nameof(reflectedType));
            if (parameter == null) throw new ArgumentNullException(nameof(parameter));

            return Attribute.GetCustomAttributes(parameter, false);
        }
    }
}