text:
var log;
var redNodes;
var settings;

module.exports = {
    init: function(runtime) {
        settings = runtime.settings;
        redNodes = runtime.nodes;
        log = runtime.log;
    },
    get: function(req,res) {
        var id = req.params.id;
        var flow = redNodes.getFlow(id);
        if (flow) {
            log.audit({event: "flow.get",id:id},req);
            res.json(flow);
        } else {
            log.audit({event: "flow.get",id:id,error:"not_found"},req);
            res.status(404).end();
        }
    },
    post: function(req,res) {
        var flow = req.body;
        redNodes.addFlow(flow).then(function(id) {
            log.audit({event: "flow.add",id:id},req);
            res.json({id:id});
        }).otherwise(function(err) {
            log.audit({event: "flow.add",error:err.code||"unexpected_error",message:err.toString()},req);
            res.status(400).json({error:err.code||"unexpected_error", message:err.toString()});
        })

    },
    put: function(req,res) {
        var id = req.params.id;
        var flow = req.body;
        try {
            redNodes.updateFlow(id,flow).then(function() {
                log.audit({event: "flow.update",id:id},req);
                res.json({id:id});
            }).otherwise(function(err) {
                log.audit({event: "flow.update",error:err.code||"unexpected_error",message:err.toString()},req);
                res.status(400).json({error:err.code||"unexpected_error", message:err.toString()});
            })
        } catch(err) {
            if (err.code === 404) {
                log.audit({event: "flow.update",id:id,error:"not_found"},req);
                res.status(404).end();
            } else {
                log.audit({event: "flow.update",error:err.code||"unexpected_error",message:err.toString()},req);
                res.status(400).json({error:err.code||"unexpected_error", message:err.toString()});
            }
        }
    },
    delete: function(req,res) {
        var id = req.params.id;
        try {
            redNodes.removeFlow(id).then(function() {
                log.audit({event: "flow.remove",id:id},req);
                res.status(204).end();
            })
        } catch(err) {
            if (err.code === 404) {
                log.audit({event: "flow.remove",id:id,error:"not_found"},req);
                res.status(404).end();
            } else {
                log.audit({event: "flow.remove",id:id,error:err.code||"unexpected_error",message:err.toString()},req);
                res.status(400).json({error:err.code||"unexpected_error", message:err.toString()});
            }
        }
    }
}


text:
Plugin.define "USP-Secure-Entry-Server" do
author "Brendan Coles <bcoles@gmail.com>" # 2011-08-25
version "0.1"
description "United Security Providers (USP; previously known as Tetrade) Secure Entry Server (SES) Web Application Firewall (WAF)"
website "http://www.united-security-providers.com/"

# The United Security Providers (USP; previously known as Tetrade) components Secure Entry Server (SES) and Secure Login Service (SLS) share their tasks in order to adhere to the principles of separation of powers. The task of the SES is to recognize non-authenticated users and to ensure that they are authenticated by the SLS (Access Control Enforcement Function). The task of the SLS is to perform the authentication (Authentication and Access Control Decision Function). The communication between SES and SLS is based on custom HTTP headers. The SES sends the desired user login type to the SLS which performs the authentication. Once the login is completed, the SLS signals the success or failure of the process back to the SES. According to this, the SES determines the access rights of the user.

# ShodanHQ results as at 2011-08-25 #
# 56 for Secure Entry Server

# Matches #
matches [

# HTTP Server Header
{ :search=>"headers[server]", :regexp=>/^Secure Entry Server$/ },

]

end

redpajama_set_name: RedPajamaGithub


text:
package com.github.shredder121.gh_event_api.handler.fork;

import static com.github.shredder121.gh_event_api.testutil.HamcrestHelpers.BaxterAndTheHackers.*;
import static com.github.shredder121.gh_event_api.testutil.HamcrestHelpers.BaxterTheHacker.*;
import static com.github.shredder121.gh_event_api.testutil.HamcrestHelpers.*;
import static java.util.Arrays.asList;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.is;

import com.github.shredder121.gh_event_api.handler.AbstractTestHandlerBean;

class TestHandler extends AbstractTestHandlerBean implements ForkHandler {

    @Override
    public void handle(ForkPayload payload) {
        errorCollector.checkThat(payload, allOf(asList(
                property(ForkPayload::getSender, is(BAXTERANDTHEHACKERS)),
                property(ForkPayload::getRepository, is(BAXTERTHEHACKER_PUBLIC_REPO)),
                property(ForkPayload::getForkee, is(BAXTERANDTHEHACKERS_PUBLIC_REPO))
        )));
        countDownLatch.countDown();
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <IncludeCompositeObjects>True</IncludeCompositeObjects>
    <TargetDatabaseName>Makc2016</TargetDatabaseName>
    <DeployScriptFileName>Makc2016.sql</DeployScriptFileName>
    <TargetConnectionString>Data Source=.\SQLEXPRESS;Integrated Security=True;Persist Security Info=False;Pooling=False;MultipleActiveResultSets=False;Connect Timeout=60;Encrypt=False;TrustServerCertificate=True</TargetConnectionString>
    <ProfileVersionNumber>1</ProfileVersionNumber>
    <BlockOnPossibleDataLoss>False</BlockOnPossibleDataLoss>
    <BackupDatabaseBeforeChanges>True</BackupDatabaseBeforeChanges>
    <DropObjectsNotInSource>True</DropObjectsNotInSource>
    <DoNotDropCertificates>True</DoNotDropCertificates>
    <DoNotDropCredentials>True</DoNotDropCredentials>
    <DoNotDropLogins>True</DoNotDropLogins>
    <DoNotDropPermissions>True</DoNotDropPermissions>
    <DoNotDropUsers>True</DoNotDropUsers>
  </PropertyGroup>
</Project>


text:
module Amr
  class CheckingValidatedReadingsForAMeter
    NAN_READINGS = Array.new(48, Float::NAN).freeze

    def initialize(dashboard_meter)
      @dashboard_meter = dashboard_meter
    end

    def perform
      pp "Checking: #{@dashboard_meter} with mpan_mprn: #{@dashboard_meter.mpan_mprn} id: #{@dashboard_meter.external_meter_id}"
      amr_data = @dashboard_meter.amr_data

      readings_to_delete = AmrValidatedReading.where(meter_id: @dashboard_meter.external_meter_id).where.not(reading_date: amr_data.keys)
      deleted_count = readings_to_delete.count
      readings_to_delete.delete_all
      pp "Checked: #{@dashboard_meter} - deleted: #{deleted_count}"
    end
  end
end


text: {{+partials.standard_apps_article article:intros.manifest/manifest_version/}}


text:
from django.test import TestCase
from django import forms
from django.db import models

from ..fields import YoutubeField

class TestModel(models.Model):
    youtube = YoutubeField()

class TestModelForm(forms.ModelForm):
    class Meta:
        model = TestModel

class FormTest(TestCase):

    def test_validation(self):
        form = TestModelForm(data={'youtube': 'http://youtu.be/jRKrZ6X5WSw'})
        self.assertTrue(form.is_valid())

        invalid = TestModelForm(data={'youtube': 'http://yandex.ru'})
        self.assertFalse(invalid.is_valid())
        self.assertTrue('Invalid youtube url' in str(invalid.errors))

        invalid = TestModelForm(data={'youtube': 'http://youtu.be/'})
        self.assertFalse(invalid.is_valid())
        self.assertTrue('Youtube url has not video param' in str(invalid.errors))

class FieldTest(TestCase):

    def setUp(self):
        self.video_url = 'http://youtu.be/jRKrZ6X5WSw'
        self.field = YoutubeField()

    def test_to_python(self):
        self.res = self.field.to_python(self.video_url)
        self.assertEqual(u'http://youtu.be/jRKrZ6X5WSw', self.res)

    def test_video_id(self):
        self.assertEqual(u'jRKrZ6X5WSw',
                self.field.to_python(self.video_url).video_id)

    def test_embed_url(self):
        expected = u'http://youtube.com/embed/jRKrZ6X5WSw/'
        self.assertEqual(expected,
                self.field.to_python(self.video_url).embed_url)

    def test_images(self):
        default_image_url = 'http://img.youtube.com/vi/jRKrZ6X5WSw/0.jpg'
        thumb_url = 'http://img.youtube.com/vi/jRKrZ6X5WSw/1.jpg'

        self.assertEqual(default_image_url,
                self.field.to_python(self.video_url).default_image_url)

        self.assertEqual(thumb_url,
                self.field.to_python(self.video_url).thumb_url)


text:
<?php namespace Fields;

class MixedGroupCest extends BaseFieldTest
{
    public function i_can_update_field(\AcceptanceTester $I)
    {
        $I->clickNode('#group2-node');

    }
}


text:
import { Line } from 'vue-chartjs';

export default {
  extends: Line,
  props: ['options'],
  mounted () {
    // this.chartData is created in the mixin
    // this.renderChart(this.chartData, this.options);
  },
  methods: {
    doRender() {
      console.log(this.chartData);
      this.renderChart(this.chartData, this.options);
    },
  },
};


text:
package org.apache.beehive.netui.script.el.util;

import java.io.StringReader;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.util.HashMap;

import org.apache.beehive.netui.script.el.parser.NetUIELParser;
import org.apache.beehive.netui.script.el.NetUIVariableResolver;
import org.apache.beehive.netui.script.el.ParsedExpression;
import org.apache.beehive.netui.script.el.ExpressionParseException;
import org.apache.beehive.netui.script.el.parser.TokenMgrError;
import org.apache.beehive.netui.script.el.parser.ParseException;
import org.apache.beehive.netui.util.internal.InternalStringBuilder;
import org.apache.beehive.netui.util.internal.cache.PropertyCache;
import org.apache.beehive.netui.util.type.TypeUtils;
import org.apache.beehive.netui.util.logging.Logger;

/**
 *
 */
public final class ParseUtils {

    private static final Logger LOGGER = Logger.getInstance(ParseUtils.class);
    private static final HashMap/*<String, ParsedExpression>*/ PARSED_CACHE = new HashMap();

    /* do not construct */
    private ParseUtils() {
    }

    /**
     * Parse the givne String into a {@link ParsedExpression}.
     * @param expression the expression
     * @return the parsed expression
     */
    public static ParsedExpression parse(String expression) {
        ParsedExpression pe = (ParsedExpression)PARSED_CACHE.get(expression);

        if(pe != null)
            return pe;

        try {
            NetUIELParser learn = new NetUIELParser(new StringReader(expression));

            ParsedExpression expr = learn.parse();
            expr.seal();

            /* infrequent; this should only happen when there is a cache miss */
            synchronized(PARSED_CACHE) {
                PARSED_CACHE.put(expression, expr);
            }

            return expr;
        } catch(ParseException e) {
            String msg = "Error occurred parsing expression \"" + expression + "\".";
            LOGGER.error(msg, e);
            throw new ExpressionParseException(msg, e);
        } catch(TokenMgrError tm) {
            String msg = "Error occurred parsing expression \"" + expression + "\".";
            LOGGER.error(msg, tm);
            throw new ExpressionParseException(msg, tm);
        }
    }

    public static Object evaluate(String exprStr, NetUIVariableResolver vr) {
        ParsedExpression expr = parse(exprStr);
        assert expr != null;
        return expr.evaluate(vr);
    }

    public static void update(String exprStr, Object value, NetUIVariableResolver vr) {
        ParsedExpression expr = parse(exprStr);
        assert expr != null;
        expr.update(value, vr);
    }

    public static Class getPropertyType(Object value, String name, PropertyCache cache) {
        assert value != null;
        assert cache != null;

        Class type = value.getClass();

        Method m = cache.getPropertySetter(type, name);
        if(m == null) {
            String msg = "Can not find setter method for property \"" + name + "\" on object of type \"" + value.getClass() + "\".";
            LOGGER.error(msg);
            throw new RuntimeException(msg);
        }
        // PropertyCache guarantees that props are found and match JavaBean naming rules
        else {
            assert m.getParameterTypes().length == 1;
            return m.getParameterTypes()[0];
        }
    }

    public static Object getProperty(Object value, String name, PropertyCache cache) {
        assert value != null;
        assert cache != null;

        Class type = value.getClass();

        Method m = cache.getPropertyGetter(type, name);
        if(m != null) {
            try {
                return m.invoke(value, (Object[])null);
            } catch(Exception e) {
                String msg = "An error occurred invoking a getter for the property  \"" + name + "\" on an object of type \"" + type + "\".";
                LOGGER.error(msg, e);
                throw new RuntimeException(msg, e);
            }
        }

        String msg = "Could not find JavaBean property named \"" + name + "\" on object of type \"" + type + "\"";
        LOGGER.error(msg);
        throw new RuntimeException(msg);
    }

    public static final Object convertType(Object value, Class toType) {
        assert toType != null;

        try {
            boolean sourceIsArray = false;

            /* only convert String types; other Object types are already assumed to be in their target types. */
            if(value != null && !(value instanceof String || (sourceIsArray = (value instanceof String[]))))
                return value;

            /* for a String[], convert each item in the array into its target type and return the resulting array. */
            if(toType.isArray()) {
                if(value == null)
                    return null;
                else {
                    Class compType = toType.getComponentType();

                    String[] strs = null;
                    if(value.getClass().isArray())
                        strs = (String[])value;
                    else
                        strs = new String[]{(String)value};

                    Object tgt = Array.newInstance(compType, strs.length);

                    for(int i = 0; i < strs.length; i++) {
                        Object o = null;
                        try {
                            /* todo: support getting the Locale here in an ExpressionContext object */
                            o = TypeUtils.convertToObject(strs[i], compType);
                        } catch(IllegalArgumentException e) {
                            String msg = "Can not set Object types via expressions that are not supported by the set of registered type converters.  Cause: " + e;
                            LOGGER.error(msg, e);
                            throw new RuntimeException(msg, e);
                        }

                        Array.set(tgt, i, o);
                    }

                    return tgt;
                }
            }
            // convert the String into its target type and return the result
            else {
                // If the "value" is multi-valued (String[]), it needs to be converted into a single-valued object.
                // There is no policy defined for how we do this right now, so the first one will always win when
                // multiple expressions reference the same property.  When that property is a String type, the result
                // is an HttpServletRequest that contains a String[], and here, we'll always the String[0].
                if(sourceIsArray) {
                    assert value instanceof String[];
                    assert Array.getLength(value) > 0 && Array.getLength(value) - 1 >= 0;

                    value = Array.get(value, Array.getLength(value) - 1);
                }

                try {
                    assert value == null || value instanceof String;

                    return TypeUtils.convertToObject((String)value, toType);
                } catch(IllegalArgumentException e) {
                    String msg = "The type \"" + toType.getName() + "\" can not be set through the NetUI expression language.";
                    LOGGER.error(msg, e);
                    throw new RuntimeException(msg, e);
                }
            }
        } catch(Exception e) {
            String msg = "Unable to convert a value of type \"" + value.getClass() + "\" to the array element type of \"" + toType + "\".  Cause: " + e;
            LOGGER.error(msg, e);
            throw new RuntimeException(msg, e);
        }
    }

    public static String getContextString(String[] contexts) {
        InternalStringBuilder builder = new InternalStringBuilder();
        builder.append("[");
        if(contexts != null) {
            for(int i = 0; i < contexts.length; i++) {
                if(i > 0) builder.append(", ");
                builder.append(contexts[i]);
            }
        }
        builder.append("]");
        return builder.toString();
    }

    public static Throwable getRootCause(Throwable t) {
        Throwable root = t;
        while(root.getCause() != null)
            root = root.getCause();
        return root;
    }
}


text:
struct aiNode *nusm_find_node(struct aiNode *, char *);
NUS_result nusm_load_animation(NUS_animation *, struct aiAnimation *);

NUS_result nusm_load(char * file_path, NUS_binary_model *p_binary_model)
{
  const struct aiScene* scene;
  struct aiMesh *mesh;
  NUS_vertex *p_vertex;
  unsigned int i,
    j,
    k;
  float weight_normalization;
  scene = aiImportFile(file_path,
		       aiProcess_CalcTangentSpace       |
		       aiProcess_FlipWindingOrder       |
		       aiProcess_Triangulate            |
		       aiProcess_JoinIdenticalVertices  |
		       aiProcess_GenNormals	        |
		       aiProcess_FlipUVs 	        |
		       aiProcess_GenUVCoords	        |
		       aiProcess_SortByPType);
  if(scene == NULL){
    printf("NUSM_ERROR::failed to import file \"%s\"\n", file_path);
    return NUS_FAILURE;
  }
  mesh = scene->mMeshes[0];

  p_binary_model->vertex_count = mesh->mNumVertices;
  p_binary_model->index_count = mesh->mNumFaces * 3;

  printf("Vertices\n");

  printf("\tCount: %d\n", p_binary_model->vertex_count);
  p_binary_model->vertices = malloc(p_binary_model->vertex_count *
				    sizeof(*p_binary_model->vertices));
  memset(p_binary_model->vertices, 0,
	 p_binary_model->vertex_count * sizeof(*p_binary_model->vertices));

  for(i = 0; i < p_binary_model->vertex_count; ++i){
    // Strores vertex position data
    p_binary_model->vertices[i].position[0] = mesh->mVertices[i].x;
    p_binary_model->vertices[i].position[1] = mesh->mVertices[i].y;
    p_binary_model->vertices[i].position[2] = mesh->mVertices[i].z;

    // Stores vertex normal data
    p_binary_model->vertices[i].normal[0] = mesh->mNormals[i].x;
    p_binary_model->vertices[i].normal[1] = mesh->mNormals[i].y;
    p_binary_model->vertices[i].normal[2] = mesh->mNormals[i].z;

    // Zero out the rest of the vertex data
    p_binary_model->vertices[i].tex_coords[0] = 0.0;
    p_binary_model->vertices[i].tex_coords[1] = 0.0;
    p_binary_model->vertices[i].bone_weights[0] = 0.0;
    p_binary_model->vertices[i].bone_weights[1] = 0.0;
    p_binary_model->vertices[i].bone_weights[2] = 0.0;
    p_binary_model->vertices[i].bone_weights[3] = 0.0;
    p_binary_model->vertices[i].bone_indices[0] = 0;
    p_binary_model->vertices[i].bone_indices[1] = 0;
    p_binary_model->vertices[i].bone_indices[2] = 0;
    p_binary_model->vertices[i].bone_indices[3] = 0;
  }

  printf("Indices\n");
  printf("\tCount: %d\n", p_binary_model->index_count);
  p_binary_model->indices = malloc(p_binary_model->index_count *
				   sizeof(*p_binary_model->indices));
  // Store index data
  for(i = 0; i < mesh->mNumFaces; ++i){
    p_binary_model->indices[(3 * i)] = mesh->mFaces[i].mIndices[0];
    p_binary_model->indices[(3 * i) + 1] = mesh->mFaces[i].mIndices[1];
    p_binary_model->indices[(3 * i) + 2] = mesh->mFaces[i].mIndices[2];
  }

  if(mesh->mTextureCoords[0]){
    printf("Texture\n");

    for(i = 0; i < p_binary_model->vertex_count; ++i){
      // Stores vertex texture coord data
      p_binary_model->vertices[i].tex_coords[0] = mesh->mTextureCoords[0][i].x;
      p_binary_model->vertices[i].tex_coords[1] = mesh->mTextureCoords[0][i].y;
    }

    // Load texture file path
    struct aiString texture_path;
    aiGetMaterialString(scene->mMaterials[mesh->mMaterialIndex],
			AI_MATKEY_TEXTURE(aiTextureType_DIFFUSE, 0), &texture_path);
    printf("\tFile Name: %s\n", texture_path.data);

    // Load texture
    int texture_channels;

    void *data = stbi_load(texture_path.data, (int*)&p_binary_model->texture_width,
			   (int*)&p_binary_model->texture_height,
			   &texture_channels, STBI_rgb_alpha);
    if(data == NULL) {
      NUS_LOG_ERROR("texturing supported, but texture data not found\n");
      return NUS_FAILURE;
    }
    p_binary_model->texture_data_size = p_binary_model->texture_width *
      p_binary_model->texture_height * texture_channels;

    printf("\tWidth: %d\n\tHeight: %d\n\tChannel Count: %d\n\tSize: %d\n",
	   p_binary_model->texture_width, p_binary_model->texture_height,
	   texture_channels, p_binary_model->texture_data_size);

    p_binary_model->texture_data = malloc(p_binary_model->texture_data_size);
    memcpy(p_binary_model->texture_data, data, p_binary_model->texture_data_size);
    free(data);
  } else {
    p_binary_model->texture_data_size = 0;
    NUS_LOG_WARNING("model has no texture\n");
  }

  printf("Skeleton\n");
  p_binary_model->skeleton.joint_count = 0;
  p_binary_model->animation_count = 0;
  if(mesh->mNumBones){
    printf("\tBone Count: %d\n", mesh->mNumBones);
    p_binary_model->skeleton.joint_count = mesh->mNumBones;
    p_binary_model->skeleton.joints = malloc(sizeof(*p_binary_model->skeleton.joints) *
					     mesh->mNumBones);
    memset(p_binary_model->skeleton.joints, 0,
	   sizeof(*p_binary_model->skeleton.joints) * mesh->mNumBones);

    for(i = 0; i < mesh->mNumBones; ++i){
      // For each bone
      printf("\tBone %d\n", i);
      printf("\t\tName: %s\n", mesh->mBones[i]->mName.data);
      printf("\t\tCount of affected vertices: %d\n", mesh->mBones[i]->mNumWeights);

      // Record skeleton data
      memcpy(&p_binary_model->skeleton.joints[i].inv_bind_pose,
	     &mesh->mBones[i]->mOffsetMatrix, sizeof(mesh->mBones[i]->mOffsetMatrix));
      nus_matrix_print(p_binary_model->skeleton.joints[i].inv_bind_pose);

      char parent_name[100];
      strcpy(parent_name,
	     nusm_find_node(scene->mRootNode,
			    mesh->mBones[i]->mName.data)->mParent->mName.data);
      printf("\t\tParent bone name: %s\n", parent_name);

      p_binary_model->skeleton.joints[i].parent_index = -1;
      for(j = 0; j < mesh->mNumBones; ++j){
	if(strcmp(parent_name, mesh->mBones[j]->mName.data) == 0){
	  p_binary_model->skeleton.joints[i].parent_index = j;
	  break;
	}
      }
      printf("\t\tParent index: %d\n", p_binary_model->skeleton.joints[i].parent_index);

      memset(p_binary_model->skeleton.joints[i].name, 0,
	     sizeof(p_binary_model->skeleton.joints[i].name));
      strcpy(p_binary_model->skeleton.joints[i].name, mesh->mBones[i]->mName.data);

      int lowest_weight_i = 0;
      for(j = 0; j < mesh->mBones[i]->mNumWeights; ++j){
	// For each vertex affected by this bone
	p_vertex = p_binary_model->vertices + mesh->mBones[i]->mWeights[j].mVertexId;
	for(k = 1; k < 4; ++k){
	  // For each weight of the current vertex
	  if(p_vertex->bone_weights[k] < p_vertex->bone_weights[lowest_weight_i]){
	    // If k is the index of the lowest weight so far
	    lowest_weight_i = k;
	  }
	}
	if(mesh->mBones[i]->mWeights[j].mWeight >
	   p_vertex->bone_weights[lowest_weight_i]){
	  // If the bone's weight is greater than the vertexes lowest weight
	  p_vertex->bone_weights[lowest_weight_i] = mesh->mBones[i]->mWeights[j].mWeight;
	  p_vertex->bone_indices[lowest_weight_i] = i;
	}
      }
    }
    // Normalize bone weights
    for(i = 0; i < p_binary_model->vertex_count; ++i){
      // For each vertex

      // Zero out the rest of the vertex data
      weight_normalization = p_binary_model->vertices[i].bone_weights[0] +
	p_binary_model->vertices[i].bone_weights[1] +
	p_binary_model->vertices[i].bone_weights[2] +
	p_binary_model->vertices[i].bone_weights[3];
      if(weight_normalization < 0.0000001 &&
	 weight_normalization > -0.0000001){
	p_binary_model->vertices[i].bone_weights[0] = 1.0;
	p_binary_model->vertices[i].bone_indices[0] = 0;
      } else {
	p_binary_model->vertices[i].bone_weights[0] /= weight_normalization;
	p_binary_model->vertices[i].bone_weights[1] /= weight_normalization;
	p_binary_model->vertices[i].bone_weights[2] /= weight_normalization;
	p_binary_model->vertices[i].bone_weights[3] /= weight_normalization;
      }
    }

    if(scene->mAnimations){
      printf("Animations\n");
      printf("\tCount: %d\n", scene->mNumAnimations);
      p_binary_model->animation_count = scene->mNumAnimations;
      p_binary_model->animations = malloc(sizeof(*p_binary_model->animations) *
					    scene->mNumAnimations);
      for(i = 0; i < scene->mNumAnimations; ++i){
	printf("\tAnimation %d\n", i);
	if(nusm_load_animation(p_binary_model->animations + i,
			       scene->mAnimations[i]) != NUS_SUCCESS){
	  printf("NUSM_ERROR::failed to load animation %d\n", i);
	  return NUS_FAILURE;
	}
	  //
      }
    } else{
      printf("\nNUSM_WARNING::mesh has no animations\n\n");
    }
  } else{
    printf("\nNUSM_WARNING::mesh has no skeleton\n\n");
  }

  return NUS_SUCCESS;
}

struct aiNode *nusm_find_node(struct aiNode *node, char *node_name)
{
  struct aiNode *result;
  int i;
  for(i = 0; i < node->mNumChildren; ++i){
    if(strcmp(node_name, node->mChildren[i]->mName.data) == 0){
      return node->mChildren[i];
    }
  }
  for(i = 0; i < node->mNumChildren; ++i){
    if((result = nusm_find_node(node->mChildren[i], node_name)) != NULL){
      return result;
    }
  }
  return NULL;
}
NUS_result nusm_load_animation
(NUS_animation *p_animation, struct aiAnimation *p_ai_animation)
{
  float t;
  int frame_count,
    pre_index,
    post_index,
    i,
    j,
    k;
  struct aiNodeAnim *p_channel;

  char frame_exist_tracker[(int)p_ai_animation->mDuration + 1];
  memset(frame_exist_tracker, 0, sizeof(frame_exist_tracker));

  printf("\t\tFull Name: %s\n", p_ai_animation->mName.data);
  // Name skips the "Armature|" that is seen at the beginning of the full name

  if(strlen(p_ai_animation->mName.data) - 9 > NUS_ANIMATION_NAME_SIZE){
    NUS_LOG_ERROR("animation name is too long\n");
    return NUS_FAILURE;
  }
  strcpy(p_animation->name, p_ai_animation->mName.data + 9);
  printf("\t\tName: %s\n", p_animation->name);
  p_animation->duration = p_ai_animation->mDuration / p_ai_animation->mTicksPerSecond;
  printf("\t\tDuration: %f seconds\n", p_animation->duration);
  printf("\t\tChannel Count: %d\n", p_ai_animation->mNumChannels);
  frame_count = 0;
  for(i = 0; i < p_ai_animation->mNumChannels; ++i){
    // For each bone
    p_channel = p_ai_animation->mChannels[i];
    printf("\t\t\tChannel: %s\n", p_channel->mNodeName.data);
    if(p_channel->mNumPositionKeys != p_channel->mNumRotationKeys ||
       p_channel->mNumRotationKeys != p_channel->mNumScalingKeys){
      printf("NUSM_ERROR::position, rotation, and scaling key counts differ\n");
      return NUS_FAILURE;
    }
    for(j = 0; j < p_channel->mNumRotationKeys; ++j){
      // For each frame
      if(frame_exist_tracker[(int)p_channel->mRotationKeys[j].mTime] == 0){
	frame_exist_tracker[(int)p_channel->mRotationKeys[j].mTime] = 1;
	++frame_count;
      }
    }
  }

  printf("\t\tFrame Count: %d\n", frame_count);
  p_animation->frame_count = frame_count;
  p_animation->keyframes = malloc(sizeof(*p_animation->keyframes) *
				  (p_ai_animation->mNumChannels - 1) * frame_count);
  p_animation->times = malloc(sizeof(*p_animation->times) * frame_count);

  frame_count = 0;

  for(i = 0; i <= (int)p_ai_animation->mDuration ; ++i){
    // For each tick

    if(frame_exist_tracker[i] == 0){
      // If i is not the tick-time of a frame
      continue;
    }
    // Time in [0, 1] of animation duration
    p_animation->times[frame_count] = (float)i / p_ai_animation->mDuration;
    p_animation->keyframes[frame_count].joints =
      malloc(sizeof(*p_animation->keyframes[frame_count].joints) *
	     (p_ai_animation->mNumChannels - 1));

    for(j = 0; j < p_ai_animation->mNumChannels - 1; ++j){
      // For each bone
      p_channel = p_ai_animation->mChannels[j + 1];
      pre_index = 0;
      post_index = 0;

      // Find the pre/post times for rot, trans, and scale
      for(k = 1; k < p_channel->mNumRotationKeys; ++k){
	if(p_channel->mRotationKeys[k].mTime >= i){
	  post_index = k;
	  pre_index = post_index - 1;
	  break;
	}
      }
      t = (float)(i - p_channel->mRotationKeys[pre_index].mTime) /
	(p_channel->mRotationKeys[post_index].mTime -
	 p_channel->mRotationKeys[pre_index].mTime);

      p_animation->keyframes[frame_count].joints[j] =
	(NUS_keyframe_joint){
	.rotation = {
	  .w = t * p_channel->mRotationKeys[pre_index].mValue.w +
	  (1 - t) * p_channel->mRotationKeys[post_index].mValue.w,
	  .x = t * p_channel->mRotationKeys[pre_index].mValue.x +
	  (1 - t) * p_channel->mRotationKeys[post_index].mValue.x,
	  .y = t * p_channel->mRotationKeys[pre_index].mValue.y +
	  (1 - t) * p_channel->mRotationKeys[post_index].mValue.y,
	  .z = t * p_channel->mRotationKeys[pre_index].mValue.z +
	  (1 - t) * p_channel->mRotationKeys[post_index].mValue.z
	},
	.translation = {
	  .x = t * p_channel->mPositionKeys[pre_index].mValue.x +
	  (1 - t) * p_channel->mPositionKeys[post_index].mValue.x,
	  .y = t * p_channel->mPositionKeys[pre_index].mValue.y +
	  (1 - t) * p_channel->mPositionKeys[post_index].mValue.y,
	  .z = t * p_channel->mPositionKeys[pre_index].mValue.z +
	  (1 - t) * p_channel->mPositionKeys[post_index].mValue.z
	},
	.scale = {
	  .x = t * p_channel->mScalingKeys[pre_index].mValue.x +
	  (1 - t) * p_channel->mScalingKeys[post_index].mValue.x,
	  .y = t * p_channel->mScalingKeys[pre_index].mValue.y +
	  (1 - t) * p_channel->mScalingKeys[post_index].mValue.y,
	  .z = t * p_channel->mScalingKeys[pre_index].mValue.z +
	  (1 - t) * p_channel->mScalingKeys[post_index].mValue.z
	}
      };
    }
    ++frame_count;
  }

  return NUS_SUCCESS;
}


text:
namespace {

class MessageSender : public content::NotificationObserver {
 public:
  MessageSender() {
    registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_HOST_DID_STOP_LOADING,
                   content::NotificationService::AllSources());
  }

 private:
  virtual void Observe(int type,
                       const content::NotificationSource& source,
                       const content::NotificationDetails& details) {
    ExtensionEventRouter* event_router =
        content::Source<Profile>(source).ptr()->GetExtensionEventRouter();

    // Sends four messages to the extension. All but the third message sent
    // from the origin http://b.com/ are supposed to arrive.
    event_router->DispatchEventToRenderers("test.onMessage",
        "[{\"lastMessage\":false,\"data\":\"no restriction\"}]",
        content::Source<Profile>(source).ptr(),
        GURL(),
        EventFilteringInfo());
    event_router->DispatchEventToRenderers("test.onMessage",
        "[{\"lastMessage\":false,\"data\":\"http://a.com/\"}]",
        content::Source<Profile>(source).ptr(),
        GURL("http://a.com/"),
        EventFilteringInfo());
    event_router->DispatchEventToRenderers("test.onMessage",
        "[{\"lastMessage\":false,\"data\":\"http://b.com/\"}]",
        content::Source<Profile>(source).ptr(),
        GURL("http://b.com/"),
        EventFilteringInfo());
    event_router->DispatchEventToRenderers("test.onMessage",
        "[{\"lastMessage\":true,\"data\":\"last message\"}]",
        content::Source<Profile>(source).ptr(),
        GURL(),
        EventFilteringInfo());
  }

  content::NotificationRegistrar registrar_;
};

}  // namespace

// Tests that message passing between extensions and content scripts works.
// Flaky on the trybots. See http://crbug.com/96725.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Messaging) {
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionTest("messaging/connect")) << message_;
}

// Tests that message passing from one extension to another works.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MessagingExternal) {
  ASSERT_TRUE(LoadExtension(
      test_data_dir_.AppendASCII("..").AppendASCII("good")
                    .AppendASCII("Extensions")
                    .AppendASCII("bjafgdebaacbbbecmhlhpofkepfkgcpa")
                    .AppendASCII("1.0")));

  ASSERT_TRUE(RunExtensionTest("messaging/connect_external")) << message_;
}

// Tests that messages with event_urls are only passed to extensions with
// appropriate permissions.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MessagingEventURL) {
  MessageSender sender;
  ASSERT_TRUE(RunExtensionTest("messaging/event_url")) << message_;
}


text:
package controllers

import (
	// "encoding/json"
	"github.com/3xxx/engineercms/controllers/utils"
	"github.com/3xxx/engineercms/models"
	"github.com/astaxie/beego"
	// "sort"
	"strconv"
	// "strings"
	// "time"
)

type LocationController struct {
	beego.Controller
}

// type wxuser struct {
// 	Name string `json:"name"`
// }

// @Title post location by projectid
// @Description post location by projectid
// @Param title query string  true "The title of locationpart"
// @Param describe query string  true "The describe of locationpart"
// @Param sort query string  true "The sort of locationpart"
// @Param userid query string true "The userid of location"
// @Param id path string true "The projectid of project"
// @Success 200 {object} models.CreateLocation
// @Failure 400 Invalid page supplied
// @Failure 404 pas not found
// @router /addlocationpart/:id [post]
// 添加一个定位组
func (c *LocationController) AddLocationPart() {
	//content去验证
	app_version := c.Input().Get("app_version")
	accessToken, _, _, err := utils.GetAccessToken(app_version)
	if err != nil {
		beego.Error(err)
		c.Data["json"] = map[string]interface{}{"info": "ERROR", "data": err}
		c.ServeJSON()
	}
	var user models.User
	// var err error
	openID := c.GetSession("openID")
	if openID != nil {
		user, err = models.GetUserByOpenID(openID.(string))
		if err != nil {
			beego.Error(err)
		}
	} else {
		c.Data["json"] = map[string]interface{}{"info": "用户未登录", "id": 0}
		c.ServeJSON()
		return
		// user.Id = 9
	}

	pid := c.Ctx.Input.Param(":id")
	//id转成64为
	projectid, err := strconv.ParseInt(pid, 10, 64)
	if err != nil {
		beego.Error(err)
	}

	title := c.Input().Get("title")
	describe := c.Input().Get("describe")
	sort := c.Input().Get("sort")
	sortint, err := strconv.Atoi(sort)
	if err != nil {
		beego.Error(err)
	}
	// 进行敏感字符验证
	content := title + describe
	// errcode, errmsg, err := utils.MsgSecCheck(accessToken, content)
	errcode, errmsg, err := utils.MsgSecCheck(2, 2, accessToken, openID.(string), content)
	if err != nil {
		beego.Error(err)
		c.Data["json"] = map[string]interface{}{"info": "ERROR", "data": err}
		c.ServeJSON()
	} else if errcode != 87014 {
		//根据项目id添加定位组
		var location models.Location
		// 添加location
		location = models.Location{
			ProjectID: projectid,
			UserID:    user.Id,
			Title:     title,
			Describe:  describe,
			Sort:      sortint,
		}
		Id, err := models.CreateLocation(location)

		if err != nil {
			beego.Error(err)
			c.Data["json"] = map[string]interface{}{"data": "WRONG", "info": "添加定位组数据错误"}
			c.ServeJSON()
		} else if Id != 0 {
			c.Data["json"] = map[string]interface{}{"data": "OK", "info": "SUCCESS", "id": Id}
			c.ServeJSON()
		} else {
			c.Data["json"] = map[string]interface{}{"data": "data already exist", "info": "数据已存在"}
			c.ServeJSON()
		}
	} else {
		c.Data["json"] = map[string]interface{}{"info": "ERROR", "data": errmsg}
		c.ServeJSON()
	}
}

// @Title post locationnavigate by locationid
// @Description post locationnavigate by locationid
// @Param title query string true "The title of location"
// @Param label query string true "The label of locationnavigate"
// @Param location query string true "The location of location"
// @Param address query string false "The address of location"
// @Param lat query string false "The lat of location"
// @Param lng query string false "The lng of location"
// @Param id path string true "The locationid of location"
// @Success 200 {object} models.CreateLocation
// @Failure 400 Invalid page supplied
// @Failure 404 pas not found
// @router /addlocationnavigate/:id [post]
// 添加一个定位
func (c *LocationController) AddLocationNavigate() {
	//content去验证
	app_version := c.Input().Get("app_version")
	accessToken, _, _, err := utils.GetAccessToken(app_version)
	if err != nil {
		beego.Error(err)
		c.Data["json"] = map[string]interface{}{"info": "ERROR", "data": err}
		c.ServeJSON()
	}
	// var err error
	openID := c.GetSession("openID")
	if openID != nil {
		_, err := models.GetUserByOpenID(openID.(string))
		if err != nil {
			beego.Error(err)
		}
	} else {
		c.Data["json"] = map[string]interface{}{"info": "用户未登录", "id": 0}
		c.ServeJSON()
		return
		// user.Id = 9
	}

	locid := c.Ctx.Input.Param(":id")
	//id转成uint
	locidint, err := strconv.Atoi(locid)
	if err != nil {
		beego.Error(err)
	}
	locationid := uint(locidint)

	title := c.Input().Get("title")
	label := c.Input().Get("label")
	location := c.Input().Get("location")
	address := c.Input().Get("address")
	sort := c.Input().Get("sort")
	var sortint int
	if sort != "" {
		sortint, err = strconv.Atoi(sort)
		if err != nil {
			beego.Error(err)
		}
	}
	lat := c.Input().Get("lat")
	latfloat, err := strconv.ParseFloat(lat, 64)
	if err != nil {
		beego.Error(err)
	}
	lng := c.Input().Get("lng")
	lngfloat, err := strconv.ParseFloat(lng, 64)
	if err != nil {
		beego.Error(err)
	}

	// 进行敏感字符验证
	content := address
	// errcode, errmsg, err := utils.MsgSecCheck(accessToken, content)
	errcode, errmsg, err := utils.MsgSecCheck(2, 2, accessToken, openID.(string), content)
	if err != nil {
		beego.Error(err)
		c.Data["json"] = map[string]interface{}{"info": "ERROR", "data": err}
		c.ServeJSON()
	} else if errcode != 87014 {
		//根据项目id添加出差
		// var locationnavigate models.LocationNavigate
		// 添加location
		locationnavigate := models.LocationNavigate{
			LocationID: locationid,
			Title:      title,
			Label:      label,
			Location:   location,
			Address:    address,
			Lat:        latfloat,
			Lng:        lngfloat,
			Sort:       sortint,
		}
		Id, err := models.CreateLocationNavigate(locationnavigate)
		// beego.Info(Id)
		// beego.Info(err)
		if err != nil {
			beego.Error(err)
			c.Data["json"] = map[string]interface{}{"data": "WRONG", "info": "添加出差数据错误"}
			c.ServeJSON()
		} else if Id != 0 {
			c.Data["json"] = map[string]interface{}{"data": "OK", "info": "SUCCESS", "id": Id}
			c.ServeJSON()
		} else {
			c.Data["json"] = map[string]interface{}{"data": "data already exist", "info": "数据已存在"}
			c.ServeJSON()
		}
	} else {
		c.Data["json"] = map[string]interface{}{"info": "ERROR", "data": errmsg}
		c.ServeJSON()
	}
}

// @Title get location by userid
// @Description get location by userid
// @Param id path string true "The projectid of location"
// @Success 200 {object} models.GetLocationPage
// @Failure 400 Invalid page supplied
// @Failure 404 location not found
// @router /getlocation/:id [get]
// 根据项目id列出有关的location
func (c *LocationController) GetLocation() {
	pid := c.Ctx.Input.Param(":id")
	//id转成64为
	projectid, err := strconv.ParseInt(pid, 10, 64)
	if err != nil {
		beego.Error(err)
	}
	// beego.Info(projectid)
	// projectid = 25001
	//查出未过期的与本人有关的出差活动
	location, err := models.GetAllLocation(projectid)
	if err != nil {
		beego.Error(err)
	}
	c.Data["json"] = location //map[string]interface{}{"userId": 1, "avatorUrl": "Filename"}
	c.ServeJSON()
}

// @Title get location by locationid
// @Description get location by locationid
// @Param id path string true "The id of location"
// @Success 200 {object} models.GetLocationPage
// @Failure 400 Invalid page supplied
// @Failure 404 location not found
// @router /getlocationbyid/:id [get]
// 根据locationid查出location
func (c *LocationController) GetLocationById() {
	var err error
	openID := c.GetSession("openID")
	if openID == nil {
		// c.Data["json"] = map[string]interface{}{"info": "用户未登录", "id": 0}
		// c.ServeJSON()
		// return
		// user.Id = 9
	}

	bid := c.Ctx.Input.Param(":id")
	//id转成64为
	locationid, err := strconv.ParseInt(bid, 10, 64)
	if err != nil {
		beego.Error(err)
	}
	//查出出差活动
	location, err := models.GetLocationById(locationid)
	if err != nil {
		beego.Error(err)
	}

	c.Data["json"] = location //map[string]interface{}{"userId": 1, "avatorUrl": "Filename"}
	c.ServeJSON()
}


text:
import os, subprocess, time
import pyven.constants

from pyven.plugins.plugin_api.process import Process

from pyven.logging.logger import Logger

class Command(Process):

    def __init__(self, cwd, name, command, directory):
        super(Command, self).__init__(cwd, name)
        self.duration = 0
        self.type = 'command'
        self.command = command
        self.directory = directory
        if self.directory != '.':
            self.cwd = os.path.join(self.cwd, self.directory)

    @Process.error_checks
    def process(self, verbose=False, warning_as_error=False):
        Logger.get().info('Command : ' + self.type + ':' + self.name)
        if not os.path.isdir(self.directory):
            os.makedirs(self.directory)
        Logger.get().info('Entering directory : ' + self.directory)
        self.duration, out, err, returncode = self._call_command(self._format_call())
        Logger.get().info('Leaving directory : ' + self.directory)

        if verbose:
            for line in out:
                Logger.get().info('[' + self.type + ']' + line)
            for line in err:
                Logger.get().info('[' + self.type + ']' + line)

        if returncode != 0:
            self.status = pyven.constants.STATUS[1]
            self.errors.extend([out + err])
            Logger.get().error('Command failed : ' + self.type + ':' + self.name)
        else:
            self.status = pyven.constants.STATUS[0]
        return returncode == 0

    @Process.error_checks
    def clean(self, verbose=False, warning_as_error=False):
        self.status = pyven.constants.STATUS[0]
        return True

    def report_summary(self):
        return self.report_title()

    def report_title(self):
        return self.name

    def report_properties(self):
        properties = []
        properties.append(('Command', self.command))
        properties.append(('Workspace', self.directory))
        properties.append(('Duration', str(self.duration) + ' seconds'))
        return properties

    def _call_command(self, command):
        tic = time.time()
        out = ''
        err = ''
        try:
            try:
                sp = subprocess.Popen(command,\
                                      stdin=subprocess.PIPE,\
                                      stdout=subprocess.PIPE,\
                                      stderr=subprocess.PIPE,\
                                      universal_newlines=True,\
                                      cwd=self.cwd,\
                                      shell=pyven.constants.PLATFORM == pyven.constants.PLATFORMS[1])
                out, err = sp.communicate(input='\n')
                out = out.splitlines()
                err = err.splitlines()
                returncode = sp.returncode
            except UnicodeDecodeError as e:
                sp = subprocess.Popen(command,\
                                      stdin=subprocess.PIPE,\
                                      stdout=subprocess.PIPE,\
                                      stderr=subprocess.PIPE,\
                                      cwd=self.cwd,\
                                      shell=pyven.constants.PLATFORM == pyven.constants.PLATFORMS[1])
                out, err = sp.communicate()
                out = out.decode("cp1252").split('\n')
                err = err.decode("cp1252").split('\n')
                returncode = sp.returncode
        except FileNotFoundError as e:
            returncode = 1
            self.errors.append(['Unknown command'])
        toc = time.time()
        return round(toc - tic, 3), out, err, returncode

    def _format_call(self):
        call = self.command.split(' ')
        Logger.get().info(self.command)
        return call


text:
/*
 * Copyright 2015 Gonzalo Peci  All rights reserved.  Licensed under the Apache v2 License.
 */

package vmwareworkstation

import (
	"bytes"
	"errors"
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"syscall"
	"unsafe"

	"github.com/docker/machine/libmachine/log"
)

var (
	vmrunbin    = setVmwareCmd("vmrun.exe")
	vdiskmanbin = setVmwareCmd("vmware-vdiskmanager.exe")
)

var (
	ErrMachineExist    = errors.New("machine already exists")
	ErrMachineNotExist = errors.New("machine does not exist")
	ErrVMRUNNotFound   = errors.New("VMRUN not found")
)

// This reads the VMware installation path from the Windows registry.
func workstationVMwareRoot() (s string, err error) {
	key := `SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\vmware.exe`
	subkey := "Path"
	s, err = readRegString(syscall.HKEY_LOCAL_MACHINE, key, subkey)
	if err != nil {
		log.Errorf(`Unable to read registry key %s\%s`, key, subkey)
		return
	}

	return normalizePath(s), nil
}

// This reads the VMware DHCP leases path from the Windows registry.
func workstationDhcpLeasesPathRegistry() (s string, err error) {
	key := `SYSTEM\CurrentControlSet\services\VMnetDHCP\Parameters`
	subkey := "LeaseFile"
	s, err = readRegString(syscall.HKEY_LOCAL_MACHINE, key, subkey)
	if err != nil {
		log.Errorf(`Unable to read registry key %s\%s`, key, subkey)
		return
	}

	return normalizePath(s), nil
}

func workstationDhcpLeasesPath() string {
	path, err := workstationDhcpLeasesPathRegistry()
	if err != nil {
		log.Errorf("Error finding leases in registry: %s", err)
	} else if _, err := os.Stat(path); err == nil {
		return path
	}

	return findFile("vmnetdhcp.leases", workstationDataFilePaths())
}

// workstationProgramFilesPaths returns a list of paths that are eligible
// to contain program files we may want just as vmware.exe.
func workstationProgramFilePaths() []string {
	path, err := workstationVMwareRoot()
	if err != nil {
		log.Errorf("Error finding VMware root: %s", err)
	}

	paths := make([]string, 0, 5)
	if os.Getenv("VMWARE_HOME") != "" {
		paths = append(paths, os.Getenv("VMWARE_HOME"))
	}

	if path != "" {
		paths = append(paths, path)
	}

	if os.Getenv("ProgramFiles(x86)") != "" {
		paths = append(paths,
			filepath.Join(os.Getenv("ProgramFiles(x86)"), "/VMware/VMware Workstation"))
	}

	if os.Getenv("ProgramFiles") != "" {
		paths = append(paths,
			filepath.Join(os.Getenv("ProgramFiles"), "/VMware/VMware Workstation"))
	}

	return paths
}

// workstationDataFilePaths returns a list of paths that are eligible
// to contain data files we may want such as vmnet NAT configuration files.
func workstationDataFilePaths() []string {
	leasesPath, err := workstationDhcpLeasesPathRegistry()
	if err != nil {
		log.Errorf("Error getting DHCP leases path: %s", err)
	}

	if leasesPath != "" {
		leasesPath = filepath.Dir(leasesPath)
	}

	paths := make([]string, 0, 5)
	if os.Getenv("VMWARE_DATA") != "" {
		paths = append(paths, os.Getenv("VMWARE_DATA"))
	}

	if leasesPath != "" {
		paths = append(paths, leasesPath)
	}

	if os.Getenv("ProgramData") != "" {
		paths = append(paths,
			filepath.Join(os.Getenv("ProgramData"), "/VMware"))
	}

	if os.Getenv("ALLUSERSPROFILE") != "" {
		paths = append(paths,
			filepath.Join(os.Getenv("ALLUSERSPROFILE"), "/Application Data/VMware"))
	}

	return paths
}

// detect the vmrun and vmware-vdiskmanager cmds' path if needed
func setVmwareCmd(cmd string) string {
	if path, err := exec.LookPath(cmd); err == nil {
		return path
	}
	return findFile(cmd, workstationProgramFilePaths())
}

func vmrun(args ...string) (string, string, error) {
	cmd := exec.Command(vmrunbin, args...)
	if os.Getenv("MACHINE_DEBUG") != "" {
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
	}

	var stdout bytes.Buffer
	var stderr bytes.Buffer
	cmd.Stdout, cmd.Stderr = &stdout, &stderr
	log.Debugf("executing: %v %v", vmrunbin, strings.Join(args, " "))

	err := cmd.Run()
	if err != nil {
		if ee, ok := err.(*exec.Error); ok && ee == exec.ErrNotFound {
			err = ErrVMRUNNotFound
		}
	}

	return stdout.String(), stderr.String(), err
}

// Make a vmdk disk image with the given size (in MB).
func vdiskmanager(dest string, size int) error {
	cmd := exec.Command(vdiskmanbin, "-c", "-t", "0", "-s", fmt.Sprintf("%dMB", size), "-a", "lsilogic", dest)
	if os.Getenv("MACHINE_DEBUG") != "" {
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
	}

	if stdout := cmd.Run(); stdout != nil {
		if ee, ok := stdout.(*exec.Error); ok && ee == exec.ErrNotFound {
			return ErrVMRUNNotFound
		}
	}
	return nil
}

func normalizePath(path string) string {
	path = strings.Replace(path, "\\", "/", -1)
	path = strings.Replace(path, "//", "/", -1)
	path = strings.TrimRight(path, "/")
	return path
}

func findFile(file string, paths []string) string {
	for _, path := range paths {
		path = filepath.Join(path, file)
		path = normalizePath(path)
		log.Debugf("Searching for file '%s'", path)

		if _, err := os.Stat(path); err == nil {
			log.Debugf("Found file '%s'", path)
			return path
		}
	}

	log.Errorf("File not found: '%s'", file)
	return ""
}

// See http://blog.natefinch.com/2012/11/go-win-stuff.html
//
func readRegString(hive syscall.Handle, subKeyPath, valueName string) (value string, err error) {
	var h syscall.Handle
	err = syscall.RegOpenKeyEx(hive, syscall.StringToUTF16Ptr(subKeyPath), 0, syscall.KEY_READ, &h)
	if err != nil {
		return
	}
	defer syscall.RegCloseKey(h)

	var typ uint32
	var bufSize uint32
	err = syscall.RegQueryValueEx(
		h,
		syscall.StringToUTF16Ptr(valueName),
		nil,
		&typ,
		nil,
		&bufSize)
	if err != nil {
		return
	}

	data := make([]uint16, bufSize/2+1)
	err = syscall.RegQueryValueEx(
		h,
		syscall.StringToUTF16Ptr(valueName),
		nil,
		&typ,
		(*byte)(unsafe.Pointer(&data[0])),
		&bufSize)
	if err != nil {
		return
	}

	return syscall.UTF16ToString(data), nil
}


text:
;(function ( $, window, document, undefined ) {

"use strict";

$.fn.progress = function(parameters) {
  var
    $allModules    = $(this),

    moduleSelector = $allModules.selector || '',

    time           = new Date().getTime(),
    performance    = [],

    query          = arguments[0],
    methodInvoked  = (typeof query == 'string'),
    queryArguments = [].slice.call(arguments, 1),

    returnedValue
  ;

  $allModules
    .each(function() {
      var
        settings          = ( $.isPlainObject(parameters) )
          ? $.extend(true, {}, $.fn.progress.settings, parameters)
          : $.extend({}, $.fn.progress.settings),

        className       = settings.className,
        metadata        = settings.metadata,
        namespace       = settings.namespace,
        selector        = settings.selector,
        error           = settings.error,

        eventNamespace  = '.' + namespace,
        moduleNamespace = 'module-' + namespace,

        $module         = $(this),
        $bar            = $(this).find(selector.bar),
        $progress       = $(this).find(selector.progress),
        $label          = $(this).find(selector.label),

        element         = this,
        instance        = $module.data(moduleNamespace),

        animating = false,
        transitionEnd,
        module
      ;

      module = {

        initialize: function() {
          module.debug('Initializing progress bar', settings);

          transitionEnd = module.get.transitionEnd();

          module.read.metadata();
          module.set.duration();
          module.set.initials();
          module.instantiate();
        },

        instantiate: function() {
          module.verbose('Storing instance of progress', module);
          instance = module;
          $module
            .data(moduleNamespace, module)
          ;
        },
        destroy: function() {
          module.verbose('Destroying previous progress for', $module);
          clearInterval(instance.interval);
          module.remove.state();
          $module.removeData(moduleNamespace);
          instance = undefined;
        },

        reset: function() {
          module.set.percent(0);
        },

        complete: function() {
          if(module.percent === undefined || module.percent < 100) {
            module.set.percent(100);
          }
        },

        read: {
          metadata: function() {
            if( $module.data(metadata.percent) ) {
              module.verbose('Current percent value set from metadata');
              module.percent = $module.data(metadata.percent);
            }
            if( $module.data(metadata.total) ) {
              module.verbose('Total value set from metadata');
              module.total = $module.data(metadata.total);
            }
            if( $module.data(metadata.value) ) {
              module.verbose('Current value set from metadata');
              module.value = $module.data(metadata.value);
            }
          },
          currentValue: function() {
            return (module.value !== undefined)
              ? module.value
              : false
            ;
          }
        },

        increment: function(incrementValue) {
          var
            total          = module.total || false,
            edgeValue,
            startValue,
            newValue
          ;
          if(total) {
            startValue     = module.value || 0;
            incrementValue = incrementValue || 1;
            newValue       = startValue + incrementValue;
            edgeValue      = module.total;
            module.debug('Incrementing value by', incrementValue, startValue, edgeValue);
            if(newValue > edgeValue ) {
              module.debug('Value cannot increment above total', edgeValue);
              newValue = edgeValue;
            }
            module.set.progress(newValue);
          }
          else {
            startValue     = module.percent || 0;
            incrementValue = incrementValue || module.get.randomValue();
            newValue       = startValue + incrementValue;
            edgeValue      = 100;
            module.debug('Incrementing percentage by', incrementValue, startValue);
            if(newValue > edgeValue ) {
              module.debug('Value cannot increment above 100 percent');
              newValue = edgeValue;
            }
            module.set.progress(newValue);
          }
        },
        decrement: function(decrementValue) {
          var
            total     = module.total || false,
            edgeValue = 0,
            startValue,
            newValue
          ;
          if(total) {
            startValue     =  module.value   || 0;
            decrementValue =  decrementValue || 1;
            newValue       =  startValue - decrementValue;
            module.debug('Decrementing value by', decrementValue, startValue);
          }
          else {
            startValue     =  module.percent || 0;
            decrementValue =  decrementValue || module.get.randomValue();
            newValue       =  startValue - decrementValue;
            module.debug('Decrementing percentage by', decrementValue, startValue);
          }

          if(newValue < edgeValue) {
            module.debug('Value cannot decrement below 0');
            newValue = 0;
          }
          module.set.progress(newValue);
        },

        get: {
          text: function(templateText) {
            var
              value   = module.value                || 0,
              total   = module.total                || 0,
              percent = (module.is.visible() && animating)
                ? module.get.displayPercent()
                : module.percent || 0,
              left = (module.total > 0)
                ? (total - value)
                : (100 - percent)
            ;
            templateText = templateText || '';
            templateText = templateText
              .replace('{value}', value)
              .replace('{total}', total)
              .replace('{left}', left)
              .replace('{percent}', percent)
            ;
            module.debug('Adding variables to progress bar text', templateText);
            return templateText;
          },
          randomValue: function() {
            module.debug('Generating random increment percentage');
            return Math.floor((Math.random() * settings.random.max) + settings.random.min);
          },

          transitionEnd: function() {
            var
              element     = document.createElement('element'),
              transitions = {
                'transition'       :'transitionend',
                'OTransition'      :'oTransitionEnd',
                'MozTransition'    :'transitionend',
                'WebkitTransition' :'webkitTransitionEnd'
              },
              transition
            ;
            for(transition in transitions){
              if( element.style[transition] !== undefined ){
                return transitions[transition];
              }
            }
          },

          // gets current displayed percentage (if animating values this is the intermediary value)
          displayPercent: function() {
            var
              barWidth       = $bar.width(),
              totalWidth     = $module.width(),
              minDisplay     = parseInt($bar.css('min-width'), 10),
              displayPercent = (barWidth > minDisplay)
                ? (barWidth / totalWidth * 100)
                : module.percent
            ;
            if(settings.precision === 0) {
              return Math.round(displayPercent);
            }
            return Math.round(displayPercent * (10 * settings.precision) / (10 * settings.precision) );
          },

          percent: function() {
            return module.percent || 0;
          },
          value: function() {
            return module.value || false;
          },
          total: function() {
            return module.total || false;
          }
        },

        is: {
          success: function() {
            return $module.hasClass(className.success);
          },
          warning: function() {
            return $module.hasClass(className.warning);
          },
          error: function() {
            return $module.hasClass(className.error);
          },
          active: function() {
            return $module.hasClass(className.active);
          },
          visible: function() {
            return $module.is(':visible');
          }
        },

        remove: {
          state: function() {
            module.verbose('Removing stored state');
            delete module.total;
            delete module.percent;
            delete module.value;
          },
          active: function() {
            module.verbose('Removing active state');
            $module.removeClass(className.active);
          },
          success: function() {
            module.verbose('Removing success state');
            $module.removeClass(className.success);
          },
          warning: function() {
            module.verbose('Removing warning state');
            $module.removeClass(className.warning);
          },
          error: function() {
            module.verbose('Removing error state');
            $module.removeClass(className.error);
          }
        },

        set: {
          barWidth: function(value) {
            if(value > 100) {
              module.error(error.tooHigh, value);
            }
            else if (value < 0) {
              module.error(error.tooLow, value);
            }
            else {
              $bar
                .css('width', value + '%')
              ;
              $module
                .attr('data-percent', parseInt(value, 10))
              ;
            }
          },
          duration: function(duration) {
            duration = duration || settings.duration;
            duration = (typeof duration == 'number')
              ? duration + 'ms'
              : duration
            ;
            module.verbose('Setting progress bar transition duration', duration);
            $bar
              .css({
                '-webkit-transition-duration': duration,
                '-moz-transition-duration': duration,
                '-ms-transition-duration': duration,
                '-o-transition-duration': duration,
                'transition-duration':  duration
              })
            ;
          },
          initials: function() {
            if(settings.total !== false) {
              module.verbose('Current total set in settings', settings.total);
              module.total = settings.total;
            }
            if(settings.value !== false) {
              module.verbose('Current value set in settings', settings.value);
              module.value = settings.value;
            }
            if(settings.percent !== false) {
              module.verbose('Current percent set in settings', settings.percent);
              module.percent = settings.percent;
            }
            if(module.percent !== undefined) {
              module.set.percent(module.percent);
            }
            else if(module.value !== undefined) {
              module.set.progress(module.value);
            }
          },
          percent: function(percent) {
            percent = (typeof percent == 'string')
              ? +(percent.replace('%', ''))
              : percent
            ;
            if(percent > 0 && percent < 1) {
              module.verbose('Module percentage passed as decimal, converting');
              percent = percent * 100;
            }
            // round percentage
            if(settings.precision === 0) {
              percent = Math.round(percent);
            }
            else {
              percent = Math.round(percent * (10 * settings.precision) / (10 * settings.precision) );
            }
            module.percent = percent;
            if(module.total) {
              module.value = Math.round( (percent / 100) * module.total);
            }
            else if(settings.limitValues) {
              module.value = (module.value > 100)
                ? 100
                : (module.value < 0)
                  ? 0
                  : module.value
              ;
            }
            module.set.barWidth(percent);
            if( module.is.visible() ) {
              module.set.labelInterval();
            }
            module.set.labels();
            settings.onChange.call(element, percent, module.value, module.total);
          },
          labelInterval: function() {
            var
              animationCallback = function() {
                module.verbose('Bar finished animating, removing continuous label updates');
                clearInterval(module.interval);
                animating = false;
                module.set.labels();
              }
            ;
            clearInterval(module.interval);
            $bar.one(transitionEnd + eventNamespace, animationCallback);
            module.timer = setTimeout(animationCallback, settings.duration + 100);
            animating = true;
            module.interval = setInterval(module.set.labels, settings.framerate);
          },
          labels: function() {
            module.verbose('Setting both bar progress and outer label text');
            module.set.barLabel();
            module.set.state();
          },
          label: function(text) {
            text = text || '';
            if(text) {
              text = module.get.text(text);
              module.debug('Setting label to text', text);
              $label.text(text);
            }
          },
          state: function(percent) {
            percent = (percent !== undefined)
              ? percent
              : module.percent
            ;
            if(percent === 100) {
              if(settings.autoSuccess && !(module.is.warning() || module.is.error())) {
                module.set.success();
                module.debug('Automatically triggering success at 100%');
              }
              else {
                module.verbose('Reached 100% removing active state');
                module.remove.active();
              }
            }
            else if(percent > 0) {
              module.verbose('Adjusting active progress bar label', percent);
              module.set.active();
            }
            else {
              module.remove.active();
              module.set.label(settings.text.active);
            }
          },
          barLabel: function(text) {
            if(text !== undefined) {
              $progress.text( module.get.text(text) );
            }
            else if(settings.label == 'ratio' && module.total) {
              module.debug('Adding ratio to bar label');
              $progress.text( module.get.text(settings.text.ratio) );
            }
            else if(settings.label == 'percent') {
              module.debug('Adding percentage to bar label');
              $progress.text( module.get.text(settings.text.percent) );
            }
          },
          active: function(text) {
            text = text || settings.text.active;
            module.debug('Setting active state');
            if(settings.showActivity && !module.is.active() ) {
              $module.addClass(className.active);
            }
            module.remove.warning();
            module.remove.error();
            module.remove.success();
            if(text) {
              module.set.label(text);
            }
            settings.onActive.call(element, module.value, module.total);
          },
          success : function(text) {
            text = text || settings.text.success;
            module.debug('Setting success state');
            $module.addClass(className.success);
            module.remove.active();
            module.remove.warning();
            module.remove.error();
            module.complete();
            if(text) {
              module.set.label(text);
            }
            settings.onSuccess.call(element, module.total);
          },
          warning : function(text) {
            text = text || settings.text.warning;
            module.debug('Setting warning state');
            $module.addClass(className.warning);
            module.remove.active();
            module.remove.success();
            module.remove.error();
            module.complete();
            if(text) {
              module.set.label(text);
            }
            settings.onWarning.call(element, module.value, module.total);
          },
          error : function(text) {
            text = text || settings.text.error;
            module.debug('Setting error state');
            $module.addClass(className.error);
            module.remove.active();
            module.remove.success();
            module.remove.warning();
            module.complete();
            if(text) {
              module.set.label(text);
            }
            settings.onError.call(element, module.value, module.total);
          },
          total: function(totalValue) {
            module.total = totalValue;
          },
          progress: function(value) {
            var
              numericValue = (typeof value === 'string')
                ? (value.replace(/[^\d.]/g, '') !== '')
                  ? +(value.replace(/[^\d.]/g, ''))
                  : false
                : value,
              percentComplete
            ;
            if(numericValue === false) {
              module.error(error.nonNumeric, value);
            }
            if(module.total) {
              module.value    = numericValue;
              percentComplete = (numericValue / module.total) * 100;
              module.debug('Calculating percent complete from total', percentComplete);
              module.set.percent( percentComplete );
            }
            else {
              percentComplete = numericValue;
              module.debug('Setting value to exact percentage value', percentComplete);
              module.set.percent( percentComplete );
            }
          }
        },

        setting: function(name, value) {
          module.debug('Changing setting', name, value);
          if( $.isPlainObject(name) ) {
            $.extend(true, settings, name);
          }
          else if(value !== undefined) {
            settings[name] = value;
          }
          else {
            return settings[name];
          }
        },
        internal: function(name, value) {
          if( $.isPlainObject(name) ) {
            $.extend(true, module, name);
          }
          else if(value !== undefined) {
            module[name] = value;
          }
          else {
            return module[name];
          }
        },
        debug: function() {
          if(settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.debug.apply(console, arguments);
            }
          }
        },
        verbose: function() {
          if(settings.verbose && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.verbose.apply(console, arguments);
            }
          }
        },
        error: function() {
          module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
          module.error.apply(console, arguments);
        },
        performance: {
          log: function(message) {
            var
              currentTime,
              executionTime,
              previousTime
            ;
            if(settings.performance) {
              currentTime   = new Date().getTime();
              previousTime  = time || currentTime;
              executionTime = currentTime - previousTime;
              time          = currentTime;
              performance.push({
                'Name'           : message[0],
                'Arguments'      : [].slice.call(message, 1) || '',
                'Element'        : element,
                'Execution Time' : executionTime
              });
            }
            clearTimeout(module.performance.timer);
            module.performance.timer = setTimeout(module.performance.display, 100);
          },
          display: function() {
            var
              title = settings.name + ':',
              totalTime = 0
            ;
            time = false;
            clearTimeout(module.performance.timer);
            $.each(performance, function(index, data) {
              totalTime += data['Execution Time'];
            });
            title += ' ' + totalTime + 'ms';
            if(moduleSelector) {
              title += ' \'' + moduleSelector + '\'';
            }
            if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
              console.groupCollapsed(title);
              if(console.table) {
                console.table(performance);
              }
              else {
                $.each(performance, function(index, data) {
                  console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
                });
              }
              console.groupEnd();
            }
            performance = [];
          }
        },
        invoke: function(query, passedArguments, context) {
          var
            object = instance,
            maxDepth,
            found,
            response
          ;
          passedArguments = passedArguments || queryArguments;
          context         = element         || context;
          if(typeof query == 'string' && object !== undefined) {
            query    = query.split(/[\. ]/);
            maxDepth = query.length - 1;
            $.each(query, function(depth, value) {
              var camelCaseValue = (depth != maxDepth)
                ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
                : query
              ;
              if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
                object = object[camelCaseValue];
              }
              else if( object[camelCaseValue] !== undefined ) {
                found = object[camelCaseValue];
                return false;
              }
              else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
                object = object[value];
              }
              else if( object[value] !== undefined ) {
                found = object[value];
                return false;
              }
              else {
                module.error(error.method, query);
                return false;
              }
            });
          }
          if ( $.isFunction( found ) ) {
            response = found.apply(context, passedArguments);
          }
          else if(found !== undefined) {
            response = found;
          }
          if($.isArray(returnedValue)) {
            returnedValue.push(response);
          }
          else if(returnedValue !== undefined) {
            returnedValue = [returnedValue, response];
          }
          else if(response !== undefined) {
            returnedValue = response;
          }
          return found;
        }
      };

      if(methodInvoked) {
        if(instance === undefined) {
          module.initialize();
        }
        module.invoke(query);
      }
      else {
        if(instance !== undefined) {
          instance.invoke('destroy');
        }
        module.initialize();
      }
    })
  ;

  return (returnedValue !== undefined)
    ? returnedValue
    : this
  ;
};

$.fn.progress.settings = {

  name         : 'Progress',
  namespace    : 'progress',

  debug        : false,
  verbose      : true,
  performance  : true,

  random       : {
    min : 2,
    max : 5
  },

  duration     : 300,

  autoSuccess  : true,
  showActivity : true,
  limitValues  : true,

  label        : 'percent',
  precision    : 1,
  framerate    : (1000 / 30), /// 30 fps

  percent      : false,
  total        : false,
  value        : false,

  onChange     : function(percent, value, total){},
  onSuccess    : function(total){},
  onActive     : function(value, total){},
  onError      : function(value, total){},
  onWarning    : function(value, total){},

  error    : {
    method     : 'The method you called is not defined.',
    nonNumeric : 'Progress value is non numeric',
    tooHigh    : 'Value specified is above 100%',
    tooLow     : 'Value specified is below 0%'
  },

  regExp: {
    variable: /\{\$*[A-z0-9]+\}/g
  },

  metadata: {
    percent : 'percent',
    total   : 'total',
    value   : 'value'
  },

  selector : {
    bar      : '> .bar',
    label    : '> .label',
    progress : '.bar > .progress'
  },

  text : {
    active  : false,
    error   : false,
    success : false,
    warning : false,
    percent : '{percent}%',
    ratio   : '{value} of {total}'
  },

  className : {
    active  : 'active',
    error   : 'error',
    success : 'success',
    warning : 'warning'
  }

};

})( jQuery, window , document );


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Shadow</string>
	<string name="Play">Play</string>
    <string name="StartListening">Start listening</string>
    <string name="StopListening">Stop listening</string>
    <string name="VoiceActivityLevel">Voice Activity Level: </string>
    <string name="Time">Time ms: </string>
    <string name="SaveInfo">Audio Files will be saved into \"shadow\" folder</string>
</resources>


text:
package ml.alternet.discover.gen;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Set;

import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Filer;
import javax.annotation.processing.Messager;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.MirroredTypeException;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Elements;
import javax.tools.Diagnostic.Kind;
import javax.tools.FileObject;
import javax.tools.StandardLocation;

import ml.alternet.discover.Injection;
import ml.alternet.discover.Injection.LookupKey;
import ml.alternet.discover.Injection.Producer;
import ml.alternet.discover.Injection.Producers;
import ml.alternet.util.AnnotationProcessorUtil;

/**
 * Generate a producer that inject classes.
 *
 * @see LookupKey
 * @see javax.inject.Inject
 *
 * @author Philippe Poulard
 */
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class LookupKeyProducerGenerator extends AbstractProcessor {

    static Set<String> TYPES = new HashSet<>();

    static {
        TYPES.add(Producer.class.getCanonicalName());
        TYPES.add(Producers.class.getCanonicalName());
    }

    Set<Mapping> mappings = new HashSet<>();

    static class Mapping {

        String producerPkg;
        String producerClassName;
        String shortClassName;
        String className;
        String variant;
        String lookupKey;

        Mapping(String producerPkg, String producerClassName, String shortClassName, String className,
                String variant, String lookupKey)
        {
            this.producerPkg = producerPkg;             // org.acme.foo
            this.producerClassName = producerClassName; // Bar$Baz_Producer_var
            this.shortClassName = shortClassName;       // Bar$Baz
            this.className = className;                 // org.acme.foo.Bar.Baz
            this.variant = variant;                     // var
            this.lookupKey = lookupKey;                 // org.acme.foo.Bar.Baz/var
        }

        @Override
        public boolean equals(Object obj) {
            return className.equals(((Mapping) obj).className) && variant.equals(((Mapping) obj).variant);
        }

        @Override
        public int hashCode() {
            return className.hashCode() ^ variant.hashCode();
        }

    }

    @Override
    public Set<String> getSupportedAnnotationTypes() {
        return TYPES;
    }

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        if (roundEnv.processingOver()) {
            generateFiles();
        } else {
            processAnnotations(annotations, roundEnv);
        }
        Messager messager = processingEnv.getMessager();
        messager.printMessage(Kind.NOTE, LookupKeyProducerGenerator.class.getCanonicalName() + " : end");
        return true;
    }

    /**
     * Process the annotations.
     *
     * @param annotations The annotation types requested to be processed
     * @param roundEnv Environment for information about the current and prior round
     */
    public void processAnnotations(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        Elements eltUtils = processingEnv.getElementUtils();

        TypeElement elementLookup = eltUtils.getTypeElement(Producers.class.getCanonicalName());
        Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(elementLookup);
        for (Element element : elements) {
            Producers lks = element.getAnnotation(Producers.class);
            if (lks != null) {
                for (Producer lk : lks.value()) {
                    processAnnotation(element, lk);
                }
            }
        }
        elementLookup = eltUtils.getTypeElement(Producer.class.getCanonicalName());
        elements = roundEnv.getElementsAnnotatedWith(elementLookup);
        for (Element element : elements) {
            Producer lk = element.getAnnotation(Producer.class);
            if (lk != null) {
                processAnnotation(element, lk);
            }
        }
    }

    /**
     * Process a single annotation.
     *
     * @param element The element that hold the annotation.
     * @param producer The annotation.
     */
    public void processAnnotation(Element element, Injection.Producer producer) {
        String forClass = null;
        try { // getting a Class cause an exception
            producer.forClass();
        } catch (MirroredTypeException mte) {
            TypeMirror tm = mte.getTypeMirror();
            forClass = AnnotationProcessorUtil.getClassName(tm);
        }
        if (forClass.equals(Void.class.getName()) && element.getKind().isClass() || element.getKind().isInterface()) {
            forClass = AnnotationProcessorUtil.getClassName((TypeElement) element);
        }
        String producerPkg = forClass.substring(0, forClass.lastIndexOf('.'));
        String shortClassName = forClass.substring(forClass.lastIndexOf('.') + 1);
        String variant = producer.variant();
        String producerClassName = shortClassName + "_Producer_" + variant;
        forClass = forClass.replace('$', '.');
        String lookupKey;
        if (producer.lookupVariant().length() == 0) {
            if (variant.length() == 0) {
                lookupKey = forClass;
            } else {
                lookupKey = forClass + '/' + variant;
            }
        } else if (producer.lookupVariant().trim().length() == 0) {
            lookupKey = forClass;
        } else {
            lookupKey = forClass + '/' + producer.lookupVariant();
        }
        String className = forClass;
        this.mappings.add(new Mapping(producerPkg, producerClassName, shortClassName, className, variant, lookupKey));
    }

    /**
     * Generate the files.
     */
    public void generateFiles() {
        Filer filer = processingEnv.getFiler();
        Messager messager = processingEnv.getMessager();
        for (Mapping mapping : this.mappings) {
            messager.printMessage(Kind.NOTE, "GENERATE PRODUCER " + mapping.producerPkg + "."
                    + mapping.producerClassName);
            try {
                FileObject file = filer.createResource(StandardLocation.SOURCE_OUTPUT, mapping.producerPkg,
                        mapping.producerClassName + ".java");
                messager.printMessage(Kind.NOTE, file.toUri().toString());
                PrintWriter writer = new PrintWriter(file.openWriter());
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        LookupKeyProducerGenerator.class.getResourceAsStream("Producer.java.template"), "UTF8"));
                reader.lines().map(s -> s.replaceAll("\\{producerPkg\\}", escapeDollar(mapping.producerPkg)))
                        .map(s -> s.replaceAll("\\{producerClassName\\}", escapeDollar(mapping.producerClassName)))
                        .map(s -> s.replaceAll("\\{shortClassName\\}", escapeDollar(mapping.shortClassName)))
                        .map(s -> s.replaceAll("\\{className\\}", escapeDollar(mapping.className)))
                        .map(s -> s.replaceAll("\\{variant\\}", escapeDollar(mapping.variant)))
                        .map(s -> s.replaceAll("\\{lookupKey\\}", escapeDollar(mapping.lookupKey)))
                        .forEach(writer::println);
                writer.close();
            } catch (IOException ioe) {
                messager.printMessage(Kind.ERROR, ioe.getMessage());
            }
        }
    }

    // escape $ sign :
    // LookupKeyProducerTest$B2_Producer_var2 -> LookupKeyProducerTest\$B2_Producer_var2
    // because the result string is used as replacement regexp, and the $ sign
    // stand for a backreference
    String escapeDollar(String string) {
        return string.replaceAll("\\$", "\\\\\\$");
    }

}


text:
#ifndef __OPENCV_PRECOMP_H__
#define __OPENCV_PRECOMP_H__

#if defined _MSC_VER && _MSC_VER >= 1200
    // disable warnings related to inline functions
    #pragma warning( disable: 4251 4711 4710 4514 )
#endif

#ifdef HAVE_CONFIG_H
#include <cvconfig.h>
#endif

#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/imgproc/imgproc_c.h"
#include "opencv2/core/internal.hpp"
#include <math.h>
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#include <float.h>

/* helper tables */
extern const uchar icvSaturate8u_cv[];
#define CV_FAST_CAST_8U(t)  (assert(-256 <= (t) || (t) <= 512), icvSaturate8u_cv[(t)+256])
#define CV_CALC_MIN_8U(a,b) (a) -= CV_FAST_CAST_8U((a) - (b))
#define CV_CALC_MAX_8U(a,b) (a) += CV_FAST_CAST_8U((b) - (a))

// -256.f ... 511.f
extern const float icv8x32fTab_cv[];
#define CV_8TO32F(x)  icv8x32fTab_cv[(x)+256]

// (-128.f)^2 ... (255.f)^2
extern const float icv8x32fSqrTab[];
#define CV_8TO32F_SQR(x)  icv8x32fSqrTab[(x)+128]

namespace cv
{

static inline Point normalizeAnchor( Point anchor, Size ksize )
{
    if( anchor.x == -1 )
        anchor.x = ksize.width/2;
    if( anchor.y == -1 )
        anchor.y = ksize.height/2;
    CV_Assert( anchor.inside(Rect(0, 0, ksize.width, ksize.height)) );
    return anchor;
}

void preprocess2DKernel( const Mat& kernel, vector<Point>& coords, vector<uchar>& coeffs );
void crossCorr( const Mat& src, const Mat& templ, Mat& dst,
                Size corrsize, int ctype,
                Point anchor=Point(0,0), double delta=0,
                int borderType=BORDER_REFLECT_101 );

}

typedef struct CvPyramid
{
    uchar **ptr;
    CvSize *sz;
    double *rate;
    int *step;
    uchar *state;
    int level;
}
CvPyramid;

#define  CV_COPY( dst, src, len, idx ) \
    for( (idx) = 0; (idx) < (len); (idx)++) (dst)[idx] = (src)[idx]

#define  CV_SET( dst, val, len, idx )  \
    for( (idx) = 0; (idx) < (len); (idx)++) (dst)[idx] = (val)

/* performs convolution of 2d floating-point array with 3x1, 1x3 or separable 3x3 mask */
void icvSepConvSmall3_32f( float* src, int src_step, float* dst, int dst_step,
            CvSize src_size, const float* kx, const float* ky, float* buffer );

#undef   CV_CALC_MIN
#define  CV_CALC_MIN(a, b) if((a) > (b)) (a) = (b)

#undef   CV_CALC_MAX
#define  CV_CALC_MAX(a, b) if((a) < (b)) (a) = (b)

CvStatus CV_STDCALL
icvCopyReplicateBorder_8u( const uchar* src, int srcstep, CvSize srcroi,
                           uchar* dst, int dststep, CvSize dstroi,
                           int left, int right, int cn, const uchar* value = 0 );

CvStatus CV_STDCALL icvGetRectSubPix_8u_C1R
( const uchar* src, int src_step, CvSize src_size,
  uchar* dst, int dst_step, CvSize win_size, CvPoint2D32f center );
CvStatus CV_STDCALL icvGetRectSubPix_8u32f_C1R
( const uchar* src, int src_step, CvSize src_size,
  float* dst, int dst_step, CvSize win_size, CvPoint2D32f center );
CvStatus CV_STDCALL icvGetRectSubPix_32f_C1R
( const float* src, int src_step, CvSize src_size,
  float* dst, int dst_step, CvSize win_size, CvPoint2D32f center );

CvStatus CV_STDCALL icvGetQuadrangleSubPix_8u_C1R
( const uchar* src, int src_step, CvSize src_size,
  uchar* dst, int dst_step, CvSize win_size, const float *matrix );
CvStatus CV_STDCALL icvGetQuadrangleSubPix_8u32f_C1R
( const uchar* src, int src_step, CvSize src_size,
  float* dst, int dst_step, CvSize win_size, const float *matrix );
CvStatus CV_STDCALL icvGetQuadrangleSubPix_32f_C1R
( const float* src, int src_step, CvSize src_size,
  float* dst, int dst_step, CvSize win_size, const float *matrix );

#include "_geom.h"

#endif /*__OPENCV_CV_INTERNAL_H_*/


text:
import datetime

from mongoengine import Document, StringField, ListField, EmbeddedDocumentField
from mongoengine import BooleanField, DynamicEmbeddedDocument
from difflib import unified_diff
from django.conf import settings

from cybox.objects.domain_name_object import DomainName
from cybox.core import Observable

from crits.core.crits_mongoengine import CritsBaseAttributes, CritsDocument
from crits.core.crits_mongoengine import CritsDocumentFormatter, CritsSourceDocument
from crits.domains.migrate import migrate_domain

class TLD(CritsDocument, Document):
    """
    TLD class for adding TLDs to the database.
    """

    meta = {
        "collection": settings.COL_EFFECTIVE_TLDS,
        "crits_type": 'TLD',
        "latest_schema_version": 1,
        "schema_doc": {
            'tld': 'The domain TLD',
        },
    }

    tld = StringField(required=True)

class EmbeddedWhoIs(DynamicEmbeddedDocument, CritsDocumentFormatter):
    """
    EmbeddedWhoIs Class.
    """

    meta = {
        'allow_inheritance': False
    }

class Domain(CritsBaseAttributes, CritsSourceDocument, Document):
    """
    Domain Class.
    """

    meta = {
        "collection": settings.COL_DOMAINS,
        "crits_type": 'Domain',
        "latest_schema_version": 3,
        "schema_doc": {
            'analyst': 'Analyst who added/modified this domain',
            'domain': 'The domain name of this domain',
            'type': 'Record type of this domain',
            'watchlistEnabled': 'Boolean - whether this is a domain to watch',
        },
        "jtable_opts": {
                         'details_url': 'crits.domains.views.domain_detail',
                         'details_url_key': 'domain',
                         'default_sort': "domain ASC",
                         'searchurl': 'crits.domains.views.domains_listing',
                         'fields': [ "domain", "modified", "source",
                                     "campaign", "status", "id"],
                         'jtopts_fields': [ "details",
                                            "domain",
                                            "modified",
                                            "source",
                                            "campaign",
                                            "status",
                                            "favorite",
                                            "id"],
                         'hidden_fields': [],
                         'linked_fields': ["source", "campaign"],
                         'details_link': 'details',
                         'no_sort': ['details']
                       }

    }

    domain = StringField(required=True)
    record_type = StringField(default="A", db_field="type")
    watchlistEnabled = BooleanField(default=False)
    analyst = StringField()

    def migrate(self):
        """
        Migrate to the latest schema version.
        """

        migrate_domain(self)

    def _custom_save(self, force_insert=False, validate=True, clean=False,
        write_concern=None, cascade=None, cascade_kwargs=None,
        _refs=None, username=None, **kwargs):
        """
        Custom save. Overrides default core custom save function.
        """

        #TODO: parse for potential root domain and add it as well?
        # - would require adding relationships between the two as well
        return super(self.__class__, self)._custom_save(force_insert, validate,
            clean, write_concern, cascade, cascade_kwargs, _refs, username)

    def to_cybox_observable(self):
        """
            Convert a Domain to a CybOX Observables.
            Returns a tuple of (CybOX object, releasability list).

            To get the cybox object as xml or json, call to_xml() or
            to_json(), respectively, on the resulting CybOX object.
        """
        obj = DomainName()
        obj.value = self.domain
        obj.type_ = self.record_type
        return ([Observable(obj)], self.releasability)

    @classmethod
    def from_cybox(cls, cybox_obs):
        """
        Convert a Cybox DefinedObject to a MongoEngine Domain object.

        :param cybox_obs: The cybox observable to create the Domain from.
        :type cybox_obs: :class:`cybox.core.Observable``
        :returns: :class:`crits.domains.domain.Domain`
        """
        cybox_object = cybox_obs.object_.properties
        db_obj = Domain.objects(domain=str(cybox_object.value)).first()
        if db_obj:
            return db_obj
        else:
            domain = cls()
            domain.domain = str(cybox_object.value)
            domain.record_type = str(cybox_object.type_)
            return domain


text:
require('./lib/loader')

const express = require('express'),
      // path = require('path'),
      logger = require('morgan'),
      cookieParser = require('cookie-parser'),
      bodyParser = require('body-parser'),
      http = require('http')

const users = require('./routes/user')

const app = express()

app.set('port', 3030)

app.use(logger('dev'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.use(cookieParser())

app.use('/users', users({
  db: 'login-test',
}))

app.use(function (req, res, next) {
  const err = new Error('Not Found')
  err.status = 404
  next(err)
})

app.use(function (err, req, res) {
  res.status(err.status || 500)
  res.render('error', {
    message: err.message,
    error: err,
  })
})

const server = http.createServer(app)

server.listen(3030)
server.on('error', (err) => {
  console.log(err.stack)
})