text:
<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">

  <meta charset="utf-8">
  <title></title>

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.3/dist/leaflet.css"
   integrity="sha512-07I2e+7D8p6he1SIM+1twR5TIrhUQn9+I6yjqD53JQjFiMf8EtC93ty0/5vJTZGF8aAocvHYNEDJajGdNx1IsQ=="
   crossorigin=""/>
   <link rel="stylesheet" href="css/leafletlabels.css">

  <link href="https://fonts.googleapis.com/css?family=Roboto:400,900|Taviraj" rel="stylesheet">

  <link rel="stylesheet" href="css/amelia.css">

Amelia Earhart

The flight paths that put her on the map

Amelia Earhart is the first woman I remember learning about in history class.

Maybe she was the first to stick with me because she was the first to accomplish so much. First woman to fly solo across the Atlantic. First to fly nonstop from coast to coast. She set endurance, speed and altitude records and brought other women along with her as she went.

Curiosity eventually pointed me to the nonfiction section of the library. I learned that Earhart loved climbing trees and that she kept a scrapbook of newspaper clippings about successful women who worked in fields dominated by men. She was a career counselor in the Department of Aeronautics at Purdue University, and she helped form and lead the Ninety-Nines, an elite organization for women in aviation to call their own.
  The more I learn about Amelia Earhart, the more she inspires me to do what I love "for the fun of it."

Sources: Amelia Earhart Collection, Purdue University Libraries; Photo credit: National Archives


text:
package ch.mlutz.plugins.t4e.tapestry.parsers;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class HivemoduleParser extends DefaultHandler {
	private Map<String, String> metaMap= new HashMap<String, String>();

	private MetaTag metaTmp;

	public String getMeta(String key) {
		return metaMap.get(key);
	}

	public String[] getPageClassPackages() {
		String value= metaMap.get("org.apache.tapestry.page-class-packages");
		if (value == null) {
			return null;
		}
		return value.split(",");
	}

	public String[] getComponentClassPackages() {
		String value= metaMap.get("org.apache.tapestry.component-class-packages");
		if (value == null) {
			return null;
		}
		return value.split(",");
	}

	public String getMessagesEncoding() {
		return metaMap.get("org.apache.tapestry.messages-encoding");
	}

	public String[] getAcceptedLocales() {
		String value= metaMap.get("org.apache.tapestry.accepted-locales");
		if (value == null) {
			return null;
		}
		return value.split(",");
	}

	public void parse(InputStream specificationContent) throws UnsupportedEncodingException {

		// parse
		SAXParserFactory factory = SAXParserFactory.newInstance();
		try {
			SAXParser parser = factory.newSAXParser();
			parser.parse(specificationContent, this);
		} catch (ParserConfigurationException e) {
			System.out.println("ParserConfig error");
		} catch (SAXException e) {
			System.out.println("SAXException : xml not well formed");
		} catch (IOException e) {
			System.out.println("IO error");
		}
	}

	@Override
	public void startElement(String s, String s1, String elementName, Attributes attributes) throws SAXException {
		// if current element is book , create new book
		// clear tmpValue on start of element

		if (elementName.equalsIgnoreCase("meta")) {
			metaTmp = new MetaTag();
			metaTmp.parseAttributes(attributes);
		}
	}
	@Override
	public void endElement(String s, String s1, String element) throws SAXException {
		if (element.equals("meta")) {
			 metaMap.put(metaTmp.getKey(), metaTmp.getValue());
		}
	}

	class MetaTag {
		private Map<String, String> attributeMap= new HashMap<String, String>();

		public String getKey() {
			return attributeMap.get("key");
		}

		public String getValue() {
			return attributeMap.get("value");
		}

		public void parseAttributes(Attributes attributes) {
			attributeMap.put("key", attributes.getValue("key"));
			attributeMap.put("value", attributes.getValue("value"));
		}
	}

	/**
	 * Reset this objects values e.g. before parsing a new specifications
	 */
	public void clear() {
		metaMap.clear();
	}
}

redpajama_set_name: RedPajamaGithub


text:
import wallaby.FXUI as FXUI

from wallaby.qt_combat import *

from wallaby.frontends.qt.widgets.edits.plainTextEdit import PlainTextEdit

#============================================================================#
# The group name in designer widgetbox                                       #
#----------------------------------------------------------------------------#
DESIGNER_GROUP_NAME = "wallaby@fX"

#============================================================================#
# Plugin for CTLiveView                                                      #
#----------------------------------------------------------------------------#
class PlainTextEditPlugin(QtDesigner.QPyDesignerCustomWidgetPlugin):

    def __init__(self, parent=None):
        super(PlainTextEditPlugin, self).__init__(parent)

        self.initialized = False

    def initialize(self, formEditor):
        if self.initialized:
            return
        self.initialized = True

    def isInitialized(self):
        return self.initialized

    def isContainer(self):
        return False

    def icon(self):
        return FXUI.icon()

    def domXml(self):
        return '<widget class="PlainTextEdit" name="plainTextEdit">\n</widget>\n'

    def group(self):
        return DESIGNER_GROUP_NAME

    def includeFile(self):
        return "wallaby.frontends.qt.widgets.edits.plainTextEdit"

    def name(self):
        return "PlainTextEdit"

    def toolTip(self):
        return ""

    def whatsThis(self):
        return ""

    def createWidget(self, parent):
        return PlainTextEdit(parent)


text:
Based on docker's ubuntu latest this is the source for all other yafra images.
It can be used through docker and the name "docker-yafrabase"

## local install and run
Run the follow commands on your local linux with docker installed:

```bash
sudo docker pull yafraorg/docker-yafrabase
sudo docker run -t -p 192.168.9.1:80:80 -i yafraorg/docker-yafrabase /bin/bash
```

## Child images

 * [Java](https://github.com/yafraorg/docker-yafrajava) @ [Docker Hub](https://registry.hub.docker.com/u/yafraorg/docker-yafrajava/)
 * [Python](https://github.com/yafraorg/docker-yafrapython) @ [Docker Hub](https://registry.hub.docker.com/u/yafraorg/docker-yafrapython/)
 * [NodeJS](https://github.com/yafraorg/docker-yafranodejs) @ [Docker Hub](https://registry.hub.docker.com/u/yafraorg/docker-yafranodejs/)
 * [PHP](https://github.com/yafraorg/docker-yafraphp) @ [Docker Hub](https://registry.hub.docker.com/u/yafraorg/docker-yafraphp/)
 * [Perl](https://github.com/yafraorg/docker-yafraperl) @ [Docker Hub](https://registry.hub.docker.com/u/yafraorg/docker-yafraperl/)
 * [C](https://github.com/yafraorg/docker-yafrac) @ [Docker Hub](https://registry.hub.docker.com/u/yafraorg/docker-yafrac/)
 * [.net](https://github.com/yafraorg/docker-yafranet) @ [Docker Hub](https://registry.hub.docker.com/u/yafraorg/docker-yafranet/)

### Specific images
 * [Database](https://github.com/yafraorg/docker-yafradb) @ [Docker Hub](https://registry.hub.docker.com/u/yafraorg/docker-yafradb/)
 * Messaging / RabbitMQ @ [Docker Hub](https://registry.hub.docker.com/u/dockerfile/rabbitmq/)

Get all dockers via
```bash
sudo bash
docker pull yafraorg/docker-yafrabase
docker pull yafraorg/docker-yafranodejs
docker pull yafraorg/docker-yafraphp
docker pull yafraorg/docker-yafrapyhton
docker pull yafraorg/docker-yafrac
docker pull yafraorg/docker-yafrajava
docker pull yafraorg/docker-yafraperl
docker pull yafraorg/docker-yafranet

docker pull yafraorg/docker-yafradb:mysql
docker pull yafraorg/docker-yafradb:postgress
docker pull yafraorg/docker-yafradb:mongodb
docker pull yafraorg/docker-yafradb:dataonly
```

# Yafra links
* [Wiki](https://github.com/yafraorg/yafra/wiki)
* [Dcoker usage](https://github.com/yafraorg/yafra/wiki/Docker)
* [Projects](https://github.com/yafraorg/yafra/wiki/Projects)


text:
export class WorkingOffLine {
  constructor() {
    this.datasource = new kendo.data.DataSource({
      offlineStorage: 'offline-kendo-demo',
      transport: {
        read: {
          url: '//demos.telerik.com/kendo-ui/service/products',
          dataType: 'jsonp'
        },
        update: {
          url: '//demos.telerik.com/kendo-ui/service/products/update',
          dataType: 'jsonp'
        },
        destroy: {
          url: '//demos.telerik.com/kendo-ui/service/products/destroy',
          dataType: 'jsonp'
        },
        create: {
          url: '//demos.telerik.com/kendo-ui/service/products/create',
          dataType: 'jsonp'
        },
        parameterMap: function(options, operation) {
          if (operation !== 'read' && options.models) {
            return {models: kendo.stringify(options.models)};
          }
        }
      },
      batch: true,
      pageSize: 8,
      schema: {
        model: {
          id: 'ProductID',
          fields: {
            ProductID: { editable: false, nullable: true },
            UnitPrice: { type: 'number', validation: { min: 1} },
            Discontinued: { type: 'boolean' },
            UnitsInStock: { type: 'number', validation: { min: 0, required: true } }
          }
        }
      }
    });
  }

  online() {
    this.datasource.online(true);
    alert('datasource is now online');
  }

  offline() {
    this.datasource.online(false);
    alert('datasource is now offline');
  }
}


text:
package org.tiwonk.gwt.rest.generator;

import java.io.PrintWriter;
import java.lang.annotation.Annotation;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Produces;

import org.tiwonk.gwt.rest.client.AbstractClientResource;
import org.tiwonk.gwt.rest.client.ResourceAccessException;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.ext.Generator;
import com.google.gwt.core.ext.GeneratorContext;
import com.google.gwt.core.ext.TreeLogger;
import com.google.gwt.core.ext.UnableToCompleteException;
import com.google.gwt.core.ext.typeinfo.JClassType;
import com.google.gwt.core.ext.typeinfo.JMethod;
import com.google.gwt.core.ext.typeinfo.JParameter;
import com.google.gwt.core.ext.typeinfo.JParameterizedType;
import com.google.gwt.core.ext.typeinfo.TypeOracle;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.rebind.ClassSourceFileComposerFactory;
import com.google.gwt.user.rebind.SourceWriter;

public class ClientResourceGenerator extends Generator {

  @Override
  public String generate(TreeLogger logger, GeneratorContext context,  String typeName)
  throws UnableToCompleteException {

    TypeOracle typeOracle = context.getTypeOracle();
    JClassType clientInterfaceType = typeOracle.findType(typeName);

    String apiPackage = clientInterfaceType.getPackage().getName();
    String implPackage = apiPackage + ".impl";
    String implClassSimpleName = clientInterfaceType.getSimpleSourceName() + "Impl";

    GeneratorInfo info = new GeneratorInfo(logger, clientInterfaceType);

    ImportAnalyzer importAnalyzer = new ImportAnalyzer(implPackage);
    importAnalyzer.analyze(clientInterfaceType);

    ClassSourceFileComposerFactory composerFactory =
        new ClassSourceFileComposerFactory(implPackage, implClassSimpleName);

    importAnalyzer.add(JSONValue.class.getName());
    importAnalyzer.add(JSONObject.class.getName());
    importAnalyzer.add(JSONParser.class.getName());
    importAnalyzer.add(Request.class.getName());
    importAnalyzer.add(Response.class.getName());
    importAnalyzer.add(RequestException.class.getName());
    importAnalyzer.add(RequestCallback.class.getName());
    importAnalyzer.add(JavaScriptObject.class.getName());
    importAnalyzer.add(AbstractClientResource.class.getName());
    importAnalyzer.add(ResourceAccessException.class.getName());
    importAnalyzer.add(RequestBuilder.class.getName());
    importAnalyzer.addImports(composerFactory);

    composerFactory.setSuperclass(AbstractClientResource.class.getSimpleName());
    composerFactory.addImplementedInterface(clientInterfaceType.getSimpleSourceName());

    PrintWriter printWriter = context.tryCreate(logger, implPackage, implClassSimpleName);
    if (printWriter != null) {
      SourceWriter sourceWriter = composerFactory.createSourceWriter(context, printWriter);

      addMethods(info, sourceWriter, clientInterfaceType);

      sourceWriter.commit(logger);
    }

    return implPackage + "." + implClassSimpleName;
  }

  private void addMethods(GeneratorInfo info, SourceWriter sourceWriter, JClassType interfaceType) throws UnableToCompleteException {

    JMethod[] methodArray = interfaceType.getMethods();
    for (int i=0; i<methodArray.length; i++) {
      addMethod(info, sourceWriter, interfaceType, methodArray[i]);
    }

  }

  private void addMethod(GeneratorInfo info, SourceWriter writer, JClassType interfaceType, JMethod method) throws UnableToCompleteException {

    String returnType = method.getReturnType().getSimpleSourceName();
    String methodName = method.getName();
    writer.print("public " + returnType + " " + methodName + "(");
    analyzeHttpMethod(info, method);
    addParameters(info, writer, method.getParameters());
    writer.println(") {");
    addMethodBody(info, writer, method);
    writer.println("}");

  }

  private void addMethodBody(GeneratorInfo info, SourceWriter writer, JMethod method)
  throws UnableToCompleteException {

    if (info.httpMethod == RequestBuilder.GET) {
      buildGetMethod(info, writer, method);
    } else if (info.httpMethod == RequestBuilder.POST) {
      buildPostMethod(info, writer, method);
    } else if (info.httpMethod == RequestBuilder.PUT) {
      buildPutMethod(info, writer, method);
    }

  }

  private void buildPostMethod(GeneratorInfo info, SourceWriter writer, JMethod method)
  throws UnableToCompleteException {

    if (
        info.asyncCallbackParam == null ||
        info.resourceParam == null ||
        info.asyncType==null
    ) {

      info.logger.log(TreeLogger.ERROR,
          "A POST method must have parameters of the form (T resource, AsyncCallback<R> callback)\n" +
          "where T is the type of object posted to the server and R is the return type.\n" +
          "If R is a string, then the callback will receive the value of the 'Location' header from the response.\n" +
          "Otherwise, the callback will receive an object of type R parsed from the response text.\n" +
          "The return type R may be Void, in which case the callback receives a null value.");

      throw new UnableToCompleteException();
    }

    if ("java.lang.String".equals(info.asyncType.getQualifiedSourceName())) {
      saveMethodReturnsLocation(info, writer, method);

    } else if ("java.lang.Void".equals(info.asyncType.getQualifiedSourceName())) {
      saveMethodReturnsVoid(info, writer, method);

    } else {
      saveMethodReturnsEntity(info, writer, method);
    }

  }

  private void buildPutMethod(GeneratorInfo info, SourceWriter writer, JMethod method)
      throws UnableToCompleteException {

        if (
            info.asyncCallbackParam == null ||
            info.resourceParam == null ||
            info.asyncType==null
        ) {

          info.logger.log(TreeLogger.ERROR,
              "A PUT method must have parameters of the form (T resource, AsyncCallback<R> callback)\n" +
              "where T is the type of object posted to the server and R is the return type.\n" +
              "The return type R may be Void, in which case the callback receives a null value." +
              "Otherwise, the callback will receive an object of type R parsed from the response text.\n" +
              "The return type R may not be a String (unlike a POST method)");

          throw new UnableToCompleteException();
        }

       if ("java.lang.Void".equals(info.asyncType.getQualifiedSourceName())) {
          saveMethodReturnsVoid(info, writer, method);

        } else {
          saveMethodReturnsEntity(info, writer, method);
        }
  }

  private void saveMethodReturnsLocation(GeneratorInfo info, SourceWriter writer, JMethod method) throws UnableToCompleteException {

    String callbackParam = info.asyncCallbackParam.getName();
    String resourceParam = info.resourceParam.getName();
    String methodName = info.httpMethod.toString();

    // RequestBuilder request = new RequestBuilder(RequestBuilder.POST, getResourceURL());
    writer.println();
    writer.indent();
    writer.println("RequestBuilder request = new RequestBuilder(RequestBuilder." + methodName + ", getResourceURL());");

    // request.setHeader("Content-Type", "application/vnd.example.v1.person");

    String consumes = info.consumes(method);
    if (consumes != null) {
      writer.print("request.setHeader(\"Content-Type\", \"");
      writer.print(consumes);
      writer.println("\");");
    }

    String produces = info.produces(method);
    if (produces != null) {
      writer.print("request.setHeader(\"Accept\", \"");
      writer.print(produces);
      writer.println("\");");
    }

    // JSONObject json = new JSONObject(person);
    // String payload = json.toString();
    writer.println();
    writer.print("JSONObject json = new JSONObject(");
    writer.print(resourceParam);
    writer.println(");");
    writer.println("String payload = json.toString();");

//    try {
//     request.sendRequest(payload, new RequestCallback() {
    writer.println();
    writer.println("try {");
    writer.indent();
    writer.println("request.sendRequest(payload, new RequestCallback() {");
    writer.indent();

//    @Override
//    public void onResponseReceived(Request request, Response response) {
//
//      if (
//        response.getStatusCode() != Response.SC_CREATED &&
//        response.getStatusCode() != Response.SC_OK
//      ) {
//        onError(request, new ResourceAccessException(response));
//        return;
//      }
//
//      String location = response.getHeader("Location");
//      callback.onSuccess(location);
//
//    }
    writer.println();
    writer.println("@Override");
    writer.println("public void onResponseReceived(Request request, Response response) {");
    writer.indent();
    writer.println("if (");
    writer.println("  response.getStatusCode() != Response.SC_CREATED &&");
    writer.println("  response.getStatusCode() != Response.SC_OK");
    writer.println(") {");
    writer.println("  onError(request, new ResourceAccessException(response));");
    writer.println("  return;");
    writer.println("}");
    writer.println();
    writer.println("String location = response.getHeader(\"Location\");");
    writer.print(callbackParam);
    writer.println(".onSuccess(location);");
    writer.outdent();
    writer.println("}");

//    @Override
//    public void onError(Request request, Throwable e) {
//      callback.onFailure(e);
//    }
//  });
    writer.println();
    writer.println("@Override");
    writer.println("public void onError(Request request, Throwable e) {");
    writer.print("  ");
    writer.print(callbackParam);
    writer.println(".onFailure(e);");
    writer.println("}");
    writer.outdent();
    writer.println("});");
    writer.outdent();

//  } catch (RequestException e) {
//    callback.onFailure(e);
//  }
    writer.println();
    writer.println("} catch (RequestException e) {");
    writer.print("  ");
    writer.print(callbackParam);
    writer.println(".onFailure(e);");
    writer.println("}");
    writer.outdent();

  }

  private void saveMethodReturnsEntity(GeneratorInfo info, SourceWriter writer, JMethod method) throws UnableToCompleteException {

    String callbackParam = info.asyncCallbackParam.getName();
    String resourceParam = info.resourceParam.getName();
    String callbackType = info.asyncType.getSimpleSourceName();
    String methodName = info.httpMethod.toString();

    // RequestBuilder request = new RequestBuilder(RequestBuilder.POST, getResourceURL());
    writer.println();
    writer.indent();
    writer.println("RequestBuilder request = new RequestBuilder(RequestBuilder." + methodName + ", getResourceURL());");

    // request.setHeader("Content-Type", "application/vnd.example.v1.person");
    String consumes = info.consumes(method);
    if (consumes != null) {
      writer.print("request.setHeader(\"Content-Type\", \"");
      writer.print(consumes);
      writer.println("\");");
    }

    String produces = info.produces(method);
    if (produces != null) {
      writer.print("request.setHeader(\"Accept\", \"");
      writer.print(produces);
      writer.println("\");");
    }

    // JSONObject json = new JSONObject(person);
    // String payload = json.toString();
    writer.println();
    writer.print("JSONObject json = new JSONObject(");
    writer.print(resourceParam);
    writer.println(");");
    writer.println("String payload = json.toString();");

//    try {
//     request.sendRequest(payload, new RequestCallback() {
    writer.println();
    writer.println("try {");
    writer.indent();
    writer.println("request.sendRequest(payload, new RequestCallback() {");
    writer.indent();

//    @Override
//    public void onResponseReceived(Request request, Response response) {
//
//      if (
//        response.getStatusCode() != Response.SC_CREATED &&
//        response.getStatusCode() != Response.SC_OK
//      ) {
//        onError(request, new ResourceAccessException(response));
//        return;
//      }
//      JSONValue value = JSONParser.parseStrict(response.getText());
//      PersonRef entity = value.isObject().getJavaScriptObject().cast();
//      callback.onSuccess(entity);
//    }
    writer.println();
    writer.println("@Override");
    writer.println("public void onResponseReceived(Request request, Response response) {");
    writer.indent();
    writer.println("if (");
    writer.println("  response.getStatusCode() != Response.SC_CREATED &&");
    writer.println("  response.getStatusCode() != Response.SC_OK");
    writer.println(") {");
    writer.println("  onError(request, new ResourceAccessException(response));");
    writer.println("  return;");
    writer.println("}");
    writer.println();
    writer.println("JSONValue value = JSONParser.parseStrict(response.getText());");
    writer.print(callbackType);
    writer.println(" entity = value.isObject().getJavaScriptObject().cast();");
    writer.print(callbackParam);
    writer.println(".onSuccess(entity);");
    writer.outdent();
    writer.println("}");

//    @Override
//    public void onError(Request request, Throwable e) {
//      callback.onFailure(e);
//    }
//  });
    writer.println();
    writer.println("@Override");
    writer.println("public void onError(Request request, Throwable e) {");
    writer.print("  ");
    writer.print(callbackParam);
    writer.println(".onFailure(e);");
    writer.println("}");
    writer.outdent();
    writer.println("});");
    writer.outdent();

//  } catch (RequestException e) {
//    callback.onFailure(e);
//  }
    writer.println();
    writer.println("} catch (RequestException e) {");
    writer.print("  ");
    writer.print(callbackParam);
    writer.println(".onFailure(e);");
    writer.println("}");
    writer.outdent();

  }

  private void saveMethodReturnsVoid(GeneratorInfo info, SourceWriter writer, JMethod method) throws UnableToCompleteException {

    String callbackParam = info.asyncCallbackParam.getName();
    String resourceParam = info.resourceParam.getName();
    String methodName = info.httpMethod.toString();

    // RequestBuilder request = new RequestBuilder(RequestBuilder.POST, getResourceURL());
    writer.println();
    writer.indent();
    writer.println("RequestBuilder request = new RequestBuilder(RequestBuilder." + methodName + ", getResourceURL());");
    writer.indent();
    // request.setHeader("Content-Type", "application/vnd.example.v1.person");
    String consumes = info.consumes(method);
    if (consumes != null) {
      writer.print("request.setHeader(\"Content-Type\", \"");
      writer.print(consumes);
      writer.println("\");");
    }

    String produces = info.produces(method);
    if (produces != null) {
      writer.print("request.setHeader(\"Accept\", \"");
      writer.print(produces);
      writer.println("\");");
    }

    // JSONObject json = new JSONObject(person);
    // String payload = json.toString();
    writer.println();
    writer.print("JSONObject json = new JSONObject(");
    writer.print(resourceParam);
    writer.println(");");
    writer.println("String payload = json.toString();");

//    try {
//     request.sendRequest(payload, new RequestCallback() {
    writer.println();
    writer.println("try {");
    writer.indent();
    writer.println("request.sendRequest(payload, new RequestCallback() {");

//    @Override
//    public void onResponseReceived(Request request, Response response) {
//
//      if (
//        response.getStatusCode() != Response.SC_CREATED &&
//        response.getStatusCode() != Response.SC_OK
//      ) {
//        onError(request, new ResourceAccessException(response));
//        return;
//      }
//      callback.onSuccess(null);
//    }
    writer.println();
    writer.println("@Override");
    writer.println("public void onResponseReceived(Request request, Response response) {");
    writer.indent();
    writer.println("if (");
    writer.println("  response.getStatusCode() != Response.SC_CREATED &&");
    writer.println("  response.getStatusCode() != Response.SC_OK");
    writer.println(") {");
    writer.println("  onError(request, new ResourceAccessException(response));");
    writer.println("  return;");
    writer.println("}");
    writer.println();
    writer.print(callbackParam);
    writer.println(".onSuccess(null);");
    writer.outdent();
    writer.println("}");

//    @Override
//    public void onError(Request request, Throwable e) {
//      callback.onFailure(e);
//    }
//  });
    writer.println();
    writer.println("@Override");
    writer.println("public void onError(Request request, Throwable e) {");
    writer.print("  ");
    writer.print(callbackParam);
    writer.println(".onFailure(e);");
    writer.println("}");
    writer.outdent();
    writer.println("});");
    writer.outdent();

//  } catch (RequestException e) {
//    callback.onFailure(e);
//  }
    writer.println();
    writer.println("} catch (RequestException e) {");
    writer.print("  ");
    writer.print(callbackParam);
    writer.println(".onFailure(e);");
    writer.println("}");
    writer.outdent();

  }

  private void buildGetMethod(GeneratorInfo info, SourceWriter writer, JMethod method) {

    if (info.asyncType == null) {
      info.logger.log(TreeLogger.ERROR,
          "GET method must have a single parameter of type AsyncCallback<T> where T is the resource type.");
      return;
    }

    String callbackParam = info.asyncCallbackParam.getName();

    String resourceSimpleName = info.asyncType.getSimpleSourceName();
    String contentType = info.produces(method);

    writer.indent();
    // RequestBuilder request = new RequestBuilder(RequestBuilder.GET, getResourceURL());
    writer.println("RequestBuilder request = new RequestBuilder(RequestBuilder.GET, getResourceURL());");

    // request.setHeader("Content-Type", "...");
    if (contentType != null) {
      writer.print("request.setHeader(\"Accept\", \"");
      writer.print(contentType);
      writer.println("\");");
    }

    /*
    request.setCallback(new RequestCallback() {

      @Override
      public void onResponseReceived(Request request, Response response) {
        if (response.getStatusCode() != Response.SC_OK) {
          onError(request, new ResourceAccessException(response));
          return;
        }
        JSONValue value = JSONParser.parseStrict(response.getText());
        Person entity = toPerson(value.isObject().getJavaScriptObject());
        callback.onSuccess(entity);
      }
   */

    writer.println("request.setCallback(new RequestCallback() {");
    writer.indent();
    writer.println();
    writer.println("@Override");
    writer.println("public void onResponseReceived(Request request, Response response) {");
    writer.indent();
    writer.println("if (response.getStatusCode() != Response.SC_OK) {");
    writer.indent();
    writer.println("onError(request, new ResourceAccessException(response));");
    writer.println("return;");
    writer.outdent();
    writer.println("}");
    writer.println("JSONValue value = JSONParser.parseStrict(response.getText());");
    writer.print(resourceSimpleName);
    writer.print(" entity = ");
    writer.println("value.isObject().getJavaScriptObject().cast();");
    writer.print(callbackParam);
    writer.println(".onSuccess(entity);");

    writer.outdent();
    writer.println("}");

    /*/
      @Override
      public void onError(Request request, Throwable exception) {
        callback.onFailure(exception);
      }
    });
     */
    writer.println();
    writer.println("@Override");
    writer.println("public void onError(Request request, Throwable exception) {");
    writer.indent();
    writer.print(callbackParam);
    writer.println(".onFailure(exception);");
    writer.outdent();
    writer.println("}");
    writer.outdent();
    writer.println("});");

    /*
    try {
      request.send();
    } catch (RequestException e) {
      callback.onFailure(e);
    }
     */
    writer.println("try {");
    writer.println("  request.send();");
    writer.println("} catch (RequestException e) {");
    writer.print("  ");
    writer.print(callbackParam);
    writer.println(".onFailure(e);");
    writer.println("}");
    writer.outdent();

  }

  private void analyzeHttpMethod(GeneratorInfo info, JMethod method) {

    Annotation[] annotations = method.getAnnotations();
    for (int i=0; i<annotations.length; i++) {
      Annotation note = annotations[i];
      if (note.annotationType() == GET.class) {
        info.httpMethod = RequestBuilder.GET;
        return;
      } else if (note.annotationType() == POST.class) {
        info.httpMethod = RequestBuilder.POST;
        return;

      } else if (note.annotationType() == PUT.class) {
        info.httpMethod = RequestBuilder.PUT;
        return;
      }
    }

  }

  private void addParameters(GeneratorInfo info, SourceWriter writer, JParameter[] parameters) throws UnableToCompleteException {
    info.asyncCallbackParam = null;
    info.asyncType = null;
    info.resourceParam = null;
    info.resourceType = null;

    for (int i=0; i<parameters.length; i++) {
      if (i > 0) {
        writer.print(", ");
      }
      JParameter param = parameters[i];
      String paramType = param.getType().getSimpleSourceName();
      String paramName = param.getName();

      JParameterizedType generic = param.getType().isParameterized();

      if (AsyncCallback.class.getName().equals(param.getType().getQualifiedSourceName())) {
        info.asyncCallbackParam = param;
        info.asyncType = generic.getTypeArgs()[0];
        writer.print("final ");
      } else {
        info.resourceParam = param;
        info.resourceType = param.getType().isClassOrInterface();
      }
      writer.print(paramType);
      if (generic != null) {
        addParameterizedType(info, writer, generic);
      }
      writer.print(" ");
      writer.print(paramName);
    }

  }

  private void addParameterizedType(GeneratorInfo info, SourceWriter writer, JParameterizedType generic) {

    JClassType param[] = generic.getTypeArgs();
    writer.print("<");
    for (int i=0; i<param.length; i++) {
      if (i>0) {
        writer.print(", ");
      }
      writer.print(param[i].getSimpleSourceName());
    }

    writer.print(">");

  }

  static class GeneratorInfo {
    TreeLogger logger;
    JParameter asyncCallbackParam;
    JClassType asyncType;
    JClassType clientType;

    JParameter resourceParam;
    JClassType resourceType;

    RequestBuilder.Method httpMethod;

    public GeneratorInfo(TreeLogger logger, JClassType clientInterfaceType) {
      this.logger = logger;
      clientType = clientInterfaceType;
    }

    String produces() {
      if (clientType == null) return null;
      Produces note = clientType.getAnnotation(Produces.class);
      return note == null ? null : note.value()[0];
    }

    String produces(JMethod method) {
      Produces note = method.getAnnotation(Produces.class);
      return note==null ? produces() : note.value()[0];
    }

    String consumes() {
      if (clientType == null) return null;
      Consumes note = clientType.getAnnotation(Consumes.class);
      return note==null ? null : note.value()[0];
    }

    String consumes(JMethod method) {
      Consumes note = method.getAnnotation(Consumes.class);
      return note==null ? consumes() : note.value()[0];
    }

  }

}


text:
lock '3.4.0'

set :application, 'orientation'
set :scm, "git"
set :repo_url, "git@github.com:LogicalBricks/orientation.git"
set :deploy_to, "/home/deployer/apps/#{fetch(:application)}"

set :ssh_options, {
  forward_agent: true
}

set :log_level, :debug
set :linked_files, %w{ .env config/database.yml }
set :linked_dirs, %w{bin log tmp vendor/bundle public/system public/uploads}

SSHKit.config.command_map[:rake]  = "bundle exec rake"
SSHKit.config.command_map[:rails] = "bundle exec rails"

namespace :deploy do

  desc 'Restart application'
  task :restart do
    on roles(:app), in: :sequence, wait: 5 do
      execute :touch, release_path.join('tmp/restart.txt')
    end
  end
  after 'deploy:publishing', 'deploy:restart'

  after :restart, :clear_cache do
    on roles(:web), in: :groups, limit: 3, wait: 10 do
    end
  end

  desc "Install bower"
  task :install_bower do
    on roles(:web) do
      within release_path do
        execute :bower, :install
      end
    end
  end
  before "deploy:compile_assets", "deploy:install_bower"

  after :finishing, 'deploy:cleanup'
end


text:
export function resetDOM(): void;
export function takeOverConsole(console: () => void): () => void;


text:
package com.amazonaws.services.fms.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.fms.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * AppMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class AppMarshaller {

    private static final MarshallingInfo<String> APPNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("AppName").build();
    private static final MarshallingInfo<String> PROTOCOL_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Protocol").build();
    private static final MarshallingInfo<Long> PORT_BINDING = MarshallingInfo.builder(MarshallingType.LONG).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Port").build();

    private static final AppMarshaller instance = new AppMarshaller();

    public static AppMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(App app, ProtocolMarshaller protocolMarshaller) {

        if (app == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(app.getAppName(), APPNAME_BINDING);
            protocolMarshaller.marshall(app.getProtocol(), PROTOCOL_BINDING);
            protocolMarshaller.marshall(app.getPort(), PORT_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
         xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.opentosca</groupId>
    <artifactId>org.opentosca.bus</artifactId>
    <version>3.0.0-SNAPSHOT</version>
  </parent>

  <artifactId>org.opentosca.bus.application.model</artifactId>

</project>


text:
import re
import ast
import functools

import IECore

import Gaffer

class PythonExpressionEngine( Gaffer.Expression.Engine ) :

	def __init__( self ) :

		Gaffer.Expression.Engine.__init__( self )

	def parse( self, node, expression, inPlugs, outPlugs, contextNames ) :

		parser = _Parser( expression )

		self.__expression = expression
		self.__inPlugPaths = list( parser.plugReads )
		self.__outPlugPaths = list( parser.plugWrites )

		inPlugs.extend( [ self.__plug( node, p ) for p in self.__inPlugPaths ] )
		outPlugs.extend( [ self.__plug( node, p ) for p in self.__outPlugPaths ] )
		contextNames.extend( parser.contextReads )

	def execute( self, context, inputs ) :

		plugDict = {}
		for plugPath, plug in zip( self.__inPlugPaths, inputs ) :
			parentDict = plugDict
			plugPathSplit = plugPath.split( "." )
			for p in plugPathSplit[:-1] :
				parentDict = parentDict.setdefault( p, {} )
			parentDict[plugPathSplit[-1]] = plug.getValue()

		for plugPath in self.__outPlugPaths :
			parentDict = plugDict
			for p in plugPath.split( "." )[:-1] :
				parentDict = parentDict.setdefault( p, {} )

		executionDict = { "IECore" : IECore, "parent" : plugDict, "context" : context }

		exec( self.__expression, executionDict, executionDict )

		result = IECore.ObjectVector()
		for plugPath in self.__outPlugPaths :
			parentDict = plugDict
			plugPathSplit = plugPath.split( "." )
			for p in plugPathSplit[:-1] :
				parentDict = parentDict[p]
			result.append( parentDict.get( plugPathSplit[-1], IECore.NullObject.defaultNullObject() ) )

		return result

	def apply( self, proxyOutput, topLevelProxyOutput, value ) :

		# NullObject signifies that the expression didn't
		# provide a value at all - set the plug to its default.
		if isinstance( value, IECore.NullObject ) :
			proxyOutput.setToDefault()
			return

		value = _extractPlugValue( proxyOutput, topLevelProxyOutput, value )
		if value is None :
			raise TypeError( "Unsupported value type \"%s\"" % type( value ).__name__ )
		else :
			proxyOutput.setValue( value )

	def identifier( self, node, plug ) :

		if node.isAncestorOf( plug ) :
			relativeName = plug.relativeName( node )
		else :
			relativeName = plug.relativeName( node.parent() )

		return 'parent' + "".join( [ '["%s"]' % n for n in relativeName.split( "." ) ] )

	def replace( self, node, expression, oldPlugs, newPlugs ) :

		for oldPlug, newPlug in zip( oldPlugs, newPlugs ) :
			if newPlug is not None :
				replacement = self.identifier( node, newPlug )
			else :
				if oldPlug.direction() == Gaffer.Plug.Direction.In :
					replacement = repr( oldPlug.defaultValue() )
				else :
					replacement = "__disconnected"

			expression = self.__plugRegex( node, oldPlug ).sub(
				replacement, expression
			)

		return expression

	def defaultExpression( self, plug ) :

		# If there's no parent scope, we can't make an expression.
		parentNode = plug.node().ancestor( Gaffer.Node )
		if parentNode is None :
			return ""

		# If we can't extract a value, we can't make an expression.
		if not hasattr( plug, "getValue" ) :
			return ""

		# If we can't store the value in an ObjectVector, we can't
		# return the value in execute().
		value = plug.getValue()
		objectVector = IECore.ObjectVector()
		try :
			objectVector.append( value )
		except :
			return ""

		# If we can't extract the appropriate value for every leaf
		# plug, we can't apply the value after execution.

		def canExtractValue( plug, topLevelPlug, value ) :

			if not len( plug ) :
				# no children - must be able to extract
				# a value for use in apply.
				return _extractPlugValue( plug, topLevelPlug, value ) is not None
			else :
				# compound plug - check all children.
				for child in plug.children() :
					if not canExtractValue( child, topLevelPlug, value ) :
						return False

				return True

		if not canExtractValue( plug, plug, objectVector[0] ) :
			return ""

		# Looks like we can support this plug, so make and return
		# a suitable expression.

		result = ""

		modulePath = Gaffer.Serialisation.modulePath( value )
		if modulePath not in ( "IECore", "" ) :
			result += "import " + modulePath + "\n\n"

		result += "parent[\""
		result += plug.relativeName( parentNode ).replace( ".", "\"][\"" )
		result += "\"] = "

		result += repr( value )

		return result

	def __plug( self, node, plugPath ) :

		plug = node.parent().descendant( plugPath )
		if isinstance( plug, Gaffer.ValuePlug ) :
			return plug

		if plug is None :
			raise RuntimeError( "\"%s\" does not exist" % plugPath )
		else :
			raise RuntimeError( "\"%s\" is not a ValuePlug" % plugPath )

	def __plugRegex( self, node, plug ) :

		identifier = self.identifier( node, plug )
		regex = identifier.replace( "[", "\[" )
		regex = regex.replace( "]", "\]" )
		regex = regex.replace( '"', "['\"']" )

		return re.compile( regex )

Gaffer.Expression.Engine.registerEngine( "python", PythonExpressionEngine )

##########################################################################
# Parser. This is used to figure out what plugs an expression wants
# to read from and write to, and what context variables it wants to read.
##########################################################################

class _Parser( ast.NodeVisitor ) :

	def __init__( self, expression ) :

		ast.NodeVisitor.__init__( self )

		self.plugWrites = set()
		self.plugReads = set()
		self.contextReads = set()

		self.visit( ast.parse( expression ) )

	def visit_Assign( self, node ) :

		if len( node.targets ) == 1 :
			if isinstance( node.targets[0], ast.Subscript ) :
				plugPath = self.__plugPath( self.__path( node.targets[0] ) )
				if plugPath :
					self.plugWrites.add( plugPath )

		self.visit( node.value )

	def visit_Subscript( self, node ) :

		if isinstance( node.ctx, ast.Load ) :
			path = self.__path( node )
			plugPath = self.__plugPath( path )
			if plugPath :
				self.plugReads.add( plugPath )
			else :
				contextName = self.__contextName( path )
				if contextName :
					self.contextReads.add( contextName )

	def visit_Call( self, node ) :

		if isinstance( node.func, ast.Attribute ) :
			if isinstance( node.func.value, ast.Name ) :
				if node.func.value.id == "context" :
					# it's a method call on the context
					if node.func.attr == "getFrame" :
						self.contextReads.add( "frame" )
					elif node.func.attr == "getTime" :
						self.contextReads.add( "frame" )
						self.contextReads.add( "framesPerSecond" )
					elif node.func.attr == "getFramesPerSecond" :
						self.contextReads.add( "framesPerSecond" )
					elif node.func.attr == "get" :
						if not isinstance( node.args[0], ast.Str ) :
							raise SyntaxError( "Context name must be a string" )
						self.contextReads.add( node.args[0].s )

		ast.NodeVisitor.generic_visit( self, node )

	def __path( self, node ) :

		result = []
		while node is not None :
			if isinstance( node, ast.Subscript ) :
				if isinstance( node.slice, ast.Index ) :
					if isinstance( node.slice.value, ast.Str ) :
						result.insert( 0, node.slice.value.s )
					else :
						return []
				node = node.value
			elif isinstance( node, ast.Name ) :
				result.insert( 0, node.id )
				node = None
			else :
				return []

		return result

	def __plugPath( self, path ) :

		if len( path ) < 2 or path[0] != "parent" :
			return ""
		else :
			return ".".join( path[1:] )

	def __contextName( self, path ) :

		if len( path ) !=2 or path[0] != "context" :
			return ""
		else :
			return path[1]

##########################################################################
# Functions for setting plug values.
##########################################################################

def __typedPlugValueExtractor( plug, topLevelPlug, value, converter = None ) :

	if converter is not None :
		return converter( value.value )
	else :
		return value.value

def __compoundNumericPlugValueExtractor( plug, topLevelPlug, value ) :

	index = topLevelPlug.children().index( plug )
	return value.value[index]

def __boxPlugValueExtractor( plug, topLevelPlug, value ) :

	vectorPlug = plug.parent()
	index = vectorPlug.children().index( plug )

	vector = value.value.min if vectorPlug.getName() == "min" else value.value.max

	return vector[index]

def __defaultValueExtractor( plug, topLevelPlug, value ) :

	with IECore.IgnoredExceptions( AttributeError ) :
		value = value.value

	# Deal with the simple atomic plug case.
	if plug.isSame( topLevelPlug ) :
		return value

	# Plug must be a child of a compound of
	# some sort. We need to try to extract
	# the right part of the compound value.
	for name in plug.relativeName( topLevelPlug ).split( "." ) :
		try :
			value = getattr( value, name )
		except AttributeError :
			accessor = getattr( value, "get" + name[0].upper() + name[1:], None )
			if accessor is not None :
				value = accessor()
			else :
				return None

	return value

_valueExtractors = {
	Gaffer.IntPlug : functools.partial( __typedPlugValueExtractor, converter = int ),
	Gaffer.FloatPlug : __typedPlugValueExtractor,
	Gaffer.StringPlug : __typedPlugValueExtractor,
	Gaffer.BoolPlug : __typedPlugValueExtractor,
	Gaffer.V2fPlug : __compoundNumericPlugValueExtractor,
	Gaffer.V2iPlug : __compoundNumericPlugValueExtractor,
	Gaffer.V3fPlug : __compoundNumericPlugValueExtractor,
	Gaffer.V3iPlug : __compoundNumericPlugValueExtractor,
	Gaffer.Color3fPlug : __compoundNumericPlugValueExtractor,
	Gaffer.Color4fPlug : __compoundNumericPlugValueExtractor,
	Gaffer.Box2fPlug : __boxPlugValueExtractor,
	Gaffer.Box2iPlug : __boxPlugValueExtractor,
	Gaffer.Box3fPlug : __boxPlugValueExtractor,
	Gaffer.Box3iPlug : __boxPlugValueExtractor,
}

def _extractPlugValue( plug, topLevelPlug, value ) :

	return _valueExtractors.get( type( topLevelPlug ), __defaultValueExtractor )( plug, topLevelPlug, value )


text:
use strict;
use warnings;
use Data::Dumper;
use Getopt::Long;

exit main();

sub main{
  my $settings={};
  GetOptions($settings,qw(help lyveset=s ttr=s));
  die usage() if($$settings{help});
  die "ERROR: need Lyve-SET project name\n".usage() if(!$$settings{lyveset});
  die "ERROR: need TreeToReads project name\n".usage() if(!$$settings{ttr});

  # where are the Lyve-SET SNPs?
  my $lyveSetSnps=lyveSetSnps($$settings{lyveset},$settings);

  # where are the real SNPs?
  my $realSnps=ttrSites($$settings{ttr},$settings);

  # compare
  my($TP,$TN,$FP,$FN)=compareSnps($lyveSetSnps,$realSnps,$settings);

  # Report
  print join("\t",qw(L-S TTR TP TN FP FN))."\n";
  print join("\t",$$settings{lyveset},$$settings{ttr},$TP, $TN, $FP, $FN)."\n";
}

sub lyveSetSnps{
  my($proj,$settings)=@_;
  my %pos;

  my $matrix="$proj/msa/out.snpmatrix.tsv";
  open(SNPMATRIX,"<",$matrix) or die "ERROR: could not open $matrix for reading: $!";
  while(<SNPMATRIX>){
    next if(/^#/);
    chomp;
    my($chr,$pos,$ref,@alt)=split /\t/;
    $pos{$pos}=$ref;
  }
  close SNPMATRIX;

  return \%pos;
}

sub ttrSites{
  my($proj,$settings)=@_;
  my %pos;

  my $matrix="$proj/mutsites.txt";
  open(TTRMATRIX,"<",$matrix) or die "ERROR: could not open $matrix for reading: $!";
  while(<TTRMATRIX>){
    chomp;
    my($pos)=split /\s+/;
    $pos{$pos}=1
  }
  close TTRMATRIX;
  return \%pos;
}

sub ttrSnps{
  my($proj,$settings)=@_;
  my %pos;

  my $matrix="$proj/var_site_matrix";
  open(TTRMATRIX,"<",$matrix) or die "ERROR: could not open $matrix for reading: $!";
  while(<TTRMATRIX>){
    chomp;
    my($chr,$ref,$pos)=split /\s+/;
    $pos{$pos}=$ref;
  }
  close TTRMATRIX;

  return \%pos;
}

sub compareSnps{
  my ($lyveSetSnps,$realSnps,$settings)=@_;

  # Initialize counts to zero
  my($TP,$TN,$FP,$FN)=split(//,"0" x 4);

  # How many of the real SNPs were found?
  while(my($truePos,$trueRef)=each(%$realSnps)){
    if($$lyveSetSnps{$truePos}){
      $TP++;  # True positive: correct SNP was found
    } else {
      $FN++;  # False negative: a real SNP was not found
    }
  }

  # How many SNPs were found that were not real?
  while(my($pos,$ref)=each(%$lyveSetSnps)){
    if($$realSnps{$pos}){
      # This is a true positive and was already counted in the previous loop.
    } else {
      $FP++;  # A SNP was found but is not in the real set of SNPs.
    }
  }

  return ($TP,$TN,$FP,$FN);
}

sub usage{
  "Compares a Lyve-SET run to a simulated dataset
  Usage: $0 --lyveset projdirectory --ttr treetoreadsdirectory
  "
}


text:
// .NAME vtkXMLStructuredGridWriter - Write VTK XML StructuredGrid files.
// .SECTION Description
// vtkXMLStructuredGridWriter writes the VTK XML StructuredGrid file
// format.  One structured grid input can be written into one file in
// any number of streamed pieces.  The standard extension for this
// writer's file format is "vts".  This writer is also used to write a
// single piece of the parallel file format.

// .SECTION See Also
// vtkXMLPStructuredGridWriter

#ifndef __vtkXMLStructuredGridWriter_h
#define __vtkXMLStructuredGridWriter_h

#include "vtkXMLStructuredDataWriter.h"

class vtkStructuredGrid;

class VTK_IO_EXPORT vtkXMLStructuredGridWriter : public vtkXMLStructuredDataWriter
{
public:
  static vtkXMLStructuredGridWriter* New();
  vtkTypeMacro(vtkXMLStructuredGridWriter,vtkXMLStructuredDataWriter);
  void PrintSelf(ostream& os, vtkIndent indent);

  //BTX
  // Description:
  // Get/Set the writer's input.
  vtkStructuredGrid* GetInput();
  //ETX

  // Description:
  // Get the default file extension for files written by this writer.
  const char* GetDefaultFileExtension();

protected:
  vtkXMLStructuredGridWriter();
  ~vtkXMLStructuredGridWriter();

  // see algorithm for more info
  virtual int FillInputPortInformation(int port, vtkInformation* info);

  void WriteAppendedPiece(int index, vtkIndent indent);
  void WriteAppendedPieceData(int index);
  void WriteInlinePiece(vtkIndent indent);
  void GetInputExtent(int* extent);
  const char* GetDataSetName();
  void CalculateSuperclassFraction(float* fractions);

  // The position of the appended data offset attribute for the points
  // array.
  OffsetsManagerGroup *PointsOM;  //one per piece

  virtual void AllocatePositionArrays();
  virtual void DeletePositionArrays();

private:
  vtkXMLStructuredGridWriter(const vtkXMLStructuredGridWriter&);  // Not implemented.
  void operator=(const vtkXMLStructuredGridWriter&);  // Not implemented.
};

#endif


text:
FROM node

RUN npm install -g coffee-script

WORKDIR /app

COPY package.json package.json
RUN npm install

COPY license-manager.coffee license-manager.coffee

CMD ["coffee", "license-manager.coffee"]


text:
package com.taobao.tddl.common.utils.extension;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;

import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.exception.ExceptionUtils;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.taobao.tddl.common.exception.TddlNestableRuntimeException;

import com.taobao.tddl.common.utils.logger.Logger;
import com.taobao.tddl.common.utils.logger.LoggerFactory;

/**
 * 包装{@linkplain ServiceLoader},提供SPI的获取方式

 * jdk自带的{@linkplain ServiceLoader}
 * 存在一些局限,无法为SPI扩展定义排序规则,如果classpath存在多个SPI配置时,加载无法确定,所以包装一下允许以后替换实现
 *
 * @see JDK5.0的自动发现机制实现
 * @author jianghang 2013-9-13 下午3:38:30
 * @since 5.0.0
 */
public class ExtensionLoader<S> {

    private static final Logger            logger             = LoggerFactory.getLogger(ExtensionLoader.class);
    private static final String            SERVICES_DIRECTORY = "META-INF/services/";
    private static final String            TDDL_DIRECTORY     = "META-INF/tddl/";
    private static Map<Class, List<Class>> providers          = Maps.newConcurrentMap();

    /**
     * 指定classloader加载server provider
     *
     * @param service
     * @param loader
     * @return
     * @throws ExtensionNotFoundException
     */
    public static <S> S load(Class<S> service, ClassLoader loader) throws ExtensionNotFoundException {
        return loadFile(service, null, loader);
    }

    /**
     * 加载server provider
     *
     * @param service
     * @return
     * @throws ExtensionNotFoundException
     */
    public static <S> S load(Class<S> service) throws ExtensionNotFoundException {
        return loadFile(service, null, findClassLoader());
    }

    /**
     * 加载server provider
     *
     * @param service
     * @return
     * @throws ExtensionNotFoundException
     */
    public static <S> S load(Class<S> service, String activateName) throws ExtensionNotFoundException {
        return loadFile(service, activateName, findClassLoader());
    }

    /**
     * 指定classloader加载server provider
     *
     * @param service
     * @param loader
     * @return
     * @throws ExtensionNotFoundException
     */
    public static <S> S load(Class<S> service, String activateName, ClassLoader loader)
                                                                                throws ExtensionNotFoundException {
        return loadFile(service, activateName, loader);
    }

    /**
     * 获取所有的扩展类,按照{@linkplain Activate}定义的order顺序进行排序
     *
     * @return
     */
    public static <S> List<Class> getAllExtendsionClass(Class<S> service) {
        return findAllExtensionClass(service, null, findClassLoader());
    }

    /**
     * 获取所有的扩展类,按照{@linkplain Activate}定义的order顺序进行排序
     *
     * @return
     */
    public static <S> List<Class> getAllExtendsionClass(Class<S> service, ClassLoader loader) {
        return findAllExtensionClass(service, null, loader);
    }

    private static <S> S loadFile(Class<S> service, String activateName, ClassLoader loader) {
        try {
            boolean foundFromCache = true;
            List<Class> extensions = providers.get(service);
            if (extensions == null) {
                synchronized (service) {
                    extensions = providers.get(service);
                    if (extensions == null) {
                        extensions = findAllExtensionClass(service, activateName, loader);
                        foundFromCache = false;
                        providers.put(service, extensions);
                    }
                }
            }

            // 为避免被覆盖,每个activateName的查找,允许再加一层子目录
            if (StringUtils.isNotEmpty(activateName)) {
                loadFile(service, TDDL_DIRECTORY + activateName.toLowerCase() + "/", loader, extensions);

                List<Class> activateExtensions = new ArrayList<Class>();
                for (int i = 0; i < extensions.size(); i++) {
                    Class clz = extensions.get(i);
                    Activate activate = (Activate) clz.getAnnotation(Activate.class);
                    if (activate != null && activateName.equals(activate.name())) {
                        activateExtensions.add(clz);
                    }
                }

                extensions = activateExtensions;
            }

            if (extensions.isEmpty()) {
                throw new ExtensionNotFoundException("not found service provider for : " + service.getName() + "["
                                                     + activateName + "] and classloader : "
                                                     + ObjectUtils.toString(loader));
            }
            Class<?> extension = extensions.get(extensions.size() - 1);// 最大的一个
            S result = service.cast(extension.newInstance());
            if (!foundFromCache && logger.isInfoEnabled()) {
                logger.info("load " + service.getSimpleName() + "[" + activateName + "] extension by class["
                            + extension.getName() + "]");
            }
            return result;
        } catch (Throwable e) {
            if (e instanceof ExtensionNotFoundException) {
                throw (ExtensionNotFoundException) e;
            } else {
                throw new ExtensionNotFoundException("not found service provider for : " + service.getName()
                                                     + " caused by " + ExceptionUtils.getFullStackTrace(e));
            }
        }
    }

    private static <S> List<Class> findAllExtensionClass(Class<S> service, String activateName, ClassLoader loader) {
        List<Class> extensions = Lists.newArrayList();
        try {
            loadFile(service, SERVICES_DIRECTORY, loader, extensions);
            loadFile(service, TDDL_DIRECTORY, loader, extensions);
        } catch (IOException e) {
            throw new TddlNestableRuntimeException(e);
        }

        if (extensions.isEmpty()) {
            return extensions;
        }

        // 做一下排序
        Collections.sort(extensions, new Comparator<Class>() {

            public int compare(Class c1, Class c2) {
                Integer o1 = 0;
                Integer o2 = 0;
                Activate a1 = (Activate) c1.getAnnotation(Activate.class);
                Activate a2 = (Activate) c2.getAnnotation(Activate.class);

                if (a1 != null) {
                    o1 = a1.order();
                }

                if (a2 != null) {
                    o2 = a2.order();
                }

                return o1.compareTo(o2);

            }
        });

        return extensions;
    }

    private static void loadFile(Class<?> service, String dir, ClassLoader classLoader, List<Class> extensions)
                                                                                throws IOException {
        String fileName = dir + service.getName();
        Enumeration<java.net.URL> urls;
        if (classLoader != null) {
            urls = classLoader.getResources(fileName);
        } else {
            urls = ClassLoader.getSystemResources(fileName);
        }

        if (urls != null) {
            while (urls.hasMoreElements()) {
                java.net.URL url = urls.nextElement();
                BufferedReader reader = null;
                try {
                    reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8"));
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        final int ci = line.indexOf('#');
                        if (ci >= 0) {
                            line = line.substring(0, ci);
                        }
                        line = line.trim();
                        if (line.length() > 0) {
                            extensions.add(Class.forName(line, true, classLoader));
                        }
                    }
                } catch (ClassNotFoundException e) {
                    // ignore
                } catch (Throwable e) {
                    logger.warn(e);// 记录一下失败日志
                } finally {
                    reader.close();
                }
            }
        }
    }

    private static ClassLoader findClassLoader() {
        // 不能使用TCCL,在pandora容器中会导致无法加载plugin中的类
        return ExtensionLoader.class.getClassLoader();
    }

}


text:
import { Attribute, ChangeDetectionStrategy, Component, ElementRef, Input, Renderer, ViewEncapsulation } from '@angular/core';

import { Config } from '../../config/config';
import { Ion } from '../ion';
import { isTrueProperty } from '../../util/util';

/**
  * @name Button
  * @module ionic
  * @description
  * Buttons are simple components in Ionic. They can consist of text and icons
  * and be enhanced by a wide range of attributes.
  * @usage
  *
  * ```html
  *
  *  <!-- Colors -->
  *  <button ion-button>Default</button>
  *
  *  <button ion-button color="secondary">Secondary</button>
  *
  *  <button ion-button color="danger">Danger</button>
  *
  *  <button ion-button color="light">Light</button>
  *
  *  <button ion-button color="dark">Dark</button>
  *
  *  <!-- Shapes -->
  *  <button ion-button full>Full Button</button>
  *
  *  <button ion-button block>Block Button</button>
  *
  *  <button ion-button round>Round Button</button>
  *
  *  <!-- Outline -->
  *  <button ion-button full outline>Outline + Full</button>
  *
  *  <button ion-button block outline>Outline + Block</button>
  *
  *  <button ion-button round outline>Outline + Round</button>
  *
  *  <!-- Icons -->
  *  <button ion-button icon-left>
  *    <ion-icon name="star"></ion-icon>
  *    Left Icon
  *  </button>
  *
  *  <button ion-button icon-right>
  *    Right Icon
  *    <ion-icon name="star"></ion-icon>
  *  </button>
  *
  *  <button ion-button icon-only>
  *    <ion-icon name="star"></ion-icon>
  *  </button>
  *
  *  <!-- Sizes -->
  *  <button ion-button large>Large</button>
  *
  *  <button ion-button>Default</button>
  *
  *  <button ion-button small>Small</button>
  * ```
  *
  * @demo /docs/v2/demos/src/button/
  * @see {@link /docs/v2/components#buttons Button Component Docs}
  * @see {@link /docs/v2/components#fabs FabButton Docs}
  * @see {@link ../../fab/FabButton FabButton API Docs}
  * @see {@link ../../fab/FabContainer FabContainer API Docs}
 */
@Component({
  selector: '[ion-button]',
  template:
    '' +
      '<ng-content></ng-content>' +
    '' +
    '

',
  changeDetection: ChangeDetectionStrategy.OnPush,
  encapsulation: ViewEncapsulation.None,
})
export class Button extends Ion {
  /** @private */
  _role: string = 'button'; // bar-button

  /** @private */
  _mt: boolean; // menutoggle

  /** @private */
  _size: string; // large/small/default

  /** @private */
  _style: string = 'default'; // outline/clear/solid

  /** @private */
  _shape: string; // round/fab

  /** @private */
  _display: string; // block/full

  /** @private */
  _init: boolean;

  /**
   * @input {boolean} Large button.
   */
  @Input()
  set large(val: boolean) {
    this._attr('_size', 'large', val);
  }

  /**
   * @input {boolean} Small button.
   */
  @Input()
  set small(val: boolean) {
    this._attr('_size', 'small', val);
  }

  /**
   * @input {boolean} Default button.
   */
  @Input()
  set default(val: boolean) {
    this._attr('_size', 'default', val);
  }

  /**
   * @input {boolean} A transparent button with a border.
   */
  @Input()
  set outline(val: boolean) {
    this._attr('_style', 'outline', val);
  }

  /**
   * @input {boolean} A transparent button without a border.
   */
  @Input()
  set clear(val: boolean) {
    this._attr('_style', 'clear', val);
  }

  /**
   * @input {boolean} Force a solid button. Useful for buttons within an item.
   */
  @Input()
  set solid(val: boolean) {
    this._attr('_style', 'solid', val);
  }

  /**
   * @input {boolean} A button with rounded corners.
   */
  @Input()
  set round(val: boolean) {
    this._attr('_shape', 'round', val);
  }

  /**
   * @input {boolean} A button that fills its parent container with a border-radius.
   */
  @Input()
  set block(val: boolean) {
    this._attr('_display', 'block', val);
  }

  /**
   * @input {boolean} A button that fills its parent container without a border-radius or borders on the left/right.
   */
  @Input()
  set full(val: boolean) {
    this._attr('_display', 'full', val);
  }

  /**
   * @input {string} The mode to apply to this component.
   */
  @Input()
  set mode(val: string) {
    this._assignCss(false);
    this._mode = val;
    this._assignCss(true);
  }

  /** @private */
  _attr(type: string, attrName: string, attrValue: boolean) {
    if (type === '_style') {
      this._updateColor(this._color, isTrueProperty(attrValue));
    }
    this._setClass((<any>this)[type], false);
    if (isTrueProperty(attrValue)) {
      (<any>this)[type] = attrName;
      this._setClass(attrName, true);

    } else {
      // Special handling for '_style' which defaults to 'default'.
      (<any>this)[type] = (type === '_style' ? 'default' : null);
      this._setClass((<any>this)[type], true);
    }
  }

  /**
   * @input {string} Dynamically set which predefined color this button should use (e.g. primary, secondary, danger, etc).
   */
  @Input()
  set color(val: string) {
    this._updateColor(this._color, false);
    this._updateColor(val, true);
    this._color = val;
  }

  constructor(
    @Attribute('menuToggle') menuToggle: string,
    @Attribute('ion-button') ionButton: string,
    config: Config,
    elementRef: ElementRef,
    renderer: Renderer
  ) {
    super(config, elementRef, renderer);
    this._mode = config.get('mode');

    if (config.get('hoverCSS') === false) {
      this.setElementClass('disable-hover', true);
    }

    if (ionButton.trim().length > 0) {
      this.setRole(ionButton);
    }

    // menuToggle can be added with or without a string
    // but if the attribute isn't added it will be null
    if (menuToggle !== null) {
      this._mt = true;
    }
  }

  /** @private */
  ngAfterContentInit() {
    this._init = true;
    this._assignCss(true);
  }

  /**
   * @private
   */
  setRole(val: string) {
    this._assignCss(false);
    this._role = val;
    this._assignCss(true);
  }

  /**
   * @private
   */
  _assignCss(assignCssClass: boolean) {
    let role = this._role;
    if (role) {
      this.setElementClass(role, assignCssClass); // button
      this.setElementClass(`${role}-${this._mode}`, assignCssClass); // button

      this._setClass('menutoggle', this._mt); // menutoggle
      this._setClass(this._style, assignCssClass); // button-clear
      this._setClass(this._shape, assignCssClass); // button-round
      this._setClass(this._display, assignCssClass); // button-full
      this._setClass(this._size, assignCssClass); // button-small
      this._updateColor(this._color, assignCssClass); // button-secondary, bar-button-secondary
    }
  }

  /**
   * @private
   */
  _setClass(type: string, assignCssClass: boolean) {
    if (type && this._init) {
      type = type.toLocaleLowerCase();
      this.setElementClass(`${this._role}-${type}`, assignCssClass);
      this.setElementClass(`${this._role}-${type}-${this._mode}`, assignCssClass);
    }
  }

  /**
   * @private
   */
  _updateColor(color: string, isAdd: boolean) {
    if (color && this._init) {
      // The class should begin with the button role
      // button, bar-button
      let className = this._role;

      // If the role is not a bar-button, don't apply the solid style
      let style = this._style;
      style = (this._role !== 'bar-button' && style === 'solid' ? 'default' : style);

      className += (style !== null && style !== '' && style !== 'default' ? '-' + style.toLowerCase() : '');

      if (color !== null && color !== '') {
        this.setElementClass(`${className}-${this._mode}-${color}`, isAdd);
      }
    }
  }
}


text:
package io.cdap.plugin.zuora.restobjects;

import io.cdap.plugin.zuora.restobjects.annotations.ObjectDefinition;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Entity meta-info holder for {@link ObjectDefinition}.
 */
public class ObjectInfo {
  private String cdapObjectName;

  private String restAPIUrl;
  private Class objectClass;
  private List<ObjectFieldInfo> fieldDefinitions;
  private List<String> requiredArguments;
  private List<String> requiredPostArguments;
  private ObjectDefinition.ObjectDefinitionType objectType;
  private String responseRootElement;

  /**
   * Constructor for ObjectInfo object.
   * @param cdapObjectName the cdap object name
   * @param fieldDefinitions the field definitions
   * @param restAPIUrl the result api url
   * @param objectClass the object class
   * @param requiredArguments required arguments
   * @param requiredPostArguments required post arguments
   * @param responseRootElement response root element
   * @param objectType object type
   */
  public ObjectInfo(String cdapObjectName, List<ObjectFieldInfo> fieldDefinitions, String restAPIUrl,
                    Class objectClass, List<String> requiredArguments, List<String> requiredPostArguments,
                    String responseRootElement, ObjectDefinition.ObjectDefinitionType objectType) {
    this.cdapObjectName = cdapObjectName;
    this.fieldDefinitions = fieldDefinitions;
    this.restAPIUrl = restAPIUrl;
    this.objectClass = objectClass;
    this.requiredArguments = requiredArguments;
    this.requiredPostArguments = requiredPostArguments;
    this.objectType = objectType;
    this.responseRootElement = responseRootElement;
  }

  public String getCdapObjectName() {
    return cdapObjectName;
  }

  public String getRestAPIUrl() {
    return restAPIUrl;
  }

  public List<ObjectFieldInfo> getFieldDefinitions() {
    return fieldDefinitions;
  }

  /**
   * Returns the list of ObjectFieldInfo.
   * @param fields
   * @return list of ObjectFieldInfo
   */
  public List<ObjectFieldInfo> getFieldsDefinitions(List<String> fields) {
    return fieldDefinitions.stream()
      .filter(x -> fields.stream().anyMatch(y -> x.getName().equals(y)))
      .collect(Collectors.toList());
  }

  public Class getObjectClass() {
    return objectClass;
  }

  public List<String> getRequiredArguments() {
    return requiredArguments.stream().filter(x -> !x.equals("")).collect(Collectors.toList());
  }

  public List<String> getRequiredPostArguments() {
    return requiredPostArguments.stream().filter(x -> !x.equals("")).collect(Collectors.toList());
  }

  public ObjectDefinition.ObjectDefinitionType getObjectType() {
    return objectType;
  }

  public String getResponseRootElement() {
    return responseRootElement;
  }
}


text:
namespace IdentitySample;

public static class Program
{
    public static void Main(string[] args)
    {

        var host = CreateHostBuilder(args).Build();
        host.Run();
    }

    public static IWebHostBuilder CreateHostBuilder(string[] args) =>
        new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>();
}


text:
'use strict';

describe('Controller: GameCtrl', function () {

  // load the controller's module
  beforeEach(module('matchupApp'));

  var GameCtrl,
    scope;

  // Initialize the controller and a mock scope
  beforeEach(inject(function ($controller, $rootScope) {
    scope = $rootScope.$new();
    GameCtrl = $controller('GameCtrl', {
      $scope: scope
    });
  }));
});


text:
using System;
using System.Collections.Generic;
using System.Reflection.Metadata.Ecma335;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Net.Http;
using System.Text.Json.Serialization;
using System.Text.Json;

namespace AppZapper
{
    public sealed class Experiment
    {
        private static long ExperimentCounter = 1;
        private long _experimentNumber;
        private string _experimentPath;
        private Process _experimentProcess;
        private ZeroBlockList _committedList;
        private ZeroBlockList _attemptingList;

        public Experiment(ZeroBlockList committedList, ZeroBlockList attemptingList)
        {
            // Assign an experiment number and increment the global counter.
            _experimentNumber = ExperimentCounter++;

            // Save the zero block lists.
            _committedList = committedList;
            _attemptingList = attemptingList;
        }

        public long Number
        {
            get { return _experimentNumber; }
        }

        public bool Succeeded
        {
            get; private set;
        }

        public ZeroBlockList CommittedList
        {
            get { return _committedList; }
        }

        public ZeroBlockList AttemptingList
        {
            get { return _attemptingList; }
        }

        public void Execute()
        {
            Log("========");
            Log($"New Experiment [{_experimentNumber}]: {_committedList.Count} blocks committed.");
            Log("========");

            // Make a new directory for the experiment.
            _experimentPath = Path.Combine(Config.TempDirectoryRoot, _experimentNumber.ToString());
            Directory.CreateDirectory(_experimentPath);

            // Copy the app into the experiment directory.
            Utilities.CopyDirectory(Config.AppDirectory, _experimentPath, true);

            // Modify the binary.
            BinaryModifier.ApplyZeroBlocks(
                Path.Combine(_experimentPath, Config.AppExeName),
                _committedList,
                _attemptingList);

            // Start the app.
            Log("Starting test process.");
            ProcessStartInfo startInfo = GetStartInfo();
            _experimentProcess = Process.Start(startInfo);

            // Verify that the app started properly.
            bool processStartedSuccessfully = false;

            Task watchConsoleTask = Task.Run(() =>
            {
                StreamReader standardOutput = _experimentProcess.StandardOutput;
                while (!standardOutput.EndOfStream)
                {
                    // Read the line.
                    string line = standardOutput.ReadLine();

                    // Write it to the console.
                    Log(line);

                    // See if the line matches what we're looking for.
                    if (line.StartsWith(Config.AppStartupSuccessStartString))
                    {
                        Log("Process started successfully.");
                        processStartedSuccessfully = true;
                        break;
                    }
                }
            });

            DateTime timeOutTime = DateTime.UtcNow.Add(Config.OperationTimeout);

            while ((!processStartedSuccessfully) && (!watchConsoleTask.IsCompleted) && (timeOutTime > DateTime.UtcNow))
            {
                watchConsoleTask.Wait(Config.PollingInterval);
            }

            // If the app didn't start successfully, kill it and abort the experiment.
            if(!processStartedSuccessfully)
            {
                _experimentProcess.Kill(true);
                return;
            }

            // Exercise the app.
            Task requestsTask = SendAndValidateRequests();
            requestsTask.Wait(Config.OperationTimeout);

            // Shutdown the app.
            Task shutdownTask = ShutdownApp();
            shutdownTask.Wait(Config.OperationTimeout);

            // Mark the experiment as succeeded if everything completed successfully.
            if(requestsTask.IsCompleted && (requestsTask.Exception == null) && shutdownTask.IsCompleted && (shutdownTask.Exception == null))
            {
                if (!_experimentProcess.HasExited)
                {
                    // Wait for graceful shutdown.
                    _experimentProcess.WaitForExit(Config.ShutdownTimeOutMilliseconds);
                    if (!_experimentProcess.HasExited)
                    {
                        Log("Failed to exit gracefully.  Terminating process.");
                        _experimentProcess.Kill(true);
                    }
                    else
                    {
                        if (_experimentProcess.ExitCode == 0)
                        {
                            Succeeded = true;
                        }
                    }
                }
                else
                {
                    if (_experimentProcess.ExitCode == 0)
                    {
                        Succeeded = true;
                    }
                }
            }
            else
            {
                Log("Abnormal behavior or termination.  Attempting to terminate process.");
                if(!_experimentProcess.HasExited)
                {
                    _experimentProcess.Kill(true);
                }
                Log("Process terminated.");
            }
        }

        private async Task ShutdownApp()
        {
            Log("Shutting down.");
            using (HttpClient httpClient = new HttpClient())
            {
                HttpResponseMessage responseMessage = await httpClient.GetAsync(Config.ShutdownUrl);
                responseMessage.EnsureSuccessStatusCode();
            }
        }

        private async Task SendAndValidateRequests()
        {
            Log($"Executing {Config.NumRequests} requests.");
            using (HttpClient httpClient = new HttpClient())
            {
                for (int i = 0; i < Config.NumRequests; i++)
                {
                    HttpResponseMessage responseMessage = await httpClient.GetAsync(Config.ServerUrl);
                    responseMessage.EnsureSuccessStatusCode();
                    string body = await responseMessage.Content.ReadAsStringAsync();
                    WeatherForecast[] forecastResponse = JsonSerializer.Deserialize<WeatherForecast[]>(body);
                    foreach (WeatherForecast forecast in forecastResponse)
                    {
                        if (!((forecast.Date != default) &&
                            !string.IsNullOrEmpty(forecast.Summary) &&
                            (forecast.TemperatureC >= -20 && forecast.TemperatureC <= 55) &&
                            (forecast.TemperatureF == (32 + (int)(forecast.TemperatureC / 0.5556)))))
                        {
                            throw new InvalidOperationException("The response provided does not match the expected result.");
                        }
                    }
                }
            }
        }

        private ProcessStartInfo GetStartInfo()
        {
            return new ProcessStartInfo(Path.Combine(_experimentPath, Config.AppExeName))
            {
                UseShellExecute = false,
                RedirectStandardOutput = true,
                CreateNoWindow = true
            };
        }

        private void Log(string message)
        {
            Console.WriteLine($"[{_experimentNumber}] {message}");
        }

        public void CopyTo(string destinationPath)
        {
            if (Directory.Exists(destinationPath))
            {
                Directory.Delete(destinationPath, recursive: true);
            }
            Directory.CreateDirectory(destinationPath);

            Utilities.CopyDirectory(_experimentPath, destinationPath, true);
        }

        public void Complete()
        {
            if(Succeeded)
            {
                ZeroBlockList committedList = new ZeroBlockList();
                committedList.AddRange(_committedList);
                committedList.AddRange(_attemptingList);
                _committedList = committedList;

                _attemptingList = new ZeroBlockList();
            }

            Delete();
        }

        public void Delete()
        {
            if (Directory.Exists(_experimentPath))
            {
                Directory.Delete(_experimentPath, true);
            }
        }
    }

    /// <summary>
    /// Structure to deserialize the message body into.
    /// </summary>
    public class WeatherForecast
    {
        [JsonPropertyName("date")]
        public DateTime Date { get; set; }
        [JsonPropertyName("temperatureC")]
        public int TemperatureC { get; set; }
        [JsonPropertyName("temperatureF")]
        public int TemperatureF { get; set; }
        [JsonPropertyName("summary")]
        public string Summary { get; set; }
    }
}


text:
/* @flow */

import type { Decoder, Decode } from "./Decoder"
import { MissmatchError } from "./Error"

export interface MatchDecoder<+a> {
  type: "Match";
  match: a;
}

const matches = <a>(actual: a, expected: a): boolean => {
  if (actual === expected) {
    return true
  } else {
    if (
      actual &&
      typeof actual === "object" &&
      expected &&
      typeof expected === "object"
    ) {
      if (Array.isArray(expected)) {
        if (Array.isArray(actual)) {
          const count = expected.length
          let index = 0
          let isMatch = count <= actual.length
          while (isMatch && index < count) {
            isMatch = matches(actual[index], expected[index])
            index++
          }
          return isMatch
        } else {
          return false
        }
      } else {
        for (const key in expected) {
          if (Object.prototype.hasOwnProperty.call(expected, key)) {
            if (!matches(actual[key], expected[key])) {
              return false
            }
          }
        }
        return true
      }
    } else {
      return false
    }
  }
}

export default class Match<a> implements MatchDecoder<a> {
  type: "Match" = "Match"
  match: a
  constructor(match: a) {
    this.match = match
  }
  static decode<a>(match: a, input: mixed): Decode<a> {
    if (matches(input, match)) {
      return match
    } else {
      return new MissmatchError(input, match)
    }
  }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Rua</tipo><logradouro>Acerola</logradouro><bairro>Limoeiro</bairro><cidade>Ipatinga</cidade><uf>MG</uf><cep>35162468</cep></feed>


text:
![Northern Mockingbird](http://www.biokids.umich.edu/collections/contributors/grzimek_birds/Mimidae/Mimus_polyglottos/medium.jpg)

[Image Source](http://www.biokids.umich.edu/critters/Mimus_polyglottos/pictures/resources/contributors/grzimek_birds/Mimidae/Mimus_polyglottos/)

[![Build Status](https://travis-ci.org/lateefj/mctest.svg?branch=master)](https://travis-ci.org/lateefj/mctest)

McTest is a Go (golang) web test library. Initally started as a gist and is slowly getting used more for testing webservices written in Go.

## Goals

 * Simple quick way to test Middleware (wrappers around http handler)
 * Quickly be able to test web service (JSON)
 * Highlevel function integration tests

## Basic API

### AssertCode(http.StatusOK) bool

This simple failes the test if the code does not match the one passed in

### AssertBody(string)  bool

If the string that is passed in doesn't match then fail the test.

#### AssertJson(instance interface{}, expectedMatchStruct interface{}) bool

By passing a struct this will validate that the response json has the same values

#### Bytes() []byte

Comparing bytes can be achieved by calling resp.Bytes().

## Use Cases

### Basic

```go
// Application code example
func HomeHandler(w http.ResponseWriter, r *http.Request) {
  w.WriteHeader(http.StatusOK)
  fmt.Fprintf(w, "HomeHandler")
}

// Testing application code
func TestHome(t *testing.T) {
  req, _ := http.NewRequest("GET", "/path/to/handler", nil)
  resp := NewMockTestResponse(t)
  HomeHandler(resp, req)
  b := "HomeHandler"
  if !resp.AssertCode(http.StatusOK) {
    t.Fatalf("Response StatusCode is %d asserted that it is %d", resp.StatusCode, http.StatusOK)
  }
  if !resp.AssertBody(b) {
    t.Fatalf("Response body is %s asserted that it is %s", resp.String(), b)
  }
}
```

### Json

```go

// JSON Stuct
type payload struct {
  X string `json:"x"`
  Y string `json:"y"`
}
// JSON API
func HomeHandler(w http.ResponseWriter, r *http.Request) {
  w.WriteHeader(http.StatusOK)
  fmt.Fprintf(w, "{\"x\":\"bar\", \"y\":\"foo\"}")
}
// Test JSON API
func TestHome(t *testing.T) {
  req, _ := http.NewRequest("GET", "/path/to/handler", nil)
  resp := NewMockTestResponse(t)
  HomeHandler(resp, req)
  b := "HomeHandler"
  if !resp.AssertCode(http.StatusOK) {
    t.Fatalf("Response StatusCode is %d asserted that it is %d", resp.StatusCode, http.StatusOK)
  }
  p := &payload{X: "bar", Y: "foo"}
  inst := &payload{}
  if !resp.AssertJson(inst, p) {
    t.Fatalf("Response body is %s asserted that it is %v", resp.String(), p)
  }
}
```

### Middleware

```go
// App authentication wrapper
func testAuthWrapper(fn http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		a, err := r.Cookie(authCookieName)
		if err != nil || a == nil {
			w.WriteHeader(http.StatusUnauthorized)
			w.Write([]byte(failedAuth))
		} else {
			fn(w, r)
		}
	}
}
// Handler code
func testAuthHandler(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusOK)
	w.Write([]byte("TestAuthHandler"))
}
// Actual test code
func TestAuthMiddleware(t *testing.T) {
	req, _ := http.NewRequest("GET", "/path/to/handler", nil)
  // Create mock
	resp := NewMockTestResponse(t)
	testAuthWrapper(testAuthHandler)(resp, req)
	if !resp.AssertCode(http.StatusUnauthorized) {
		t.Fatalf("Response StatusCode is %d asserted that it is %d", resp.StatusCode, http.StatusUnauthorized)
	}
	if !resp.AssertBody(failedAuth) {
		t.Fatalf("Response body is %s asserted that it is %s", resp.String(), failedAuth)
	}
	b := "TestAuthHandler"
  // Add auth cookie
	req.AddCookie(authCookie)
	resp = NewMockTestResponse(t)
	// Run the code again
	testAuthWrapper(testAuthHandler)(resp, req)
	if !resp.AssertCode(http.StatusOK) {
		t.Fatalf("Response StatusCode is %d asserted that it is %d", resp.StatusCode, http.StatusOK)
	}
	if !resp.AssertBody(b) {
		t.Fatalf("Response body is %s asserted that it is %s", resp.String(), b)
	}
}
```

Check the http_test.go for more examples on how to use the api.


text:
package builtin

import (
	. "github.com/hyperledger/fabric/core/handlers/endorsement/api"
	. "github.com/hyperledger/fabric/core/handlers/endorsement/api/identities"
	"github.com/hyperledger/fabric/protos/peer"
	"github.com/pkg/errors"
)

// DefaultEndorsementFactory returns an endorsement plugin factory which returns plugins
// that behave as the default endorsement system chaincode
type DefaultEndorsementFactory struct {
}

// New returns an endorsement plugin that behaves as the default endorsement system chaincode
func (*DefaultEndorsementFactory) New() Plugin {
	return &DefaultEndorsement{}
}

// DefaultEndorsement is an endorsement plugin that behaves as the default endorsement system chaincode
type DefaultEndorsement struct {
	SigningIdentityFetcher
}

// Endorse signs the given payload(ProposalResponsePayload bytes), and optionally mutates it.
// Returns:
// The Endorsement: A signature over the payload, and an identity that is used to verify the signature
// The payload that was given as input (could be modified within this function)
// Or error on failure
func (e *DefaultEndorsement) Endorse(prpBytes []byte, sp *peer.SignedProposal) (*peer.Endorsement, []byte, error) {
	signer, err := e.SigningIdentityForRequest(sp)
	if err != nil {
		return nil, nil, errors.Wrap(err, "failed fetching signing identity")
	}
	// serialize the signing identity
	identityBytes, err := signer.Serialize()
	if err != nil {
		return nil, nil, errors.Wrapf(err, "could not serialize the signing identity")
	}

	// sign the concatenation of the proposal response and the serialized endorser identity with this endorser's key
	signature, err := signer.Sign(append(prpBytes, identityBytes...))
	if err != nil {
		return nil, nil, errors.Wrapf(err, "could not sign the proposal response payload")
	}
	endorsement := &peer.Endorsement{Signature: signature, Endorser: identityBytes}
	return endorsement, prpBytes, nil
}

// Init injects dependencies into the instance of the Plugin
func (e *DefaultEndorsement) Init(dependencies ...Dependency) error {
	for _, dep := range dependencies {
		sIDFetcher, isSigningIdentityFetcher := dep.(SigningIdentityFetcher)
		if !isSigningIdentityFetcher {
			continue
		}
		e.SigningIdentityFetcher = sIDFetcher
		return nil
	}
	return errors.New("could not find SigningIdentityFetcher in dependencies")
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<pack>
    <snippet attachedevent="true" class="scripts.SceneEvents_0" classname="scripts.SceneEvents_0" desc="Scene Specific Events" description="Scene Specific Events" design="true" drawOrder="0" id="1" name="SceneEvents_0" oid="-1" package="scripts." sceneid="0" scenespecific="true" shared="false" type="scene">
        <boolean default="false" defaultValue="false" desc="" dropdown="" fullname="Already Started" hidden="false" id="1" name="_AlreadyStarted" order="0"/>
        <list default="list" defaultValue="list" desc="" dropdown="" fullname="controls" hidden="false" id="2" name="_controls" order="1"/>
        <blocks/>
        <events>
            <event displayName="Created" enabled="true" id="1" name="init" order="1" repeats="true"/>
            <event displayName="Keyboard" enabled="true" id="2" name="event-key-press-release" order="5" repeats="true"/>
            <event displayName="Touch Control Update" enabled="true" id="3" name="step" order="4" repeats="true"/>
            <event displayName="Debug Font Code" enabled="false" id="4" name="event-custom-code" order="7" repeats="true"/>
            <event displayName="Debug Font Drawing" enabled="false" id="5" name="draw" order="10" repeats="true"/>
            <event displayName="Profiling" enabled="false" id="6" name="init" order="6" repeats="true"/>
            <event displayName="Debug Font Setup" enabled="false" id="7" name="init" order="9" repeats="true"/>
            <event displayName="Gamepad Setup" enabled="true" id="8" name="init" order="2" repeats="true"/>
            <event displayName="Touch Control Setup" enabled="true" id="9" name="init" order="3" repeats="true"/>
        </events>
    </snippet>
    <snippet attachedevent="true" class="scripts.ActorEvents_17" classname="scripts.ActorEvents_17" desc="Actor Specific Events" description="Actor Specific Events" design="true" drawOrder="0" id="3" name="ActorEvents_17" oid="-1" package="scripts." scenespecific="false" shared="false" type="actor">
        <number default="0.0" defaultValue="0.0" desc="" dropdown="" fullname="Opacity" hidden="false" id="1" name="_Opacity" order="0"/>
        <blocks/>
        <events>
            <event displayName="Drawing" enabled="true" id="1" name="draw" order="2" repeats="true"/>
            <event displayName="Created" enabled="true" id="2" name="init" order="1" repeats="true"/>
        </events>
    </snippet>
    <snippet attachedevent="true" class="scripts.ActorEvents_21" classname="scripts.ActorEvents_21" desc="Actor Specific Events" description="Actor Specific Events" design="true" drawOrder="0" id="4" name="ActorEvents_21" oid="-1" package="scripts." scenespecific="false" shared="false" type="actor">
        <blocks/>
        <events/>
    </snippet>
    <snippet attachedevent="true" class="scripts.ActorEvents_34" classname="scripts.ActorEvents_34" desc="Actor Specific Events" description="Actor Specific Events" design="true" drawOrder="0" id="5" name="ActorEvents_34" oid="-1" package="scripts." scenespecific="false" shared="false" type="actor">
        <blocks/>
        <events/>
    </snippet>
    <snippet attachedevent="false" class="scripts.Design_6_6_TouchControl" classname="scripts.Design_6_6_TouchControl" desc="" description="" design="true" drawOrder="0" id="6" name="Touch Control" oid="-1" package="scripts" scenespecific="false" shared="false" type="actor">
        <text default="" defaultValue="" desc="" dropdown="" fullname="control" hidden="false" id="1" name="_control" order="1"/>
        <control default="" defaultValue="" desc="" dropdown="" fullname="ctrl" hidden="true" id="2" name="_ctrl" order="2"/>
        <boolean default="false" defaultValue="false" desc="" dropdown="" fullname="down" hidden="true" id="3" name="_down" order="3"/>
        <actor default="thisactor" defaultValue="thisactor" desc="" dropdown="" fullname="Actor" hidden="true" id="2147483647" name="actor" order="0"/>
        <blocks/>
        <events>
            <event displayName="Created" enabled="true" id="1" name="init" order="1" repeats="true"/>
            <event displayName="checkInput" enabled="true" id="5" name="event-custom" order="3" repeats="true"/>
        </events>
    </snippet>
    <snippet attachedevent="false" class="scripts.Design_7_7_SceneSwitcher" classname="scripts.Design_7_7_SceneSwitcher" desc="" description="" design="true" drawOrder="0" id="7" name="Scene Switcher" oid="-1" package="scripts" scenespecific="false" shared="false" type="scene">
        <blocks/>
        <events>
            <event displayName="gotoScene" enabled="true" id="1" name="event-custom-code" order="1" repeats="true"/>
        </events>
    </snippet>
    <snippet attachedevent="true" class="scripts.SceneEvents_1" classname="scripts.SceneEvents_1" desc="Scene Specific Events" description="Scene Specific Events" design="true" drawOrder="0" id="8" name="SceneEvents_1" oid="-1" package="scripts." sceneid="1" scenespecific="true" shared="false" type="scene">
        <blocks/>
        <events/>
    </snippet>
</pack>


text:
describe('Edit flashcardlist scenarios', function() {

  describe('The view', function() {
    var INITIAL_NUMBER_OF_LISTS = 3;

    beforeEach(function() {
        browser().navigateTo('/');
        restartDB();
        browser().navigateTo('/#/FlashcardList');
    });

    it('should not contain a modal after starting the page', function() {
        expect(element('.modal.edit-list-modal').count()).toBe(0);
    });

    it('should show edit modal after clicking on the second edit button', function() {
        element('.flashcard-list-container > div:nth-child(3) :button.edit-flashcard-list').click();

        expect(element('.modal.edit-list-modal').count()).toBe(1);
        expect(input('modalObject.title').val()).toMatch('Spanish for beginners');
    });

    it('should do nothing after clicking the cancel button', function() {
        element('.flashcard-list-container > div:nth-child(3) :button.edit-flashcard-list').click();
        expect(element('.modal.edit-list-modal').count()).toBe(1);

        input('modalObject.title').enter('Klingon for beginners');
        element('.modal .close-button').click();

        expect(element('modal.edit.list-modal').count()).toBe(0);

        var titleElement = element('.flashcard-list-container > div:nth-child(3) .flashcard-list-title');
        expect(titleElement.text()).toContain('Spanish for beginners');
    });

    it('should change the list title after clicking the ok button', function() {
        element('.flashcard-list-container > div:first :button.edit-flashcard-list').click();
        expect(element('.modal.edit-list-modal').count()).toBe(1);

        input('modalObject.title').enter('Klingon for beginners');
        element('.modal .save-button').click();

        expect(element('modal.edit.list-modal').count()).toBe(0);

        var titleElement = element('.flashcard-list-container > .flashcardlist:first .flashcard-list-title');
        expect(titleElement.text()).toContain('Klingon for beginners');
    });

    it('should change the list and remain after refresh', function() {
        element('.flashcard-list-container > div:first :button.edit-flashcard-list').click();
        expect(element('.modal.edit-list-modal').count()).toBe(1);

        input('modalObject.title').enter('Klingon for beginners');
        element('.modal .save-button').click();

        expect(element('modal.edit.list-modal').count()).toBe(0);

        var titleElement = element('.flashcard-list-container > .flashcardlist:first .flashcard-list-title');
        expect(titleElement.text()).toContain('Klingon for beginners');

        browser().reload();
        expect(repeater('.flashcard-list-container > div').count()).toBe(INITIAL_NUMBER_OF_LISTS);
    });

    it('should ensure sorting at editing', function() {
        element('.flashcard-list-container > div:nth-child(2) :button.edit-flashcard-list').click();
        expect(element('.modal.edit-list-modal').count()).toBe(1);

        input('modalObject.title').enter('AAAAA');
        element('.modal .save-button').click();

        expect(element('modal.edit.list-modal').count()).toBe(0);

        var titleElement = element('.flashcard-list-container > div:first .flashcard-list-title');
        expect(titleElement.text()).toContain('AAAAA');

        browser().reload();
        expect(repeater('.flashcard-list-container > div').count()).toBe(INITIAL_NUMBER_OF_LISTS);
    });
  });
});


text:
package com.aspose.imaging.examples.ManipulatingJPEGImages;

import com.aspose.imaging.Image;
import com.aspose.imaging.examples.Utils;
import com.aspose.imaging.exif.ExifData;
import com.aspose.imaging.fileformats.jpeg.JpegImage;

public class ReadingEXIFData
{
    public static void main(String... args)
    {
        // The path to the documents directory.
        String dataDir = Utils.getSharedDataDir() + "ManipulatingJPEGImages/";
        //ExStart:ReadingEXIFData
        Image image = Image.load(dataDir + "aspose-logo.jpg");

		try
		{
			// Initialize an object of ExifData and fill it will image's EXIF
			// information
			ExifData exif = ((JpegImage) image).getExifData();

			// Check if image has any EXIF entries defined
			if (exif != null)
			{
				// Display a few EXIF entries
				System.out.println("Exif WhiteBalance: " + exif.getWhiteBalance());
				System.out.println("Exif PixelXDimension: " + exif.getPixelXDimension());
				System.out.println("Exif PixelYDimension: " + exif.getPixelYDimension());
				System.out.println("Exif ISOSpeed: " + exif.getISOSpeed());
				System.out.println("Exif BodySerialNumber: " + exif.getBodySerialNumber());
				System.out.println("Exif CameraOwnerName: " + exif.getCameraOwnerName());
				System.out.println("Exif ColorSpace: " + exif.getColorSpace());
				System.out.println("Exif Contrast: " + exif.getContrast());
				System.out.println("Exif CustomRendered: " + exif.getCustomRendered());
				System.out.println("Exif DateTimeDigitized: " + exif.getDateTimeDigitized());
				System.out.println("Exif DateTimeOriginal: " + exif.getDateTimeOriginal());
				System.out.println("Exif ExposureMode: " + exif.getExposureMode());
				System.out.println("Exif ExposureProgram: " + exif.getExposureProgram());
				System.out.println("Exif Flash: " + exif.getFlash());
				System.out.println("Exif FocalLengthIn35MmFilm: " + exif.getFocalLengthIn35MmFilm());
				System.out.println("Exif FocalPlaneResolutionUnit: " + exif.getFocalPlaneResolutionUnit());
				System.out.println("Exif GainControl: " + exif.getGainControl());
				System.out.println("Exif ImageUniqueID: " + exif.getImageUniqueID());
				System.out.println("Exif Sharpness: " + exif.getSharpness());
				System.out.println("Exif MeteringMode: " + exif.getMeteringMode());
			}
		}
		finally
		{
			image.close();

		}
		//ExEnd:ReadingEXIFData
    }

}