text:
// started from https://github.com/google/grafika/blob/f3c8c3dee60153f471312e21acac8b3a3cddd7dc/src/com/android/grafika/gles/Texture2dProgram.java

package io.cine.android.streaming.gles;

import android.opengl.GLES11Ext;
import android.opengl.GLES20;
import android.util.Log;

import java.nio.FloatBuffer;

/**
 * GL program and supporting functions for textured 2D shapes.
 */
public class Texture2dProgram {
    // Fragment shader with a convolution filter.  The upper-left half will be drawn normally,
    // the lower-right half will have the filter applied, and a thin red line will be drawn
    // at the border.
    //
    // This is not optimized for performance.  Some things that might make this faster:
    // - Remove the conditionals.  They're used to present a half & half view with a red
    //   stripe across the middle, but that's only useful for a demo.
    // - Unroll the loop.  Ideally the compiler does this for you when it's beneficial.
    // - Bake the filter kernel into the shader, instead of passing it through a uniform
    //   array.  That, combined with loop unrolling, should reduce memory accesses.
    public static final int KERNEL_SIZE = 9;
    private static final String FRAGMENT_SHADER_EXT_FILT =
            "#extension GL_OES_EGL_image_external : require\n" +
                    "#define KERNEL_SIZE " + KERNEL_SIZE + "\n" +
                    "precision highp float;\n" +
                    "varying vec2 vTextureCoord;\n" +
                    "uniform samplerExternalOES sTexture;\n" +
                    "uniform float uKernel[KERNEL_SIZE];\n" +
                    "uniform vec2 uTexOffset[KERNEL_SIZE];\n" +
                    "uniform float uColorAdjust;\n" +
                    "void main() {\n" +
                    "    int i = 0;\n" +
                    "    vec4 sum = vec4(0.0);\n" +
                    "    if (vTextureCoord.x < vTextureCoord.y - 0.005) {\n" +
                    "        for (i = 0; i < KERNEL_SIZE; i++) {\n" +
                    "            vec4 texc = texture2D(sTexture, vTextureCoord + uTexOffset[i]);\n" +
                    "            sum += texc * uKernel[i];\n" +
                    "        }\n" +
                    "    sum += uColorAdjust;\n" +
                    "    } else if (vTextureCoord.x > vTextureCoord.y + 0.005) {\n" +
                    "        sum = texture2D(sTexture, vTextureCoord);\n" +
                    "    } else {\n" +
                    "        sum.r = 1.0;\n" +
                    "    }\n" +
                    "    gl_FragColor = sum;\n" +
                    "}\n";
    private float[] mKernel = new float[KERNEL_SIZE];
    private static final String TAG = GlUtil.TAG;
    // Simple vertex shader, used for all programs.
    private static final String VERTEX_SHADER =
            "uniform mat4 uMVPMatrix;\n" +
                    "uniform mat4 uTexMatrix;\n" +
                    "attribute vec4 aPosition;\n" +
                    "attribute vec4 aTextureCoord;\n" +
                    "varying vec2 vTextureCoord;\n" +
                    "void main() {\n" +
                    "    gl_Position = uMVPMatrix * aPosition;\n" +
                    "    vTextureCoord = (uTexMatrix * aTextureCoord).xy;\n" +
                    "}\n";
    // Simple fragment shader for use with "normal" 2D textures.
    private static final String FRAGMENT_SHADER_2D =
            "precision mediump float;\n" +
                    "varying vec2 vTextureCoord;\n" +
                    "uniform sampler2D sTexture;\n" +
                    "void main() {\n" +
                    "    gl_FragColor = texture2D(sTexture, vTextureCoord);\n" +
                    "}\n";
    // Simple fragment shader for use with external 2D textures (e.g. what we get from
    // SurfaceTexture).
    private static final String FRAGMENT_SHADER_EXT =
            "#extension GL_OES_EGL_image_external : require\n" +
                    "precision mediump float;\n" +
                    "varying vec2 vTextureCoord;\n" +
                    "uniform samplerExternalOES sTexture;\n" +
                    "void main() {\n" +
                    "    gl_FragColor = texture2D(sTexture, vTextureCoord);\n" +
                    "}\n";
    // Fragment shader that converts color to black & white with a simple transformation.
    private static final String FRAGMENT_SHADER_EXT_BW =
            "#extension GL_OES_EGL_image_external : require\n" +
                    "precision mediump float;\n" +
                    "varying vec2 vTextureCoord;\n" +
                    "uniform samplerExternalOES sTexture;\n" +
                    "void main() {\n" +
                    "    vec4 tc = texture2D(sTexture, vTextureCoord);\n" +
                    "    float color = tc.r * 0.3 + tc.g * 0.59 + tc.b * 0.11;\n" +
                    "    gl_FragColor = vec4(color, color, color, 1.0);\n" +
                    "}\n";
    private ProgramType mProgramType;

    // Handles to the GL program and various components of it.
    private int mProgramHandle;
    private int muMVPMatrixLoc;
    private int muTexMatrixLoc;
    private int muKernelLoc;
    private int muTexOffsetLoc;
    private int muColorAdjustLoc;
    private int maPositionLoc;
    private int maTextureCoordLoc;

    private int mTextureTarget;
    private float[] mTexOffset;
    private float mColorAdjust;

    /**
     * Prepares the program in the current EGL context.
     */
    public Texture2dProgram(ProgramType programType) {
        mProgramType = programType;

        switch (programType) {
            case TEXTURE_2D:
                mTextureTarget = GLES20.GL_TEXTURE_2D;
                mProgramHandle = GlUtil.createProgram(VERTEX_SHADER, FRAGMENT_SHADER_2D);
                break;
            case TEXTURE_EXT:
                mTextureTarget = GLES11Ext.GL_TEXTURE_EXTERNAL_OES;
                mProgramHandle = GlUtil.createProgram(VERTEX_SHADER, FRAGMENT_SHADER_EXT);
                break;
            case TEXTURE_EXT_BW:
                mTextureTarget = GLES11Ext.GL_TEXTURE_EXTERNAL_OES;
                mProgramHandle = GlUtil.createProgram(VERTEX_SHADER, FRAGMENT_SHADER_EXT_BW);
                break;
            case TEXTURE_EXT_FILT:
                mTextureTarget = GLES11Ext.GL_TEXTURE_EXTERNAL_OES;
                mProgramHandle = GlUtil.createProgram(VERTEX_SHADER, FRAGMENT_SHADER_EXT_FILT);
                break;
            default:
                throw new RuntimeException("Unhandled type " + programType);
        }
        if (mProgramHandle == 0) {
            throw new RuntimeException("Unable to create program");
        }
        Log.d(TAG, "Created program " + mProgramHandle + " (" + programType + ")");

        // get locations of attributes and uniforms

        maPositionLoc = GLES20.glGetAttribLocation(mProgramHandle, "aPosition");
        GlUtil.checkLocation(maPositionLoc, "aPosition");
        maTextureCoordLoc = GLES20.glGetAttribLocation(mProgramHandle, "aTextureCoord");
        GlUtil.checkLocation(maTextureCoordLoc, "aTextureCoord");
        muMVPMatrixLoc = GLES20.glGetUniformLocation(mProgramHandle, "uMVPMatrix");
        GlUtil.checkLocation(muMVPMatrixLoc, "uMVPMatrix");
        muTexMatrixLoc = GLES20.glGetUniformLocation(mProgramHandle, "uTexMatrix");
        GlUtil.checkLocation(muTexMatrixLoc, "uTexMatrix");
        muKernelLoc = GLES20.glGetUniformLocation(mProgramHandle, "uKernel");
        if (muKernelLoc < 0) {
            // no kernel in this one
            muKernelLoc = -1;
            muTexOffsetLoc = -1;
            muColorAdjustLoc = -1;
        } else {
            // has kernel, must also have tex offset and color adj
            muTexOffsetLoc = GLES20.glGetUniformLocation(mProgramHandle, "uTexOffset");
            GlUtil.checkLocation(muTexOffsetLoc, "uTexOffset");
            muColorAdjustLoc = GLES20.glGetUniformLocation(mProgramHandle, "uColorAdjust");
            GlUtil.checkLocation(muColorAdjustLoc, "uColorAdjust");

            // initialize default values
            setKernel(new float[]{0f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 0f}, 0f);
            setTexSize(256, 256);
        }
    }

    /**
     * Releases the program.
     *

     * The appropriate EGL context must be current (i.e. the one that was used to create
     * the program).
     */
    public void release() {
        Log.d(TAG, "deleting program " + mProgramHandle);
        GLES20.glDeleteProgram(mProgramHandle);
        mProgramHandle = -1;
    }

    /**
     * Returns the program type.
     */
    public ProgramType getProgramType() {
        return mProgramType;
    }

    /**
     * Creates a texture object suitable for use with this program.
     *

     * On exit, the texture will be bound.
     */
    public int createTextureObject() {
        int[] textures = new int[1];
        GLES20.glGenTextures(1, textures, 0);
        GlUtil.checkGlError("glGenTextures");

        int texId = textures[0];
        GLES20.glBindTexture(mTextureTarget, texId);
        GlUtil.checkGlError("glBindTexture " + texId);

        GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MIN_FILTER,
                GLES20.GL_NEAREST);
        GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MAG_FILTER,
                GLES20.GL_LINEAR);
        GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_S,
                GLES20.GL_CLAMP_TO_EDGE);
        GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_T,
                GLES20.GL_CLAMP_TO_EDGE);
        GlUtil.checkGlError("glTexParameter");

        return texId;
    }

    /**
     * Configures the convolution filter values.
     *
     * @param values Normalized filter values; must be KERNEL_SIZE elements.
     */
    public void setKernel(float[] values, float colorAdj) {
        if (values.length != KERNEL_SIZE) {
            throw new IllegalArgumentException("Kernel size is " + values.length +
                    " vs. " + KERNEL_SIZE);
        }
        System.arraycopy(values, 0, mKernel, 0, KERNEL_SIZE);
        mColorAdjust = colorAdj;
        //Log.d(TAG, "filt kernel: " + Arrays.toString(mKernel) + ", adj=" + colorAdj);
    }

    /**
     * Sets the size of the texture.  This is used to find adjacent texels when filtering.
     */
    public void setTexSize(int width, int height) {
        float rw = 1.0f / width;
        float rh = 1.0f / height;

        // Don't need to create a new array here, but it's syntactically convenient.
        mTexOffset = new float[]{
                -rw, -rh, 0f, -rh, rw, -rh,
                -rw, 0f, 0f, 0f, rw, 0f,
                -rw, rh, 0f, rh, rw, rh
        };
        //Log.d(TAG, "filt size: " + width + "x" + height + ": " + Arrays.toString(mTexOffset));
    }

    /**
     * Issues the draw call.  Does the full setup on every call.
     *
     * @param mvpMatrix       The 4x4 projection matrix.
     * @param vertexBuffer    Buffer with vertex position data.
     * @param firstVertex     Index of first vertex to use in vertexBuffer.
     * @param vertexCount     Number of vertices in vertexBuffer.
     * @param coordsPerVertex The number of coordinates per vertex (e.g. x,y is 2).
     * @param vertexStride    Width, in bytes, of the position data for each vertex (often
     *                        vertexCount * sizeof(float)).
     * @param texMatrix       A 4x4 transformation matrix for texture coords.  (Primarily intended
     *                        for use with SurfaceTexture.)
     * @param texBuffer       Buffer with vertex texture data.
     * @param texStride       Width, in bytes, of the texture data for each vertex.
     */
    public void draw(float[] mvpMatrix, FloatBuffer vertexBuffer, int firstVertex,
                     int vertexCount, int coordsPerVertex, int vertexStride,
                     float[] texMatrix, FloatBuffer texBuffer, int textureId, int texStride) {
        GlUtil.checkGlError("draw start");

        // Select the program.
        GLES20.glUseProgram(mProgramHandle);
        GlUtil.checkGlError("glUseProgram");

        // Set the texture.
        GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
        GLES20.glBindTexture(mTextureTarget, textureId);

        // Copy the model / view / projection matrix over.
        GLES20.glUniformMatrix4fv(muMVPMatrixLoc, 1, false, mvpMatrix, 0);
        GlUtil.checkGlError("glUniformMatrix4fv");

        // Copy the texture transformation matrix over.
        GLES20.glUniformMatrix4fv(muTexMatrixLoc, 1, false, texMatrix, 0);
        GlUtil.checkGlError("glUniformMatrix4fv");

        // Enable the "aPosition" vertex attribute.
        GLES20.glEnableVertexAttribArray(maPositionLoc);
        GlUtil.checkGlError("glEnableVertexAttribArray");

        // Connect vertexBuffer to "aPosition".
        GLES20.glVertexAttribPointer(maPositionLoc, coordsPerVertex,
                GLES20.GL_FLOAT, false, vertexStride, vertexBuffer);
        GlUtil.checkGlError("glVertexAttribPointer");

        // Enable the "aTextureCoord" vertex attribute.
        GLES20.glEnableVertexAttribArray(maTextureCoordLoc);
        GlUtil.checkGlError("glEnableVertexAttribArray");

        // Connect texBuffer to "aTextureCoord".
        GLES20.glVertexAttribPointer(maTextureCoordLoc, 2,
                GLES20.GL_FLOAT, false, texStride, texBuffer);
        GlUtil.checkGlError("glVertexAttribPointer");

        // Populate the convolution kernel, if present.
        if (muKernelLoc >= 0) {
            GLES20.glUniform1fv(muKernelLoc, KERNEL_SIZE, mKernel, 0);
            GLES20.glUniform2fv(muTexOffsetLoc, KERNEL_SIZE, mTexOffset, 0);
            GLES20.glUniform1f(muColorAdjustLoc, mColorAdjust);
        }

        // Draw the rect.
        GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, firstVertex, vertexCount);
        GlUtil.checkGlError("glDrawArrays");

        // Done -- disable vertex array, texture, and program.
        GLES20.glDisableVertexAttribArray(maPositionLoc);
        GLES20.glDisableVertexAttribArray(maTextureCoordLoc);
        GLES20.glBindTexture(mTextureTarget, 0);
        GLES20.glUseProgram(0);
    }

    public enum ProgramType {
        TEXTURE_2D, TEXTURE_EXT, TEXTURE_EXT_BW, TEXTURE_EXT_FILT
    }
}


text:
<template name="orionMaterializeDictionaryUpdate">
  {{# autoForm collection="orion.dictionary" id="updateDictionaryForm" type="update" doc=getDoc }}
    {{# Layout template="orionMaterializeHeaderContainer" }}
      {{ i18n 'dictionary.update.title' }}
    {{/ Layout }}
    {{> reactiveTemplate template="tabs" data=getDataForTabs }}
    {{# Layout template="orionMaterializeContentContainer" }}
      {{# if currentCategory }}
        {{> afQuickFields name=currentCategory }}
      {{/ if }}
    {{/ Layout }}
    {{# Layout template="orionMaterializeButtonsContainer" }}
        <button class="waves-effect waves-light btn light-blue accent-4">{{ i18n 'global.save' }}</button>
    {{/ Layout }}
  {{/ autoForm }}
</template>

redpajama_set_name: RedPajamaGithub


text:
package org.apache.cassandra.metrics;

import java.util.concurrent.ConcurrentMap;

import com.codahale.metrics.Counter;
import org.apache.cassandra.locator.InetAddressAndPort;

import org.cliffc.high_scale_lib.NonBlockingHashMap;

import static org.apache.cassandra.metrics.CassandraMetricsRegistry.Metrics;

/**
 * Metrics for streaming.
 */
public class StreamingMetrics
{
    public static final String TYPE_NAME = "Streaming";

    private static final ConcurrentMap<InetAddressAndPort, StreamingMetrics> instances = new NonBlockingHashMap<>();

    public static final Counter activeStreamsOutbound = Metrics.counter(DefaultNameFactory.createMetricName(TYPE_NAME, "ActiveOutboundStreams", null));
    public static final Counter totalIncomingBytes = Metrics.counter(DefaultNameFactory.createMetricName(TYPE_NAME, "TotalIncomingBytes", null));
    public static final Counter totalOutgoingBytes = Metrics.counter(DefaultNameFactory.createMetricName(TYPE_NAME, "TotalOutgoingBytes", null));
    public static final Counter totalOutgoingRepairBytes = Metrics.counter(DefaultNameFactory.createMetricName(TYPE_NAME, "TotalOutgoingRepairBytes", null));
    public static final Counter totalOutgoingRepairSSTables = Metrics.counter(DefaultNameFactory.createMetricName(TYPE_NAME, "TotalOutgoingRepairSSTables", null));
    public final Counter incomingBytes;
    public final Counter outgoingBytes;

    public static StreamingMetrics get(InetAddressAndPort ip)
    {
       /*
         computeIfAbsent doesn't work for this situation. Since JMX metrics register themselves in their ctor, we need
         to create the metric exactly once, otherwise we'll get duplicate name exceptions. Although computeIfAbsent is
         thread safe in the context of the map, it uses compare and swap to add the computed value to the map. This
         means it eagerly allocates new metric instances, which can cause the jmx name collision we're trying to avoid
         if multiple calls interleave. So here we use synchronized to ensure we only instantiate metrics exactly once.
        */
       StreamingMetrics metrics = instances.get(ip);
       if (metrics == null)
       {
           synchronized (instances)
           {
               metrics = instances.get(ip);
               if (metrics == null)
               {
                   metrics = new StreamingMetrics(ip);
                   instances.put(ip, metrics);
               }
           }
       }
       return metrics;
    }

    public StreamingMetrics(final InetAddressAndPort peer)
    {
        MetricNameFactory factory = new DefaultNameFactory("Streaming", peer.toString().replace(':', '.'));
        incomingBytes = Metrics.counter(factory.createMetricName("IncomingBytes"));
        outgoingBytes= Metrics.counter(factory.createMetricName("OutgoingBytes"));
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
	<import
		resource="classpath:/com/easyjf/core/open-spring-transaction.xml" />
	<import resource="classpath:/com/easyjf/core/jpa-generic-dao.xml" />
	<import resource="dao.xml" />
	<import resource="service.xml" />

	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:db.properties</value>
			</list>
		</property>
	</bean>
</beans>


text:
package org.openqa.selenium.remote.server;

import static com.google.common.base.Preconditions.checkState;

import org.openqa.selenium.Capabilities;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class DefaultDriverFactory implements DriverFactory {
  private Map<Capabilities, Class<? extends WebDriver>> capabilitiesToDriver =
      new ConcurrentHashMap<Capabilities, Class<? extends WebDriver>>();

  public void registerDriver(Capabilities capabilities, Class<? extends WebDriver> implementation) {
    capabilitiesToDriver.put(capabilities, implementation);
  }

  protected Class<? extends WebDriver> getBestMatchFor(Capabilities desired) {
    // We won't be able to make a match if no drivers have been registered.
    checkState(!capabilitiesToDriver.isEmpty(),
        "No drivers have been registered, will be unable to match %s", desired);
    Capabilities bestMatchingCapabilities =
        CapabilitiesComparator.getBestMatch(desired, capabilitiesToDriver.keySet());
    return capabilitiesToDriver.get(bestMatchingCapabilities);
  }

  public WebDriver newInstance(Capabilities capabilities) {
    Class<? extends WebDriver> clazz = getBestMatchFor(capabilities);

    // Try and call the single arg constructor that takes a capabilities first
    return callConstructor(clazz, capabilities);
  }

  private WebDriver callConstructor(Class<? extends WebDriver> from, Capabilities capabilities) {
    try {
      Constructor<? extends WebDriver> constructor = from.getConstructor(Capabilities.class);
      return constructor.newInstance(capabilities);
    } catch (NoSuchMethodException e) {
      try {
        return from.newInstance();
      } catch (InstantiationException e1) {
        throw new WebDriverException(e);
      } catch (IllegalAccessException e1) {
        throw new WebDriverException(e);
      }
    } catch (InvocationTargetException e) {
      throw new WebDriverException(e);
    } catch (InstantiationException e) {
      throw new WebDriverException(e);
    } catch (IllegalAccessException e) {
      throw new WebDriverException(e);
    }
  }

  public boolean hasMappingFor(Capabilities capabilities) {
    return capabilitiesToDriver.containsKey(capabilities);
  }
}


text:
// oleerr.cpp : Defines error codes
//
#include "stdafx.h"
#include "PythonCOM.h"
#include "oaidl.h"
#include "olectl.h" // For connection point constants.

#ifdef MS_WINCE
extern "C" void WINAPIV NKDbgPrintfW(LPWSTR lpszFmt, ...);
#endif

static const WCHAR *szBadStringObject = L"<Bad String Object>";
extern PyObject *PyCom_InternalError;

void GetScodeString(SCODE sc, TCHAR *buf, int bufSize);
LPCTSTR GetScodeRangeString(SCODE sc);
LPCTSTR GetSeverityString(SCODE sc);
LPCTSTR GetFacilityString(SCODE sc);

static PyObject *PyCom_PyObjectFromIErrorInfo(IErrorInfo *, HRESULT errorhr);

static const char *traceback_prefix = "Traceback (most recent call last):\n";

// todo: nuke me!
PYCOM_EXPORT void PyCom_StreamMessage(const char *msg);

// Private helper to convert a "char *" to a BSTR for use in the error
// structures.
BSTR PyWin_String_AsBstr(const char *value)
{
	if (value==NULL || *value=='\0')
		return SysAllocStringLen(L"", 0);
	/* use MultiByteToWideChar() as a "good" strlen() */
	/* NOTE: this will include the null-term in the length */
	int cchWideChar = MultiByteToWideChar(CP_ACP, 0, value, -1, NULL, 0);

	/* alloc a temporary conversion buffer, but dont use alloca, as super
	   large strings will blow our stack */
	LPWSTR wstr = (LPWSTR)malloc(cchWideChar * sizeof(WCHAR));
	if (wstr==NULL) {
		PyErr_SetString(PyExc_MemoryError, "Not enough memory to allocate wide string buffer.");
		return NULL;
	}

	/* convert the input into the temporary buffer */
   	MultiByteToWideChar(CP_ACP, 0, value, -1, wstr, cchWideChar);

	/* don't place the null-term into the BSTR */
	BSTR ret = SysAllocStringLen(wstr, cchWideChar - 1);
	if (ret==NULL)
		PyErr_SetString(PyExc_MemoryError, "allocating BSTR");
	free(wstr);
	return ret;
}

////////////////////////////////////////////////////////////////////////
//
// Server Side Errors - translate a Python exception to COM error information
//
////////////////////////////////////////////////////////////////////////

// Generically fills an EXCEP_INFO.  The scode in the EXCEPINFO
// is the HRESULT as nominated by the user.
void PyCom_ExcepInfoFromPyException(EXCEPINFO *pExcepInfo)
{
	// If the caller did not provide a valid exception info, get out now!
	if (pExcepInfo==NULL) {
		PyErr_Clear(); // must leave Python in a clean state.
		return;
	}
	PyObject *exception, *v, *tb;
	PyErr_Fetch(&exception, &v, &tb);
	if (PyCom_ExcepInfoFromPyObject(v, pExcepInfo, NULL))
	{
		// done.
	}
	else
	{
		memset(pExcepInfo, 0, sizeof(EXCEPINFO));
		// Clear the exception raised by PyCom_ExcepInfoFromPyObject,
		// not the one we are interested in!
		PyErr_Clear();
		// Not a special exception object - do the best we can.
		char *szBaseMessage = "Unexpected Python Error: ";
		char *szException = GetPythonTraceback(exception, v, tb);
		size_t len = strlen(szBaseMessage) + strlen(szException) + 1;
		char *tempBuf = new char[len];
		if (tempBuf) {
			snprintf(tempBuf, len, "%s%s", szBaseMessage, szException);
			pExcepInfo->bstrDescription = PyWin_String_AsBstr(tempBuf);
			delete [] tempBuf;
		} else
			pExcepInfo->bstrDescription = SysAllocString(L"memory error allocating exception buffer!");
		pExcepInfo->bstrSource = SysAllocString(L"Python COM Server Internal Error");

		// Map some well known exceptions to specific HRESULTs
		// Note: v can be NULL. This can happen via PyErr_SetNone().
		//       e.g.: KeyboardInterrupt
		if (PyErr_GivenExceptionMatches(exception, PyExc_MemoryError))
			pExcepInfo->scode = E_OUTOFMEMORY;
		else
			// Any other common Python exceptions we should map?
			pExcepInfo->scode = E_FAIL;
	}
	Py_XDECREF(exception);
	Py_XDECREF(v);
	Py_XDECREF(tb);
	PyErr_Clear();
}

static BOOL PyCom_ExcepInfoFromServerExceptionInstance(PyObject *v, EXCEPINFO *pExcepInfo)
{
	BSTR temp;

	assert(v != NULL);
	assert(pExcepInfo != NULL);
	memset(pExcepInfo, 0, sizeof(EXCEPINFO));

	PyObject *ob = PyObject_GetAttrString(v, "description");
	if (ob && ob != Py_None) {
		if ( !PyWinObject_AsBstr(ob, &temp) )
			pExcepInfo->bstrDescription = SysAllocString(szBadStringObject);
		else
			pExcepInfo->bstrDescription = temp;
	} else {
		// No description - leave it empty.
		PyErr_Clear();
	}
	Py_XDECREF(ob);

	ob = PyObject_GetAttrString(v, "source");
	if (ob && ob != Py_None) {
		if ( !PyWinObject_AsBstr(ob, &temp) )
			pExcepInfo->bstrSource = SysAllocString(szBadStringObject);
		else
			pExcepInfo->bstrSource = temp;
	}
	else
		PyErr_Clear();
	Py_XDECREF(ob);

	ob = PyObject_GetAttrString(v, "helpfile");
	if (ob && ob != Py_None) {
		if ( !PyWinObject_AsBstr(ob, &temp) )
			pExcepInfo->bstrHelpFile = SysAllocString(szBadStringObject);
		else
			pExcepInfo->bstrHelpFile = temp;
	}
	else
		PyErr_Clear();
	Py_XDECREF(ob);

	ob = PyObject_GetAttrString(v, "code");
	if (ob && ob != Py_None) {
		PyObject *temp = PyNumber_Int(ob);
		if (temp) {
			pExcepInfo->wCode = (unsigned short)PyInt_AsLong(temp);
			Py_DECREF(temp);
		} // XXX - else - what to do here, apart from call the user a moron :-)
	}
	else
		PyErr_Clear();
	Py_XDECREF(ob);

	ob = PyObject_GetAttrString(v, "scode");
	if (ob && ob != Py_None) {
		PyObject *temp = PyNumber_Int(ob);
		if (temp) {
			pExcepInfo->scode = PyInt_AsLong(temp);
			Py_DECREF(temp);
		} else
			// XXX - again, should we call the user a moron?
			pExcepInfo->scode = E_FAIL;
	}
	else
		PyErr_Clear();
	Py_XDECREF(ob);

	ob = PyObject_GetAttrString(v, "helpcontext");
	if (ob && ob != Py_None) {
		PyObject *temp = PyNumber_Int(ob);
		if (temp) {
			pExcepInfo->dwHelpContext = (unsigned short)PyInt_AsLong(temp);
			Py_DECREF(temp);
		}
	}
	else
		PyErr_Clear();
	Py_XDECREF(ob);
	return TRUE;
}

// Fill an exception info from a specific COM error raised by the
// Python code.  If the Python exception is not a specific COM error
// (ie, pythoncom.com_error, or a COM server exception instance)
// then return FALSE.
BOOL PyCom_ExcepInfoFromPyObject(PyObject *v, EXCEPINFO *pExcepInfo, HRESULT *phresult)
{
	assert(pExcepInfo != NULL);
	if (v==NULL || pExcepInfo==NULL) {
		PyErr_SetString(PyExc_RuntimeError, "invalid arg to PyCom_ExcepInfoFromPyObject");
		return FALSE;
	}

	// New handling for 1.5 exceptions.
	if (!PyErr_GivenExceptionMatches(v, PyWinExc_COMError)) {
		PyErr_Format(PyExc_TypeError, "Must be a COM exception object (not '%s')", v->ob_type->tp_name);
		return FALSE;
	}

	// It is a COM exception, but may be a server or client instance.
	// Explicit check for client.
	// Note that with class based exceptions, a simple pointer check fails.
	// Any class sub-classed from the client is considered a server error,
	// so we need to check the class explicitly.
	if ((PyObject *)v->ob_type==PyWinExc_COMError) {
		// Client side error
		// Clear the state of the excep info.
		// use abstract API to get at details.
		memset(pExcepInfo, 0, sizeof(EXCEPINFO));
		PyObject *ob;
		if (phresult) {
			ob = PySequence_GetItem(v, 0);
			if (ob) {
				*phresult = PyInt_AsLong(ob);
				Py_DECREF(ob);
			}
		}
		// item[1] is the scode description, which we dont need.
		ob = PySequence_GetItem(v, 2);
		if (ob) {
			int code, helpContext, scode;
			const char *source, *description, *helpFile;
			if ( !PyArg_ParseTuple(ob, "izzzii:ExceptionInfo",
								   &code,
								   &source,
								   &description,
								   &helpFile,
								   &helpContext,
								   &scode) ) {
				Py_DECREF(ob);
				PyErr_Clear();
				PyErr_SetString(PyExc_TypeError, "The inner exception tuple must be of format 'izzzii'");
				return FALSE;
			}
			pExcepInfo->wCode = code;
			pExcepInfo->wReserved = 0;
			pExcepInfo->bstrSource = PyWin_String_AsBstr(source);
			pExcepInfo->bstrDescription = PyWin_String_AsBstr(description);
			pExcepInfo->bstrHelpFile = PyWin_String_AsBstr(helpFile);
			pExcepInfo->dwHelpContext = helpContext;
			pExcepInfo->pvReserved = 0;
			pExcepInfo->pfnDeferredFillIn = NULL;
			pExcepInfo->scode = scode;
			Py_DECREF(ob);
		}
		return TRUE;
	} else {
		// Server side error
		BOOL ok = PyCom_ExcepInfoFromServerExceptionInstance(v, pExcepInfo);
		if (ok && phresult)
			*phresult = pExcepInfo->scode;
		return ok;
	}
}

// Given an EXCEPINFO, register the error information with the
// IErrorInfo interface.
BOOL PyCom_SetCOMErrorFromExcepInfo(const EXCEPINFO *pexcepinfo, REFIID riid)
{
	ICreateErrorInfo *pICEI;
	HRESULT hr = CreateErrorInfo(&pICEI);
	if ( SUCCEEDED(hr) )
	{
		pICEI->SetGUID(riid);
		pICEI->SetHelpContext(pexcepinfo->dwHelpContext);
		if ( pexcepinfo->bstrDescription )
			pICEI->SetDescription(pexcepinfo->bstrDescription);
		if ( pexcepinfo->bstrHelpFile )
			pICEI->SetHelpFile(pexcepinfo->bstrHelpFile);
		if ( pexcepinfo->bstrSource )
			pICEI->SetSource(pexcepinfo->bstrSource);

		IErrorInfo *pIEI;
		Py_BEGIN_ALLOW_THREADS
		hr = pICEI->QueryInterface(IID_IErrorInfo, (LPVOID*) &pIEI);
		Py_END_ALLOW_THREADS
		if ( SUCCEEDED(hr) )
		{
			SetErrorInfo(0, pIEI);
			pIEI->Release();
		}
		pICEI->Release();
	}
	return SUCCEEDED(hr);
}

void PyCom_CleanupExcepInfo(EXCEPINFO *pexcepinfo)
{
	if ( pexcepinfo->bstrDescription ) {
		SysFreeString(pexcepinfo->bstrDescription);
		pexcepinfo->bstrDescription = NULL;
	}
	if ( pexcepinfo->bstrHelpFile ) {
		SysFreeString(pexcepinfo->bstrHelpFile);
		pexcepinfo->bstrHelpFile = NULL;
	}
	if ( pexcepinfo->bstrSource ) {
		SysFreeString(pexcepinfo->bstrSource);
		pexcepinfo->bstrSource = NULL;
	}
}

HRESULT PyCom_SetCOMErrorFromSimple(HRESULT hr, REFIID riid /* = IID_NULL */, const char *description /* = NULL*/)
{
	// fast path...
	if ( hr == S_OK )
		return S_OK;

	// If you specify a description you should also specify the IID
	assert(riid != IID_NULL || description==NULL);
	// Reset the error info for this thread.  "Inside OLE2" says we
	// can call IErrorInfo with NULL, but the COM documentation doesnt mention it.
	BSTR bstrDesc = NULL;
	if (description) bstrDesc = PyWin_String_AsBstr(description);

	EXCEPINFO einfo = {
		0,		// wCode
		0,		// wReserved
		NULL,	// bstrSource
		bstrDesc,	// bstrDescription
		NULL,	// bstrHelpFile
		0,		// dwHelpContext
		NULL,	// pvReserved
		NULL,	// pfnDeferredFillIn
		hr		// scode
	};
	HRESULT ret = PyCom_SetCOMErrorFromExcepInfo(&einfo, riid);
	PyCom_CleanupExcepInfo(&einfo);
	return ret;
}

PYCOM_EXPORT HRESULT PyCom_SetCOMErrorFromPyException(REFIID riid /* = IID_NULL */)
{
	if (!PyErr_Occurred())
		// No error occurred
		return S_OK;

	// These errors are generally 'unexpected' (ie, errors converting args on
	// the way into a gateway method.  If not explicitly raised by the user,
	// log it.
	PyCom_LoggerNonServerException(NULL, "Unexpected gateway error");

	EXCEPINFO einfo;
	PyCom_ExcepInfoFromPyException(&einfo);

	// force this to a failure just in case we couldn't extract a proper
	// error value
	if ( einfo.scode == S_OK )
		einfo.scode = E_FAIL;

	PyCom_SetCOMErrorFromExcepInfo(&einfo, riid);
	PyCom_CleanupExcepInfo(&einfo);
	return einfo.scode;
}

PYCOM_EXPORT HRESULT PyCom_SetAndLogCOMErrorFromPyException(const char *methodName, REFIID riid /* = IID_NULL */)
{
	if (!PyErr_Occurred())
		// No error occurred
		return S_OK;
	PyCom_LoggerNonServerException(NULL, "Unexpected exception in gateway method '%s'", methodName);
	return PyCom_SetCOMErrorFromPyException(riid);
}

PYCOM_EXPORT HRESULT PyCom_SetAndLogCOMErrorFromPyExceptionEx(PyObject *provider, const char *methodName, REFIID riid /* = IID_NULL */)
{
	if (!PyErr_Occurred())
		// No error occurred
		return S_OK;
	PyCom_LoggerNonServerException(provider, "Unexpected exception in gateway method '%s'", methodName);
	return PyCom_SetCOMErrorFromPyException(riid);
}

void PyCom_StreamMessage(const char *pszMessageText)
{
#ifndef MS_WINCE
	OutputDebugStringA(pszMessageText);
#else
	NKDbgPrintfW(pszMessageText);
#endif
	// PySys_WriteStderr has an internal 1024 limit due to varargs.
	// weve already resolved them, so we gotta do it the hard way
	// We can't afford to screw with the Python exception state
	PyObject *typ, *val, *tb;
	PyErr_Fetch(&typ, &val, &tb);
	PyObject *pyfile = PySys_GetObject("stderr");
	if (pyfile)
		if (PyFile_WriteString((char *)pszMessageText, pyfile)!=0)
			// eeek - Python error writing this error - write it to stdout.
			fprintf(stdout, "%s", pszMessageText);
	PyErr_Restore(typ, val, tb);
}

BOOL VLogF_Logger(PyObject *logger, const char *log_method,
				  const char *prefix, const char *fmt, va_list argptr)
{
	// Protected by Python lock
	static char buff[8196];
	size_t buf_len = sizeof(buff) / sizeof(buff[0]);
	size_t prefix_len = strlen(prefix);
	strncpy(buff, prefix, buf_len);
	vsnprintf(buff+prefix_len, buf_len-prefix_len, fmt, argptr);

	PyObject *exc_typ = NULL, *exc_val = NULL, *exc_tb = NULL;
	PyErr_Fetch( &exc_typ, &exc_val, &exc_tb);

	// Python 2.3 has an issue in that attempting to make the call with
	// an exception set causes the call itself to fail - but
	// 2.3's logger provides no way of passing the exception!
	// We make no attempt to worm around this - if you really want this feature
	// in Python 2.3, simply use the Python 2.4 logging package (or at least
	// a logger from that package)
	PyObject *kw = PyDict_New();
	if (kw && exc_typ) {
		PyObject *exc_info = Py_BuildValue("OOO", exc_typ,
		                                   exc_val ? exc_val : Py_None,
		                                   exc_tb ? exc_tb : Py_None);
		PyDict_SetItemString(kw, "exc_info", exc_info);
		Py_XDECREF(exc_info);
	}
	PyObject *args = Py_BuildValue("(s)", buff);
	PyObject *method = PyObject_GetAttrString(logger, (char *)log_method);
	PyObject *result = NULL;
	if (method && kw && args)
		result = PyObject_Call(method, args, kw);
	Py_XDECREF(method);
	Py_XDECREF(kw);
	Py_XDECREF(args);
	if (!result)
		PyErr_Print();
	BOOL rc = result != NULL;
	Py_XDECREF(result);
	PyErr_Restore( exc_typ, exc_val, exc_tb);
	return rc;
}

void VLogF(const char *fmt, va_list argptr)
{
	static char buff[8196]; // protected by Python lock

	vsnprintf(buff, 8196, fmt, argptr);

	PyCom_StreamMessage(buff);
}

void PyCom_LogF(const char *fmt, ...)
{
	va_list marker;

	va_start(marker, fmt);
	VLogF(fmt, marker);
	PyCom_StreamMessage("\n");
}

void _LogException(PyObject *exc_typ, PyObject *exc_val, PyObject *exc_tb)
{
	char *szTraceback = GetPythonTraceback(exc_typ, exc_val, exc_tb);
	PyCom_StreamMessage(szTraceback);
	free(szTraceback);
}

// XXX - _DoLogError() was a really bad name in retrospect, given
// the "logger" module and my dumb choice of _DoLogger() for logger errors :)
// Thankfully both are private.
static void _DoLogError(const char *prefix, const char *fmt, va_list argptr)
{
	PyCom_StreamMessage(prefix);
	VLogF(fmt, argptr);
	PyCom_StreamMessage("\n");
	// If we have a Python exception, also log that:
	PyObject *exc_typ = NULL, *exc_val = NULL, *exc_tb = NULL;
	PyErr_Fetch( &exc_typ, &exc_val, &exc_tb);
	if (exc_typ) {
		PyErr_NormalizeException( &exc_typ, &exc_val, &exc_tb);
		PyCom_StreamMessage("\n");
		_LogException(exc_typ, exc_val, exc_tb);
	}
	PyErr_Restore(exc_typ, exc_val, exc_tb);
}

static void _DoLogger(PyObject *logProvider, char *log_method, const char *fmt, va_list argptr)
{
	CEnterLeavePython _celp;
	PyObject *exc_typ = NULL, *exc_val = NULL, *exc_tb = NULL;
	PyErr_Fetch( &exc_typ, &exc_val, &exc_tb);
	PyObject *logger = NULL;
	char prefix[128];
	strcpy(prefix, "pythoncom ");
	strncat(prefix, log_method, 100);
	strncat(prefix, ": ", 2);

	if (logProvider)
		logger = PyObject_CallMethod(logProvider, "_GetLogger_", NULL);
	if (logger == NULL) {
		PyObject *mod = PyImport_ImportModule("win32com");
		if (mod) {
			logger = PyObject_GetAttrString(mod, "logger");
			Py_DECREF(mod);
		}
	}
	// Returning a logger of None means "no logger"
	if (logger == Py_None) {
		Py_DECREF(logger);
		logger = NULL;
	}
	PyErr_Restore(exc_typ, exc_val, exc_tb);
	if (!logger ||
		!VLogF_Logger(logger, log_method, prefix, fmt, argptr))
		// No logger, or logger error - normal stdout stream.
		_DoLogError(prefix, fmt, argptr);
	Py_XDECREF(logger);
}

// Is the current exception a "server" exception? - ie, one explicitly
// thrown by Python code to indicate an error.  This is defined as
// any exception whose type is a subclass of com_error (a plain
// com_error probably means an unhandled exception from someone
// calling an interface)
BOOL IsServerErrorCurrent() {
	BOOL rc = FALSE;
	PyObject *exc_typ = NULL, *exc_val = NULL, *exc_tb = NULL;
	PyErr_Fetch( &exc_typ, &exc_val, &exc_tb);
	assert(exc_typ); // we should only be called with an exception current.
	if (exc_typ) {
		PyErr_NormalizeException( &exc_typ, &exc_val, &exc_tb);
		// so it must "match" a com_error, but not be *exactly* a COM error.
		rc = PyErr_GivenExceptionMatches(exc_val, PyWinExc_COMError) && exc_typ != PyWinExc_COMError;
	}
	PyErr_Restore(exc_typ, exc_val, exc_tb);
	return rc;
}

PYCOM_EXPORT void PyCom_LoggerException(PyObject *logProvider, const char *fmt, ...)
{
	va_list marker;
	va_start(marker, fmt);
	_DoLogger(logProvider, "error", fmt, marker);
}

PYCOM_EXPORT void PyCom_LoggerWarning(PyObject *logProvider, const char *fmt, ...)
{
	va_list marker;
	va_start(marker, fmt);
	_DoLogger(logProvider, "warning", fmt, marker);
}

PYCOM_EXPORT
void PyCom_LoggerNonServerException(PyObject *logProvider, const char *fmt, ...)
{
	if (IsServerErrorCurrent())
		return;
	va_list marker;
	va_start(marker, fmt);
	_DoLogger(logProvider, "error", fmt, marker);
}

////////////////////////////////////////////////////////////////////////
//
// Client Side Errors - translate a COM failure to a Python exception
//
////////////////////////////////////////////////////////////////////////
PyObject *PyCom_BuildPyException(HRESULT errorhr, IUnknown *pUnk /* = NULL */, REFIID iid /* = IID_NULL */)
{
	PyObject *obEI = NULL;
	TCHAR scodeStringBuf[512];
	GetScodeString(errorhr, scodeStringBuf, sizeof(scodeStringBuf)/sizeof(scodeStringBuf[0]));

#ifndef MS_WINCE // WINCE doesnt appear to have GetErrorInfo() - compiled, but doesnt link!
	if (pUnk != NULL) {
		assert(iid != IID_NULL); // If you pass an IUnknown, you should pass the specific IID.
		// See if it supports error info.
		ISupportErrorInfo *pSEI;
		HRESULT hr;
		Py_BEGIN_ALLOW_THREADS
		hr = pUnk->QueryInterface(IID_ISupportErrorInfo, (void **)&pSEI);
		if (SUCCEEDED(hr)) {
			hr = pSEI->InterfaceSupportsErrorInfo(iid);
			pSEI->Release(); // Finished with this object
		}
		Py_END_ALLOW_THREADS
		if (SUCCEEDED(hr)) {
			IErrorInfo *pEI;
			Py_BEGIN_ALLOW_THREADS
			hr=GetErrorInfo(0, &pEI);
			Py_END_ALLOW_THREADS
			if (hr==S_OK) {
				obEI = PyCom_PyObjectFromIErrorInfo(pEI, errorhr);
				PYCOM_RELEASE(pEI);
			}
		}
	}
#endif // MS_WINCE
	if (obEI==NULL)	{
		obEI = Py_None;
		Py_INCREF(Py_None);
	}
	PyObject *evalue = Py_BuildValue("iNOO", errorhr, PyWinObject_FromTCHAR(scodeStringBuf), obEI, Py_None);
	Py_DECREF(obEI);

	PyErr_SetObject(PyWinExc_COMError, evalue);
	Py_XDECREF(evalue);
	return NULL;
}

// Uses the HRESULT and an EXCEPINFO structure to create and
// set a pythoncom.com_error.
// Used rarely - currently by IDispatch and IActiveScriptParse* interfaces.
PyObject* PyCom_BuildPyExceptionFromEXCEPINFO(HRESULT hr, EXCEPINFO *pexcepInfo /* = NULL */, UINT nArgErr /* = -1 */)
{
	TCHAR buf[512];
	GetScodeString(hr, buf, sizeof(buf)/sizeof(TCHAR));
	PyObject *obScodeString = PyWinObject_FromTCHAR(buf);
	PyObject *evalue;
	PyObject *obArg;

	if ( nArgErr != -1 ) {
		obArg = PyInt_FromLong(nArgErr);
	} else {
		obArg = Py_None;
		Py_INCREF(obArg);
	}
	if (pexcepInfo==NULL)
	{
		evalue = Py_BuildValue("iOzO", hr, obScodeString, NULL, obArg);
	}
	else
	{
		PyObject *obExcepInfo = PyCom_PyObjectFromExcepInfo(pexcepInfo);
		if ( obExcepInfo )
		{
			evalue = Py_BuildValue("iOOO", hr, obScodeString, obExcepInfo, obArg);
			Py_DECREF(obExcepInfo);
		}
		else
			evalue = NULL;

		/* done with the exception, free it */
		PyCom_CleanupExcepInfo(pexcepInfo);
	}
	Py_DECREF(obArg);
	PyErr_SetObject(PyWinExc_COMError, evalue);
	Py_XDECREF(evalue);
	Py_XDECREF(obScodeString);
	return NULL;
}

PyObject* PyCom_BuildInternalPyException(char *msg)
{
	PyErr_SetString(PyCom_InternalError, msg);
	return NULL;
}

PyObject *PyCom_PyObjectFromExcepInfo(const EXCEPINFO *pexcepInfo)
{
	EXCEPINFO filledIn;

	// Do a deferred fill-in if necessary
	if ( pexcepInfo->pfnDeferredFillIn )
	{
		filledIn = *pexcepInfo;
		(*pexcepInfo->pfnDeferredFillIn)(&filledIn);
		pexcepInfo = &filledIn;
	}

	 // ### should these by PyUnicode values?  Still strings for compatibility.
	PyObject *obSource = PyWinObject_FromBstr(pexcepInfo->bstrSource);
	PyObject *obDescription = PyWinObject_FromBstr(pexcepInfo->bstrDescription);
	PyObject *obHelpFile = PyWinObject_FromBstr(pexcepInfo->bstrHelpFile);
	PyObject *rc = Py_BuildValue("iOOOii",
						 (int)pexcepInfo->wCode,
						 obSource,
						 obDescription,
						 obHelpFile,
						 (int)pexcepInfo->dwHelpContext,
						 (int)pexcepInfo->scode);
	Py_XDECREF(obSource);
	Py_XDECREF(obDescription);
	Py_XDECREF(obHelpFile);
	return rc;
}

// NOTE - This MUST return the same object format as the above function
static PyObject *PyCom_PyObjectFromIErrorInfo(IErrorInfo *pEI, HRESULT errorhr)
{
	BSTR desc;
	BSTR source;
	BSTR helpfile;
	PyObject *obDesc;
	PyObject *obSource;
	PyObject *obHelpFile;

	HRESULT hr;

	Py_BEGIN_ALLOW_THREADS
	hr=pEI->GetDescription(&desc);
	Py_END_ALLOW_THREADS
	if (hr!=S_OK) {
		obDesc = Py_None;
		Py_INCREF(obDesc);
	} else {
		obDesc = MakeBstrToObj(desc);
		SysFreeString(desc);
	}

	Py_BEGIN_ALLOW_THREADS
	hr=pEI->GetSource(&source);
	Py_END_ALLOW_THREADS
	if (hr!=S_OK) {
		obSource = Py_None;
		Py_INCREF(obSource);
	} else {
		obSource = MakeBstrToObj(source);
		SysFreeString(source);
	}
	Py_BEGIN_ALLOW_THREADS
	hr=pEI->GetHelpFile(&helpfile);
	Py_END_ALLOW_THREADS
	if (hr!=S_OK) {
		obHelpFile = Py_None;
		Py_INCREF(obHelpFile);
	} else {
		obHelpFile = MakeBstrToObj(helpfile);
		SysFreeString(helpfile);
	}
	DWORD helpContext = 0;
	pEI->GetHelpContext(&helpContext);
	PyObject *ret = Py_BuildValue("iOOOii",
						 0, // wCode remains zero, as scode holds our data.
						 // ### should these by PyUnicode values?
						 obSource,
						 obDesc,
						 obHelpFile,
						 (int)helpContext,
						 errorhr);
	Py_XDECREF(obSource);
	Py_XDECREF(obDesc);
	Py_XDECREF(obHelpFile);
	return ret;
}

////////////////////////////////////////////////////////////////////////
//
// Error string helpers - get SCODE, FACILITY etc strings
//
////////////////////////////////////////////////////////////////////////
#ifndef _countof
#define _countof(array) (sizeof(array)/sizeof(array[0]))
#endif

void GetScodeString(HRESULT hr, LPTSTR buf, int bufSize)
{
	struct HRESULT_ENTRY
	{
		HRESULT hr;
		LPCTSTR lpszName;
	};
	#define MAKE_HRESULT_ENTRY(hr)    { hr, _T(#hr) }
	static const HRESULT_ENTRY hrNameTable[] =
	{
		MAKE_HRESULT_ENTRY(S_OK),
		MAKE_HRESULT_ENTRY(S_FALSE),

		MAKE_HRESULT_ENTRY(CACHE_S_FORMATETC_NOTSUPPORTED),
		MAKE_HRESULT_ENTRY(CACHE_S_SAMECACHE),
		MAKE_HRESULT_ENTRY(CACHE_S_SOMECACHES_NOTUPDATED),
		MAKE_HRESULT_ENTRY(CONVERT10_S_NO_PRESENTATION),
		MAKE_HRESULT_ENTRY(DATA_S_SAMEFORMATETC),
		MAKE_HRESULT_ENTRY(DRAGDROP_S_CANCEL),
		MAKE_HRESULT_ENTRY(DRAGDROP_S_DROP),
		MAKE_HRESULT_ENTRY(DRAGDROP_S_USEDEFAULTCURSORS),
		MAKE_HRESULT_ENTRY(INPLACE_S_TRUNCATED),
		MAKE_HRESULT_ENTRY(MK_S_HIM),
		MAKE_HRESULT_ENTRY(MK_S_ME),
		MAKE_HRESULT_ENTRY(MK_S_MONIKERALREADYREGISTERED),
		MAKE_HRESULT_ENTRY(MK_S_REDUCED_TO_SELF),
		MAKE_HRESULT_ENTRY(MK_S_US),
		MAKE_HRESULT_ENTRY(OLE_S_MAC_CLIPFORMAT),
		MAKE_HRESULT_ENTRY(OLE_S_STATIC),
		MAKE_HRESULT_ENTRY(OLE_S_USEREG),
		MAKE_HRESULT_ENTRY(OLEOBJ_S_CANNOT_DOVERB_NOW),
		MAKE_HRESULT_ENTRY(OLEOBJ_S_INVALIDHWND),
		MAKE_HRESULT_ENTRY(OLEOBJ_S_INVALIDVERB),
		MAKE_HRESULT_ENTRY(OLEOBJ_S_LAST),
		MAKE_HRESULT_ENTRY(STG_S_CONVERTED),
		MAKE_HRESULT_ENTRY(VIEW_S_ALREADY_FROZEN),

		MAKE_HRESULT_ENTRY(E_UNEXPECTED),
		MAKE_HRESULT_ENTRY(E_NOTIMPL),
		MAKE_HRESULT_ENTRY(E_OUTOFMEMORY),
		MAKE_HRESULT_ENTRY(E_INVALIDARG),
		MAKE_HRESULT_ENTRY(E_NOINTERFACE),
		MAKE_HRESULT_ENTRY(E_POINTER),
		MAKE_HRESULT_ENTRY(E_HANDLE),
		MAKE_HRESULT_ENTRY(E_ABORT),
		MAKE_HRESULT_ENTRY(E_FAIL),
		MAKE_HRESULT_ENTRY(E_ACCESSDENIED),

		MAKE_HRESULT_ENTRY(CACHE_E_NOCACHE_UPDATED),
		MAKE_HRESULT_ENTRY(CLASS_E_CLASSNOTAVAILABLE),
		MAKE_HRESULT_ENTRY(CLASS_E_NOAGGREGATION),
		MAKE_HRESULT_ENTRY(CLIPBRD_E_BAD_DATA),
		MAKE_HRESULT_ENTRY(CLIPBRD_E_CANT_CLOSE),
		MAKE_HRESULT_ENTRY(CLIPBRD_E_CANT_EMPTY),
		MAKE_HRESULT_ENTRY(CLIPBRD_E_CANT_OPEN),
		MAKE_HRESULT_ENTRY(CLIPBRD_E_CANT_SET),
		MAKE_HRESULT_ENTRY(CO_E_ALREADYINITIALIZED),
		MAKE_HRESULT_ENTRY(CO_E_APPDIDNTREG),
		MAKE_HRESULT_ENTRY(CO_E_APPNOTFOUND),
		MAKE_HRESULT_ENTRY(CO_E_APPSINGLEUSE),
		MAKE_HRESULT_ENTRY(CO_E_BAD_PATH),
		MAKE_HRESULT_ENTRY(CO_E_CANTDETERMINECLASS),
		MAKE_HRESULT_ENTRY(CO_E_CLASS_CREATE_FAILED),
		MAKE_HRESULT_ENTRY(CO_E_CLASSSTRING),
		MAKE_HRESULT_ENTRY(CO_E_DLLNOTFOUND),
		MAKE_HRESULT_ENTRY(CO_E_ERRORINAPP),
		MAKE_HRESULT_ENTRY(CO_E_ERRORINDLL),
		MAKE_HRESULT_ENTRY(CO_E_IIDSTRING),
		MAKE_HRESULT_ENTRY(CO_E_NOTINITIALIZED),
		MAKE_HRESULT_ENTRY(CO_E_OBJISREG),
		MAKE_HRESULT_ENTRY(CO_E_OBJNOTCONNECTED),
		MAKE_HRESULT_ENTRY(CO_E_OBJNOTREG),
		MAKE_HRESULT_ENTRY(CO_E_OBJSRV_RPC_FAILURE),
		MAKE_HRESULT_ENTRY(CO_E_SCM_ERROR),
		MAKE_HRESULT_ENTRY(CO_E_SCM_RPC_FAILURE),
		MAKE_HRESULT_ENTRY(CO_E_SERVER_EXEC_FAILURE),
		MAKE_HRESULT_ENTRY(CO_E_SERVER_STOPPING),
		MAKE_HRESULT_ENTRY(CO_E_WRONGOSFORAPP),
		MAKE_HRESULT_ENTRY(CONVERT10_E_OLESTREAM_BITMAP_TO_DIB),
		MAKE_HRESULT_ENTRY(CONVERT10_E_OLESTREAM_FMT),
		MAKE_HRESULT_ENTRY(CONVERT10_E_OLESTREAM_GET),
		MAKE_HRESULT_ENTRY(CONVERT10_E_OLESTREAM_PUT),
		MAKE_HRESULT_ENTRY(CONVERT10_E_STG_DIB_TO_BITMAP),
		MAKE_HRESULT_ENTRY(CONVERT10_E_STG_FMT),
		MAKE_HRESULT_ENTRY(CONVERT10_E_STG_NO_STD_STREAM),
		MAKE_HRESULT_ENTRY(DISP_E_ARRAYISLOCKED),
		MAKE_HRESULT_ENTRY(DISP_E_BADCALLEE),
		MAKE_HRESULT_ENTRY(DISP_E_BADINDEX),
		MAKE_HRESULT_ENTRY(DISP_E_BADPARAMCOUNT),
		MAKE_HRESULT_ENTRY(DISP_E_BADVARTYPE),
		MAKE_HRESULT_ENTRY(DISP_E_EXCEPTION),
		MAKE_HRESULT_ENTRY(DISP_E_MEMBERNOTFOUND),
		MAKE_HRESULT_ENTRY(DISP_E_NONAMEDARGS),
		MAKE_HRESULT_ENTRY(DISP_E_NOTACOLLECTION),
		MAKE_HRESULT_ENTRY(DISP_E_OVERFLOW),
		MAKE_HRESULT_ENTRY(DISP_E_PARAMNOTFOUND),
		MAKE_HRESULT_ENTRY(DISP_E_PARAMNOTOPTIONAL),
		MAKE_HRESULT_ENTRY(DISP_E_TYPEMISMATCH),
		MAKE_HRESULT_ENTRY(DISP_E_UNKNOWNINTERFACE),
		MAKE_HRESULT_ENTRY(DISP_E_UNKNOWNLCID),
		MAKE_HRESULT_ENTRY(DISP_E_UNKNOWNNAME),
		MAKE_HRESULT_ENTRY(DRAGDROP_E_ALREADYREGISTERED),
		MAKE_HRESULT_ENTRY(DRAGDROP_E_INVALIDHWND),
		MAKE_HRESULT_ENTRY(DRAGDROP_E_NOTREGISTERED),
		MAKE_HRESULT_ENTRY(DV_E_CLIPFORMAT),
		MAKE_HRESULT_ENTRY(DV_E_DVASPECT),
		MAKE_HRESULT_ENTRY(DV_E_DVTARGETDEVICE),
		MAKE_HRESULT_ENTRY(DV_E_DVTARGETDEVICE_SIZE),
		MAKE_HRESULT_ENTRY(DV_E_FORMATETC),
		MAKE_HRESULT_ENTRY(DV_E_LINDEX),
		MAKE_HRESULT_ENTRY(DV_E_NOIVIEWOBJECT),
		MAKE_HRESULT_ENTRY(DV_E_STATDATA),
		MAKE_HRESULT_ENTRY(DV_E_STGMEDIUM),
		MAKE_HRESULT_ENTRY(DV_E_TYMED),
		MAKE_HRESULT_ENTRY(INPLACE_E_NOTOOLSPACE),
		MAKE_HRESULT_ENTRY(INPLACE_E_NOTUNDOABLE),
		MAKE_HRESULT_ENTRY(MEM_E_INVALID_LINK),
		MAKE_HRESULT_ENTRY(MEM_E_INVALID_ROOT),
		MAKE_HRESULT_ENTRY(MEM_E_INVALID_SIZE),
		MAKE_HRESULT_ENTRY(MK_E_CANTOPENFILE),
		MAKE_HRESULT_ENTRY(MK_E_CONNECTMANUALLY),
		MAKE_HRESULT_ENTRY(MK_E_ENUMERATION_FAILED),
		MAKE_HRESULT_ENTRY(MK_E_EXCEEDEDDEADLINE),
		MAKE_HRESULT_ENTRY(MK_E_INTERMEDIATEINTERFACENOTSUPPORTED),
		MAKE_HRESULT_ENTRY(MK_E_INVALIDEXTENSION),
		MAKE_HRESULT_ENTRY(MK_E_MUSTBOTHERUSER),
		MAKE_HRESULT_ENTRY(MK_E_NEEDGENERIC),
		MAKE_HRESULT_ENTRY(MK_E_NO_NORMALIZED),
		MAKE_HRESULT_ENTRY(MK_E_NOINVERSE),
		MAKE_HRESULT_ENTRY(MK_E_NOOBJECT),
		MAKE_HRESULT_ENTRY(MK_E_NOPREFIX),
		MAKE_HRESULT_ENTRY(MK_E_NOSTORAGE),
		MAKE_HRESULT_ENTRY(MK_E_NOTBINDABLE),
		MAKE_HRESULT_ENTRY(MK_E_NOTBOUND),
		MAKE_HRESULT_ENTRY(MK_E_SYNTAX),
		MAKE_HRESULT_ENTRY(MK_E_UNAVAILABLE),
		MAKE_HRESULT_ENTRY(OLE_E_ADVF),
		MAKE_HRESULT_ENTRY(OLE_E_ADVISENOTSUPPORTED),
		MAKE_HRESULT_ENTRY(OLE_E_BLANK),
		MAKE_HRESULT_ENTRY(OLE_E_CANT_BINDTOSOURCE),
		MAKE_HRESULT_ENTRY(OLE_E_CANT_GETMONIKER),
		MAKE_HRESULT_ENTRY(OLE_E_CANTCONVERT),
		MAKE_HRESULT_ENTRY(OLE_E_CLASSDIFF),
		MAKE_HRESULT_ENTRY(OLE_E_ENUM_NOMORE),
		MAKE_HRESULT_ENTRY(OLE_E_INVALIDHWND),
		MAKE_HRESULT_ENTRY(OLE_E_INVALIDRECT),
		MAKE_HRESULT_ENTRY(OLE_E_NOCACHE),
		MAKE_HRESULT_ENTRY(OLE_E_NOCONNECTION),
		MAKE_HRESULT_ENTRY(OLE_E_NOSTORAGE),
		MAKE_HRESULT_ENTRY(OLE_E_NOT_INPLACEACTIVE),
		MAKE_HRESULT_ENTRY(OLE_E_NOTRUNNING),
		MAKE_HRESULT_ENTRY(OLE_E_OLEVERB),
		MAKE_HRESULT_ENTRY(OLE_E_PROMPTSAVECANCELLED),
		MAKE_HRESULT_ENTRY(OLE_E_STATIC),
		MAKE_HRESULT_ENTRY(OLE_E_WRONGCOMPOBJ),
		MAKE_HRESULT_ENTRY(OLEOBJ_E_INVALIDVERB),
		MAKE_HRESULT_ENTRY(OLEOBJ_E_NOVERBS),
		MAKE_HRESULT_ENTRY(REGDB_E_CLASSNOTREG),
		MAKE_HRESULT_ENTRY(REGDB_E_IIDNOTREG),
		MAKE_HRESULT_ENTRY(REGDB_E_INVALIDVALUE),
		MAKE_HRESULT_ENTRY(REGDB_E_KEYMISSING),
		MAKE_HRESULT_ENTRY(REGDB_E_READREGDB),
		MAKE_HRESULT_ENTRY(REGDB_E_WRITEREGDB),
		MAKE_HRESULT_ENTRY(RPC_E_ATTEMPTED_MULTITHREAD),
		MAKE_HRESULT_ENTRY(RPC_E_CALL_CANCELED),
		MAKE_HRESULT_ENTRY(RPC_E_CALL_REJECTED),
		MAKE_HRESULT_ENTRY(RPC_E_CANTCALLOUT_AGAIN),
		MAKE_HRESULT_ENTRY(RPC_E_CANTCALLOUT_INASYNCCALL),
		MAKE_HRESULT_ENTRY(RPC_E_CANTCALLOUT_INEXTERNALCALL),
		MAKE_HRESULT_ENTRY(RPC_E_CANTCALLOUT_ININPUTSYNCCALL),
		MAKE_HRESULT_ENTRY(RPC_E_CANTPOST_INSENDCALL),
		MAKE_HRESULT_ENTRY(RPC_E_CANTTRANSMIT_CALL),
		MAKE_HRESULT_ENTRY(RPC_E_CHANGED_MODE),
		MAKE_HRESULT_ENTRY(RPC_E_CLIENT_CANTMARSHAL_DATA),
		MAKE_HRESULT_ENTRY(RPC_E_CLIENT_CANTUNMARSHAL_DATA),
		MAKE_HRESULT_ENTRY(RPC_E_CLIENT_DIED),
		MAKE_HRESULT_ENTRY(RPC_E_CONNECTION_TERMINATED),
		MAKE_HRESULT_ENTRY(RPC_E_DISCONNECTED),
		MAKE_HRESULT_ENTRY(RPC_E_FAULT),
		MAKE_HRESULT_ENTRY(RPC_E_INVALID_CALLDATA),
		MAKE_HRESULT_ENTRY(RPC_E_INVALID_DATA),
		MAKE_HRESULT_ENTRY(RPC_E_INVALID_DATAPACKET),
		MAKE_HRESULT_ENTRY(RPC_E_INVALID_PARAMETER),
		MAKE_HRESULT_ENTRY(RPC_E_INVALIDMETHOD),
		MAKE_HRESULT_ENTRY(RPC_E_NOT_REGISTERED),
		MAKE_HRESULT_ENTRY(RPC_E_OUT_OF_RESOURCES),
		MAKE_HRESULT_ENTRY(RPC_E_RETRY),
		MAKE_HRESULT_ENTRY(RPC_E_SERVER_CANTMARSHAL_DATA),
		MAKE_HRESULT_ENTRY(RPC_E_SERVER_CANTUNMARSHAL_DATA),
		MAKE_HRESULT_ENTRY(RPC_E_SERVER_DIED),
		MAKE_HRESULT_ENTRY(RPC_E_SERVER_DIED_DNE),
		MAKE_HRESULT_ENTRY(RPC_E_SERVERCALL_REJECTED),
		MAKE_HRESULT_ENTRY(RPC_E_SERVERCALL_RETRYLATER),
		MAKE_HRESULT_ENTRY(RPC_E_SERVERFAULT),
		MAKE_HRESULT_ENTRY(RPC_E_SYS_CALL_FAILED),
		MAKE_HRESULT_ENTRY(RPC_E_THREAD_NOT_INIT),
		MAKE_HRESULT_ENTRY(RPC_E_UNEXPECTED),
		MAKE_HRESULT_ENTRY(RPC_E_WRONG_THREAD),
		MAKE_HRESULT_ENTRY(STG_E_ABNORMALAPIEXIT),
		MAKE_HRESULT_ENTRY(STG_E_ACCESSDENIED),
		MAKE_HRESULT_ENTRY(STG_E_CANTSAVE),
		MAKE_HRESULT_ENTRY(STG_E_DISKISWRITEPROTECTED),
		MAKE_HRESULT_ENTRY(STG_E_EXTANTMARSHALLINGS),
		MAKE_HRESULT_ENTRY(STG_E_FILEALREADYEXISTS),
		MAKE_HRESULT_ENTRY(STG_E_FILENOTFOUND),
		MAKE_HRESULT_ENTRY(STG_E_INSUFFICIENTMEMORY),
		MAKE_HRESULT_ENTRY(STG_E_INUSE),
		MAKE_HRESULT_ENTRY(STG_E_INVALIDFLAG),
		MAKE_HRESULT_ENTRY(STG_E_INVALIDFUNCTION),
		MAKE_HRESULT_ENTRY(STG_E_INVALIDHANDLE),
		MAKE_HRESULT_ENTRY(STG_E_INVALIDHEADER),
		MAKE_HRESULT_ENTRY(STG_E_INVALIDNAME),
		MAKE_HRESULT_ENTRY(STG_E_INVALIDPARAMETER),
		MAKE_HRESULT_ENTRY(STG_E_INVALIDPOINTER),
		MAKE_HRESULT_ENTRY(STG_E_LOCKVIOLATION),
		MAKE_HRESULT_ENTRY(STG_E_MEDIUMFULL),
		MAKE_HRESULT_ENTRY(STG_E_NOMOREFILES),
		MAKE_HRESULT_ENTRY(STG_E_NOTCURRENT),
		MAKE_HRESULT_ENTRY(STG_E_NOTFILEBASEDSTORAGE),
		MAKE_HRESULT_ENTRY(STG_E_OLDDLL),
		MAKE_HRESULT_ENTRY(STG_E_OLDFORMAT),
		MAKE_HRESULT_ENTRY(STG_E_PATHNOTFOUND),
		MAKE_HRESULT_ENTRY(STG_E_READFAULT),
		MAKE_HRESULT_ENTRY(STG_E_REVERTED),
		MAKE_HRESULT_ENTRY(STG_E_SEEKERROR),
		MAKE_HRESULT_ENTRY(STG_E_SHAREREQUIRED),
		MAKE_HRESULT_ENTRY(STG_E_SHAREVIOLATION),
		MAKE_HRESULT_ENTRY(STG_E_TOOMANYOPENFILES),
		MAKE_HRESULT_ENTRY(STG_E_UNIMPLEMENTEDFUNCTION),
		MAKE_HRESULT_ENTRY(STG_E_UNKNOWN),
		MAKE_HRESULT_ENTRY(STG_E_WRITEFAULT),
		MAKE_HRESULT_ENTRY(TYPE_E_AMBIGUOUSNAME),
		MAKE_HRESULT_ENTRY(TYPE_E_BADMODULEKIND),
		MAKE_HRESULT_ENTRY(TYPE_E_BUFFERTOOSMALL),
		MAKE_HRESULT_ENTRY(TYPE_E_CANTCREATETMPFILE),
		MAKE_HRESULT_ENTRY(TYPE_E_CANTLOADLIBRARY),
		MAKE_HRESULT_ENTRY(TYPE_E_CIRCULARTYPE),
		MAKE_HRESULT_ENTRY(TYPE_E_DLLFUNCTIONNOTFOUND),
		MAKE_HRESULT_ENTRY(TYPE_E_DUPLICATEID),
		MAKE_HRESULT_ENTRY(TYPE_E_ELEMENTNOTFOUND),
		MAKE_HRESULT_ENTRY(TYPE_E_INCONSISTENTPROPFUNCS),
		MAKE_HRESULT_ENTRY(TYPE_E_INVALIDSTATE),
		MAKE_HRESULT_ENTRY(TYPE_E_INVDATAREAD),
		MAKE_HRESULT_ENTRY(TYPE_E_IOERROR),
		MAKE_HRESULT_ENTRY(TYPE_E_LIBNOTREGISTERED),
		MAKE_HRESULT_ENTRY(TYPE_E_NAMECONFLICT),
		MAKE_HRESULT_ENTRY(TYPE_E_OUTOFBOUNDS),
		MAKE_HRESULT_ENTRY(TYPE_E_QUALIFIEDNAMEDISALLOWED),
		MAKE_HRESULT_ENTRY(TYPE_E_REGISTRYACCESS),
		MAKE_HRESULT_ENTRY(TYPE_E_SIZETOOBIG),
		MAKE_HRESULT_ENTRY(TYPE_E_TYPEMISMATCH),
		MAKE_HRESULT_ENTRY(TYPE_E_UNDEFINEDTYPE),
		MAKE_HRESULT_ENTRY(TYPE_E_UNKNOWNLCID),
		MAKE_HRESULT_ENTRY(TYPE_E_UNSUPFORMAT),
		MAKE_HRESULT_ENTRY(TYPE_E_WRONGTYPEKIND),
		MAKE_HRESULT_ENTRY(VIEW_E_DRAW),

		MAKE_HRESULT_ENTRY(CONNECT_E_NOCONNECTION),
		MAKE_HRESULT_ENTRY(CONNECT_E_ADVISELIMIT),
		MAKE_HRESULT_ENTRY(CONNECT_E_CANNOTCONNECT),
		MAKE_HRESULT_ENTRY(CONNECT_E_OVERRIDDEN),

#ifndef NO_PYCOM_IPROVIDECLASSINFO
		MAKE_HRESULT_ENTRY(CLASS_E_NOTLICENSED),
		MAKE_HRESULT_ENTRY(CLASS_E_NOAGGREGATION),
		MAKE_HRESULT_ENTRY(CLASS_E_CLASSNOTAVAILABLE),
#endif // NO_PYCOM_IPROVIDECLASSINFO

#ifndef MS_WINCE // ??
		MAKE_HRESULT_ENTRY(CTL_E_ILLEGALFUNCTIONCALL      ),
		MAKE_HRESULT_ENTRY(CTL_E_OVERFLOW                 ),
		MAKE_HRESULT_ENTRY(CTL_E_OUTOFMEMORY              ),
		MAKE_HRESULT_ENTRY(CTL_E_DIVISIONBYZERO           ),
		MAKE_HRESULT_ENTRY(CTL_E_OUTOFSTRINGSPACE         ),
		MAKE_HRESULT_ENTRY(CTL_E_OUTOFSTACKSPACE          ),
		MAKE_HRESULT_ENTRY(CTL_E_BADFILENAMEORNUMBER      ),
		MAKE_HRESULT_ENTRY(CTL_E_FILENOTFOUND             ),
		MAKE_HRESULT_ENTRY(CTL_E_BADFILEMODE              ),
		MAKE_HRESULT_ENTRY(CTL_E_FILEALREADYOPEN          ),
		MAKE_HRESULT_ENTRY(CTL_E_DEVICEIOERROR            ),
		MAKE_HRESULT_ENTRY(CTL_E_FILEALREADYEXISTS        ),
		MAKE_HRESULT_ENTRY(CTL_E_BADRECORDLENGTH          ),
		MAKE_HRESULT_ENTRY(CTL_E_DISKFULL                 ),
		MAKE_HRESULT_ENTRY(CTL_E_BADRECORDNUMBER          ),
		MAKE_HRESULT_ENTRY(CTL_E_BADFILENAME              ),
		MAKE_HRESULT_ENTRY(CTL_E_TOOMANYFILES             ),
		MAKE_HRESULT_ENTRY(CTL_E_DEVICEUNAVAILABLE        ),
		MAKE_HRESULT_ENTRY(CTL_E_PERMISSIONDENIED         ),
		MAKE_HRESULT_ENTRY(CTL_E_DISKNOTREADY             ),
		MAKE_HRESULT_ENTRY(CTL_E_PATHFILEACCESSERROR      ),
		MAKE_HRESULT_ENTRY(CTL_E_PATHNOTFOUND             ),
		MAKE_HRESULT_ENTRY(CTL_E_INVALIDPATTERNSTRING     ),
		MAKE_HRESULT_ENTRY(CTL_E_INVALIDUSEOFNULL         ),
		MAKE_HRESULT_ENTRY(CTL_E_INVALIDFILEFORMAT        ),
		MAKE_HRESULT_ENTRY(CTL_E_INVALIDPROPERTYVALUE     ),
		MAKE_HRESULT_ENTRY(CTL_E_INVALIDPROPERTYARRAYINDEX),
		MAKE_HRESULT_ENTRY(CTL_E_SETNOTSUPPORTEDATRUNTIME ),
		MAKE_HRESULT_ENTRY(CTL_E_SETNOTSUPPORTED          ),
		MAKE_HRESULT_ENTRY(CTL_E_NEEDPROPERTYARRAYINDEX   ),
		MAKE_HRESULT_ENTRY(CTL_E_SETNOTPERMITTED          ),
		MAKE_HRESULT_ENTRY(CTL_E_GETNOTSUPPORTEDATRUNTIME ),
		MAKE_HRESULT_ENTRY(CTL_E_GETNOTSUPPORTED          ),
		MAKE_HRESULT_ENTRY(CTL_E_PROPERTYNOTFOUND         ),
		MAKE_HRESULT_ENTRY(CTL_E_INVALIDCLIPBOARDFORMAT   ),
		MAKE_HRESULT_ENTRY(CTL_E_INVALIDPICTURE           ),
		MAKE_HRESULT_ENTRY(CTL_E_PRINTERERROR             ),
		MAKE_HRESULT_ENTRY(CTL_E_CANTSAVEFILETOTEMP       ),
		MAKE_HRESULT_ENTRY(CTL_E_SEARCHTEXTNOTFOUND       ),
		MAKE_HRESULT_ENTRY(CTL_E_REPLACEMENTSTOOLONG      ),
#endif // MS_WINCE
	};
	#undef MAKE_HRESULT_ENTRY

	// first ask the OS to give it to us..
	// ### should we get the Unicode version instead?
	int numCopied = ::FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, hr, 0, buf, bufSize, NULL );
	if (numCopied>0) {
		if (numCopied<bufSize) {
			// trim trailing crap
			if (numCopied>2 && (buf[numCopied-2]=='\n'||buf[numCopied-2]=='\r'))
				buf[numCopied-2] = '\0';
		}
		return;
	}
	// Next see if this particular error code is registered as being supplied
	// by a specific DLL.
	HINSTANCE hi = PyWin_GetErrorMessageModule(hr);
	if (hi) {
		numCopied = ::FormatMessage(FORMAT_MESSAGE_FROM_HMODULE, hi, hr, 0, buf, bufSize, NULL );
		if (numCopied>0) {
			if (numCopied<bufSize) {
				// trim trailing crap
				if (numCopied>2 && (buf[numCopied-2]=='\n'||buf[numCopied-2]=='\r'))
					buf[numCopied-2] = '\0';
			}
			return;
		}
	}

	// else look for it in the table
	for (int i = 0; i < _countof(hrNameTable); i++)
	{
		if (hr == hrNameTable[i].hr) {
			_tcsncpy(buf, hrNameTable[i].lpszName, bufSize);
			return;
		}
	}
	// not found - make one up
	wsprintf(buf, _T("OLE error 0x%08x"), hr);
}

LPCTSTR GetScodeRangeString(HRESULT hr)
{
	struct RANGE_ENTRY
	{
		HRESULT hrFirst;
		HRESULT hrLast;
		LPCTSTR lpszName;
	};
	#define MAKE_RANGE_ENTRY(hrRange) \
		{ hrRange##_FIRST, hrRange##_LAST, \
			_T(#hrRange) _T("_FIRST...") _T(#hrRange) _T("_LAST") }

	static const RANGE_ENTRY hrRangeTable[] =
	{
		MAKE_RANGE_ENTRY(CACHE_E),
		MAKE_RANGE_ENTRY(CACHE_S),
		MAKE_RANGE_ENTRY(CLASSFACTORY_E),
		MAKE_RANGE_ENTRY(CLASSFACTORY_S),
		MAKE_RANGE_ENTRY(CLIENTSITE_E),
		MAKE_RANGE_ENTRY(CLIENTSITE_S),
		MAKE_RANGE_ENTRY(CLIPBRD_E),
		MAKE_RANGE_ENTRY(CLIPBRD_S),
		MAKE_RANGE_ENTRY(CONVERT10_E),
		MAKE_RANGE_ENTRY(CONVERT10_S),
		MAKE_RANGE_ENTRY(CO_E),
		MAKE_RANGE_ENTRY(CO_S),
		MAKE_RANGE_ENTRY(DATA_E),
		MAKE_RANGE_ENTRY(DATA_S),
		MAKE_RANGE_ENTRY(DRAGDROP_E),
		MAKE_RANGE_ENTRY(DRAGDROP_S),
		MAKE_RANGE_ENTRY(ENUM_E),
		MAKE_RANGE_ENTRY(ENUM_S),
		MAKE_RANGE_ENTRY(INPLACE_E),
		MAKE_RANGE_ENTRY(INPLACE_S),
		MAKE_RANGE_ENTRY(MARSHAL_E),
		MAKE_RANGE_ENTRY(MARSHAL_S),
		MAKE_RANGE_ENTRY(MK_E),
		MAKE_RANGE_ENTRY(MK_S),
		MAKE_RANGE_ENTRY(OLEOBJ_E),
		MAKE_RANGE_ENTRY(OLEOBJ_S),
		MAKE_RANGE_ENTRY(OLE_E),
		MAKE_RANGE_ENTRY(OLE_S),
		MAKE_RANGE_ENTRY(REGDB_E),
		MAKE_RANGE_ENTRY(REGDB_S),
		MAKE_RANGE_ENTRY(VIEW_E),
		MAKE_RANGE_ENTRY(VIEW_S),
		MAKE_RANGE_ENTRY(CONNECT_E),
		MAKE_RANGE_ENTRY(CONNECT_S),

	};
	#undef MAKE_RANGE_ENTRY

	// look for it in the table
	for (int i = 0; i < _countof(hrRangeTable); i++)
	{
		if (hr >= hrRangeTable[i].hrFirst && hr <= hrRangeTable[i].hrLast)
			return hrRangeTable[i].lpszName;
	}
	return NULL;    // not found
}

LPCTSTR GetSeverityString(HRESULT hr)
{
	static LPCTSTR rgszSEVERITY[] =
	{
		_T("SEVERITY_SUCCESS"),
		_T("SEVERITY_ERROR"),
	};
	return rgszSEVERITY[HRESULT_SEVERITY(hr)];
}

LPCTSTR GetFacilityString(HRESULT hr)
{
	static LPCTSTR rgszFACILITY[] =
	{
		_T("FACILITY_NULL"),
		_T("FACILITY_RPC"),
		_T("FACILITY_DISPATCH"),
		_T("FACILITY_STORAGE"),
		_T("FACILITY_ITF"),
		_T("FACILITY_ADSI"),
		_T("FACILITY_0x06"),
		_T("FACILITY_WIN32"),
		_T("FACILITY_WINDOWS"),
		_T("FACILITY_SSPI/FACILITY_MQ"), // SSPI from ADSERR.H, MQ from mq.h
		_T("FACILITY_CONTROL"),
		_T("FACILITY_EDK"),
		_T("FACILITY_INTERNET"),
		_T("FACILITY_MEDIASERVER"),
		_T("FACILITY_MSMQ"),
		_T("FACILITY_SETUPAPI"),
	};
	if (HRESULT_FACILITY(hr) >= _countof(rgszFACILITY))
		switch (HRESULT_FACILITY(hr)) {
			case 0x7FF:
				return _T("FACILITY_BACKUP");
			case 0x800:
				return _T("FACILITY_EDB");
			case 0x900:
				return _T("FACILITY_MDSI");
			default:
				return _T("<Unknown Facility>");
		}
	return rgszFACILITY[HRESULT_FACILITY(hr)];
}


text:
//*****************************************************************************
/*!
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *****************************************************************************
 *
 *  \file   transfermodule.h
 *
 *  \brief  A module that handles all transfer encodings.
 *
 *  \version
 *      - S Panyam      10/03/2009
 *        Created
 *
 *****************************************************************************/

#ifndef _STRANSFER_MODULE_H_
#define _STRANSFER_MODULE_H_

#include "httpmodule.h"

// Takes care of transfer encoding - Strips out Content-Length in chunked
// mode
class STransferModule : public SHttpModule
{
public:
    //! Create it
    STransferModule(SHttpModule *pNext) : SHttpModule(pNext) { }

    //! Called to handle output data from another module
    virtual void ProcessOutput(SConnection *        pConnection,
                               SHttpHandlerData *   pHandlerData,
                               SHttpHandlerStage *  pStage,
                               SBodyPart *          pBodyPart);

protected:
    void HandleBodyPart(SConnection *       pConnection,
                        SHttpHandlerData *  pHandlerData,
                        SHttpHandlerStage * pStage,
                        SHttpModuleData *   pModData,
                        SBodyPart *         pBodyPart);
};

#endif


text:
/**
 *     This code was auto-generated by a tool.
 *
 *     Changes to this file may cause incorrect behavior and will be lost if
 *     the code is regenerated.
 */
package com.mozu.api.contracts.reference;

import java.util.List;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.joda.time.DateTime;
import com.mozu.api.contracts.reference.UnitOfMeasure;

/**
 *	The paged collection of all units of measure that the system currently supports.
 */
@JsonIgnoreProperties(ignoreUnknown = true)
public class UnitOfMeasureCollection implements Serializable
{
	// Default Serial Version UID
	private static final long serialVersionUID = 1L;

	/**
	 * The number of results listed in the query collection, represented by a signed 64-bit (8-byte) integer. This value is system-supplied and read-only.
	 */
	protected Long totalCount;

	public Long getTotalCount() {
		return this.totalCount;
	}

	public void setTotalCount(Long totalCount) {
		this.totalCount = totalCount;
	}

	/**
	 * An array list of objects in the returned collection.
	 */
	protected List<UnitOfMeasure> items;
	public List<UnitOfMeasure> getItems() {
		return this.items;
	}
	public void setItems(List<UnitOfMeasure> items) {
		this.items = items;
	}

}


text:
namespace g{namespace Uno{namespace Graphics{struct VertexAttributeTypeHelpers;}}}

namespace g{
namespace Uno{
namespace Graphics{

// public static class VertexAttributeTypeHelpers :1418
// {
uClassType* VertexAttributeTypeHelpers_typeof();
void VertexAttributeTypeHelpers__GetStrideInBytes_fn(int* type, int* __retval);

struct VertexAttributeTypeHelpers : uObject
{
    static int GetStrideInBytes(int type);
};
// }

}}} // ::g::Uno::Graphics


text:
package model.commands;

import model.Command;
import model.CommandManager;
import model.Turtle;
import model.VariableManager;

/**
 * @author Aaron Paskin
 * @author Ian Eldridge-Allegra
 */
public class And implements Command {
	private static final long serialVersionUID = -9050221653639491294L;
	private Command x1;
	private Command x2;

	public And(Command x1, Command x2) {
		this.x1 = x1;
		this.x2 = x2;
	}

	@Override
	public double execute(Turtle t, CommandManager commands, VariableManager variables) {
		if(x1.execute(t, commands, variables) != 0 && x2.execute(t, commands, variables) != 0) return 1;
		return 0;
	}

}


text:
class FeedsController < ApplicationController
  def discover
    users = User.randomize_six_users
    @works = users.collect do |user|
      Work.find(user.masterpiece)
    end
    render :layout => false
  end

  def followingfeed
    if user_signed_in?
      @feed_items = current_user.feed
    end
  end

  def random
    w = User.where(artist: true).where.not(masterpiece: nil).sample(6)
    @works = w.collect do |user|
      Work.find(user.masterpiece)
    end
    render 'feeds'
  end

  def most_collected
    @works =  Work.order(times_collected: :desc)[0...6]
    render 'feeds'
  end

end


text:
//---------------------------------*-C++-*-----------------------------------//

//---------------------------------------------------------------------------//

#include "../Anderson_Solver.hh"

#include "gtest/utils_gtest.hh"

#include <string>
#include <vector>
#include <memory>

#include "xs/XS_Builder.hh"
#include "solvers/LinAlgTypedefs.hh"
#include "spn/MatrixTraits.hh"
#include "geometry/Cartesian_Mesh.hh"
#include "geometry/RTK_Geometry.hh"
#include "../Fission_Source.hh"
#include "../Global_RNG.hh"
#include "../Tally.hh"
#include "../Group_Bounds.hh"
#include "../VR_Roulette.hh"
#include "../Tallier.hh"

//---------------------------------------------------------------------------//
// Test fixture
//---------------------------------------------------------------------------//

class Anderson_SolverTest : public testing::Test
{
  protected:
    // >>> TYPEDEFS
    typedef profugus::Core                                  Geometry_t;
    typedef profugus::EpetraTypes                           LinAlg_t;
    typedef profugus::Anderson_Solver<Geometry_t,LinAlg_t>  Solver_t;
    typedef Solver_t::Operator                              Operator;
    typedef Operator::Source_Transporter_t                  Transporter_t;
    typedef profugus::Tallier<Geometry_t>                   Tallier_t;
    typedef Transporter_t::Physics_t                        Physics_t;
    typedef profugus::Global_RNG::RNG_Control_t             RNG_Control_t;
    typedef Physics_t::Particle_t                           Particle_t;
    typedef Physics_t::Bank_t                               Bank_t;
    typedef profugus::VR_Roulette<Geometry_t>               Var_Reduction_t;
    typedef profugus::Cartesian_Mesh                        Mesh_t;

    typedef Physics_t::XS_t   XS_t;
    typedef Physics_t::RCP_XS RCP_XS;

    typedef XS_t::OneDArray OneDArray;
    typedef XS_t::TwoDArray TwoDArray;

    typedef Physics_t::ParameterList_t ParameterList_t;
    typedef Physics_t::RCP_Std_DB      RCP_Std_DB;

    typedef std::shared_ptr<Physics_t>       SP_Physics;
    typedef std::shared_ptr<Geometry_t>      SP_Geometry;
    typedef Physics_t::SP_Particle           SP_Particle;
    typedef std::shared_ptr<RNG_Control_t>   SP_RNG_Control;
    typedef Solver_t::SP_Tallier             SP_Tallier;
    typedef Solver_t::SP_Fission_Source      SP_Fission_Source;
    typedef Solver_t::SP_Source_Transporter  SP_Transporter;
    typedef std::shared_ptr<Var_Reduction_t> SP_Var_Reduction;

    typedef Solver_t::RCP_MAP RCP_MAP;

  protected:
    void SetUp()
    {
        seed = 32442;
        rcon = std::make_shared<RNG_Control_t>(seed);

        // set number of nodes
        node  = profugus::node();
        nodes = profugus::nodes();

        // set our other attributes
        this->init_db();
        this->init_geometry();
        this->init_physics();

        // make the source transporter
        transporter = std::make_shared<Transporter_t>(db, geometry, physics);

        // make the variance reduction
        var_reduction = std::make_shared<Var_Reduction_t>(db);

        // make the tallier
        tallier = std::make_shared<Tallier_t>();
        tallier->set(geometry, physics);

        // add objects to the source transporter
        transporter->set(tallier);
        transporter->set(var_reduction);
    }

    //! Set the geometry
    void init_geometry()
    {
        typedef Geometry_t::SP_Array SP_Core;
        typedef Geometry_t::Array_t  Core_t;
        typedef Core_t::SP_Object    SP_Lattice;
        typedef Core_t::Object_t     Lattice_t;
        typedef Lattice_t::SP_Object SP_Pin_Cell;
        typedef Lattice_t::Object_t  Pin_Cell_t;

        // UO2 pin cell
        SP_Pin_Cell pin(std::make_shared<Pin_Cell_t>(1, 0.54, 8, 1.26, 1.0));

        // make lattice
        SP_Lattice lat(std::make_shared<Lattice_t>(3, 3, 1, 1));

        // assign pins
        lat->assign_object(pin, 0); // fuel pins

        // complete lattice
        lat->complete(0.0, 0.0, 0.0);

        // make core
        SP_Core core(std::make_shared<Core_t>(1, 1, 1, 1));

        // assign lattice
        core->assign_object(lat, 0); // lattice of single fuel pin

        // arrange lattice in core
        core->id(0, 0, 0) = 0;

        // add reflecting boundary conditions
        Core_t::Vec_Int reflect(6, 1);
        core->set_reflecting(reflect);

        // complete core
        core->complete(0.0, 0.0, 0.0);

        // make the geometry
        geometry = std::make_shared<Geometry_t>(core);
    }

    //! Set the physics
    void init_physics()
    {
        typedef profugus::XS_Builder::Matid_Map Matid_Map;
        typedef Matid_Map::value_type           value_type;
        typedef std::string                     string;

        // make an xs_builder
        profugus::XS_Builder builder;
        builder.open_and_broadcast("xs_c5g7.xml");

        Matid_Map map;
        map.insert(value_type(1, string("UO2")));
        map.insert(value_type(2, string("MOX_43")));
        map.insert(value_type(3, string("MOX_70")));
        map.insert(value_type(4, string("MOX_87")));
        map.insert(value_type(5, string("fission_chamber")));
        map.insert(value_type(6, string("guide_tube")));
        map.insert(value_type(7, string("control_rod")));
        map.insert(value_type(8, string("mod")));
        map.complete();

        builder.build(map);

        RCP_XS xs = builder.get_xs();

        physics = std::make_shared<Physics_t>(db, xs);
        physics->set_geometry(geometry);
    }

    //! Set the database options.
    void init_db()
    {
        db = Teuchos::rcp(new ParameterList_t("test"));

        db->set("Np", 1000);

        db->set("mc_diag_frac", 1.1);
        db->set("keff_init", 1.32);
        db->set("num_cycles", 20);

        auto &adb = db->sublist("anderson_db");
    }

  protected:
    int node;
    int nodes;
    int seed;

    SP_RNG_Control  rcon;
    RCP_Std_DB      db;
    SP_Geometry     geometry;
    SP_Physics      physics;

    SP_Transporter   transporter;
    SP_Var_Reduction var_reduction;
    SP_Tallier       tallier;
};

//---------------------------------------------------------------------------//
// TESTS
//---------------------------------------------------------------------------//

TEST_F(Anderson_SolverTest, api)
{
    // Make anderson mesh
    std::vector<double> r = {0.0, 1.26, 2.52, 3.78};
    std::vector<double> z = {0.0, 1.0};
    auto &adb = db->sublist("anderson_db");
    adb.set("x_bounds", OneDArray(r));
    adb.set("y_bounds", OneDArray(r));
    adb.set("z_bounds", OneDArray(z));

    // make fission source
    auto fs = std::make_shared<profugus::Fission_Source<profugus::Core> >(
        db, geometry, physics, rcon);

    // Make the operator
    Solver_t anderson(db);

    // Set it
    anderson.set(transporter, fs);
}

//---------------------------------------------------------------------------//
// end of MC/mc/test/tstAnderson_Solver.cc
//---------------------------------------------------------------------------//


text:
Provides a list of system fonts and fonts available from Google Fonts, prepared for use in the Web Stories editor.

The list, `font.json`, contains additional information like metrics for each font, and is updated regularly using an automated CI task.

To update the list, run `GOOGLE_FONTS_API_KEY=yourapikey node index.js`.


text:
<!--
Copyright DTCC 2016 All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

  <modelVersion>4.0.0</modelVersion>

  <groupId>example</groupId>
  <artifactId>chaincode-table</artifactId>
  <packaging>jar</packaging>
  <name>java-table-example</name>
  <version>1.0</version>
  <url>http://maven.apache.org</url>
  <build>
   <directory>${project.basedir}/build</directory>
   <finalName>chaincode</finalName>
   <plugins>
        <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
                <version>3.0.2</version>
    <configuration>
      <outputDirectory>${dist.dir}</outputDirectory>
      <archive>
      <manifest>
      <addClasspath>true</addClasspath>
      <classpathPrefix>libs/</classpathPrefix>
      <mainClass>example.TableExample</mainClass>
      </manifest>
      </archive>
    </configuration>
  </plugin>
  <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-dependency-plugin</artifactId>
        <version>2.10</version>
        <executions>
          <execution>
            <id>copy-dependencies</id>
            <phase>package</phase>
            <goals>
              <goal>copy-dependencies</goal>
            </goals>
            <configuration>
              <outputDirectory>${project.build.directory}/libs</outputDirectory>
              <overWriteReleases>false</overWriteReleases>
              <overWriteSnapshots>false</overWriteSnapshots>
              <overWriteIfNewer>true</overWriteIfNewer>
            </configuration>
          </execution>
        </executions>
  </plugin>
  </plugins>
  </build>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
     <groupId>io.grpc</groupId>
     <artifactId>grpc-all</artifactId>
     <version>0.13.2</version>
   </dependency>
   <dependency>
     <groupId>commons-cli</groupId>
     <artifactId>commons-cli</artifactId>
     <version>1.3.1</version>
  </dependency>
  <dependency>
    <groupId>org.hyperledger</groupId>
    <artifactId>shim-client</artifactId>
    <version>1.0</version>
  </dependency>
  </dependencies>
</project>


text:
#ifndef _MYSQL_LIBMYSQL_STATIC_H_
#define _MYSQL_LIBMYSQL_STATIC_H_

#include "mysql_client_api.h"
#include <cppconn/config.h>
#include <boost/noncopyable.hpp>
#include <boost/shared_ptr.hpp>

namespace sql
{
    namespace mysql
    {
        namespace util
        {
            template <class T>
            class Singleton: public boost::noncopyable
            {
            protected:
                Singleton() {}

            public:

                static boost::shared_ptr<T> & theInstance() {
                    //shared::ptr is used only to be able to use in getCApiHandle
                    static boost::shared_ptr<T> instance(new T());

                    return instance;
                }
            };

            // macros to use in private/protected part of singleton-ed class
#define CCPP_SINGLETON(classname) classname();\
	friend class sql::mysql::util::Singleton<classname>
        }

        namespace NativeAPI
        {

            class LibmysqlStaticProxy : public IMySQLCAPI, public ::sql::mysql::util::Singleton< LibmysqlStaticProxy >
            {
            private:

                CCPP_SINGLETON(LibmysqlStaticProxy);

            public:

                virtual ~LibmysqlStaticProxy();

                // MySQL C-API calls wrappers

                my_ulonglong affected_rows(MYSQL* mysql);

                my_bool autocommit(MYSQL*, my_bool);

                void close(MYSQL* mysql);

                my_bool commit(MYSQL* mysql);

                void data_seek(MYSQL_RES*, my_ulonglong);

                void debug(const char*);

                unsigned int mysql_errno(MYSQL* mysql);

                const char* error(MYSQL* mysql);

                MYSQL_FIELD* fetch_field(MYSQL_RES*);

                MYSQL_FIELD* fetch_field_direct(MYSQL_RES*, unsigned int);

                unsigned long* fetch_lengths(MYSQL_RES*);

                MYSQL_ROW fetch_row(MYSQL_RES*);

                unsigned int field_count(MYSQL* mysql);

                void free_result(MYSQL_RES*);

                unsigned long get_client_version();

                const char* get_server_info(MYSQL* mysql);

                unsigned long get_server_version(MYSQL* mysql);

                MYSQL* init(MYSQL* mysql);

                int library_init(int, char**, char**);

                void library_end();

                my_bool more_results(MYSQL* mysql);

                int next_result(MYSQL* mysql);

                unsigned int num_fields(MYSQL_RES*);

                my_ulonglong num_rows(MYSQL_RES*);

                int options(MYSQL*, enum mysql_option, const void*);

                int ping(MYSQL*);

                int query(MYSQL*, const char*);

                MYSQL* real_connect(MYSQL* mysql,
                                    const char*   host,
                                    const char*   user,
                                    const char*   passwd,
                                    const char*   db,
                                    unsigned int  port,
                                    const char*   unix_socket,
                                    unsigned long client_flag);

                unsigned long real_escape_string(MYSQL* mysql, char* to, const char* from, unsigned long length);

                int real_query(MYSQL*, const char*, unsigned long);

                my_bool rollback(MYSQL* mysql);

                const char* sqlstate(MYSQL* mysql);

                my_bool ssl_set(MYSQL* mysql,
                                const char* key,
                                const char* cert,
                                const char* ca,
                                const char* capath,
                                const char* cipher);

                MYSQL_RES*   store_result(MYSQL* mysql);

                MYSQL_RES*   use_result(MYSQL* mysql);

                // Prepared Statementstmt_* functions
                my_ulonglong stmt_affected_rows(MYSQL_STMT*);

                my_bool stmt_attr_set(MYSQL_STMT*, enum enum_stmt_attr_type, const void*);

                my_bool stmt_bind_param(MYSQL_STMT*, MYSQL_BIND*);

                my_bool stmt_bind_result(MYSQL_STMT*, MYSQL_BIND*);

                my_bool stmt_close(MYSQL_STMT*);

                void stmt_data_seek(MYSQL_STMT*, my_ulonglong);

                unsigned int stmt_errno(MYSQL_STMT*);

                const char* stmt_error(MYSQL_STMT*);

                int stmt_execute(MYSQL_STMT*);

                int stmt_fetch(MYSQL_STMT*);

                unsigned int stmt_field_count(MYSQL_STMT*);

                MYSQL_STMT* stmt_init(MYSQL* mysql);

                my_ulonglong stmt_num_rows(MYSQL_STMT*);

                unsigned long stmt_param_count(MYSQL_STMT*);

                int stmt_prepare(MYSQL_STMT*, const char*, unsigned long);

                MYSQL_RES* stmt_result_metadata(MYSQL_STMT*);

                my_bool stmt_send_long_data(MYSQL_STMT*, unsigned int, const char*, unsigned long);

                const char* stmt_sqlstate(MYSQL_STMT*);

                int stmt_store_result(MYSQL_STMT*);

                void thread_init();

                void thread_end();
            };

        } // namespace NativeAPI
    } // namespace mysql
} // namespace sql

#endif

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * End:
 * vim600: noet sw=4 ts=4 fdm=marker
 * vim<600: noet sw=4 ts=4
 */


text:
'''
Created on 01.05.2015

@author: Daniil Sorokin<sorokin@ukp.informatik.tu-darmstadt.de>
'''

import codecs
import sys
import re
import os
import argparse
import nltk
from nltk.probability import FreqDist
from nltk.tokenize import regexp_tokenize
from nltk.corpus import stopwords

my_encoding = 'utf-8'

if __name__ == '__main__':
    # Parse arguments
    parser = argparse.ArgumentParser()
    parser.add_argument('-n',type=int, help = "Number of most common word to compare between documents", default=30)
    parser.add_argument('-m',type=int, help = "Number of most letters and letter pairs to compare between documents", default=30)
    parser.add_argument('-s',type=argparse.FileType('r', encoding=my_encoding),
                        help = "Use the given list of stop words. Should be in " + my_encoding)
    parser.add_argument('files', nargs='+', type=argparse.FileType('r', encoding=my_encoding),
                        help = "Text documents to process. Should be in " + my_encoding)
    params = parser.parse_args()

    # Patterns for splitting text into words and ngrams
    pattern_words = "[\w\-0-9']+"
    pattern_unigrams = "[^\W\d_]"
    pattern_bigrams = "[^\W\d_]{2}"

    # Store most common words and ngrams for latter comparison of texts
    words_most_common = []
    ngrams_most_common = []

    # Load stopwords if necessary
    if params.s:
        stopwords = [sw.strip() for sw in params.s.readlines()]
        params.s.close()

    #Process documents
    for f in params.files:
        txt = f.read().lower()
        f.close()

        # Tokenize
        txt_tokens = regexp_tokenize(txt, pattern_words)
        if params.s:
            txt_tokens = [token for token in txt_tokens if token not in stopwords]

        # Extract ngrams
        unigrams = regexp_tokenize(txt, pattern_unigrams)
        bigrams = regexp_tokenize(txt, pattern_bigrams)

        #Create frequency distributions
        fdist_words = FreqDist(txt_tokens)
        fdist_ngrams = FreqDist(unigrams + bigrams)

        # Store most common words and ngrams for latter comparison of texts
        words_most_common.append([k for (k,_) in fdist_words.most_common(params.n)])
        ngrams_most_common.append([k for (k,_) in fdist_ngrams.most_common(params.m)])
        outputname = "output_for_" + f.name.rsplit(os.sep, 2)[1]

        # Write out the distribution of words in the document
        with codecs.open("distributions-data/output/words_" + outputname, "w", encoding=my_encoding) as out:
            for k,v in fdist_words.most_common():
                prozent = fdist_words.freq(k)
                out.write("{},{},{}\n".format(k,v, prozent))
        # Write out the distribution of ngrams in the document
        with codecs.open("distributions-data/output/letters_" + outputname, "w", encoding=my_encoding) as out:
            for k,v in fdist_ngrams.most_common():
                prozent = v / (len(unigrams) if len(k) == 1 else len(bigrams))
                out.write("{},{},{}\n".format(k,v, prozent))
        # Write the size of bins of words that appear with the same frequency
        with codecs.open("distributions-data/bins/" + outputname, "w", encoding=my_encoding) as out:
            for i in sorted(set(fdist_words.values())):
                bin_size = fdist_words.Nr(i)
                out.write("{},{}\n".format(i,bin_size))
    print('Output distributions saved in \'output\' folder.')
    print('Output bins saved in \'bins\' folder.')
    # If there are many documents -> compare their most common words and ngrams
    if len(params.files) > 1:
        print("Pairwise overlap between {} most frequent words:".format(params.n))
        short_names = [f.name[-15:] for f in params.files]
        for i, list1 in enumerate(words_most_common):
            for j, list2 in enumerate(words_most_common[i+1:]):
                print("{} | {} | ".format(short_names[i], short_names[i+j+1]), end="")
                overlap = len([w for w in list1 if w in list2])
                print(overlap)
        print("Pairwise overlap between {} most frequent letters and letter pairs:".format(params.m))
        short_names = [f.name[-15:] for f in params.files]
        for i, list1 in enumerate(ngrams_most_common):
            for j, list2 in enumerate(ngrams_most_common[i+1:]):
                print("{} | {} | ".format(short_names[i], short_names[i+j+1]), end="")
                overlap = len([w for w in list1 if w in list2])
                print(overlap)


text:
#include "sweep.h"

#include <chrono>
#include <string>
#include <thread>

int32_t sweep_get_version(void) { return SWEEP_VERSION; }
bool sweep_is_abi_compatible(void) { return sweep_get_version() >> 16u == SWEEP_VERSION_MAJOR; }

struct sweep_error {
  std::string what;
};

struct sweep_device {
  bool is_scanning;
  int32_t motor_speed;
  int32_t sample_rate;
  int32_t nth_scan_request;
};

struct sweep_scan {
  int32_t count;
  int32_t nth;
};

const char* sweep_error_message(sweep_error_s error) {
  SWEEP_ASSERT(error);

  return error->what.c_str();
}

void sweep_error_destruct(sweep_error_s error) {
  SWEEP_ASSERT(error);

  delete error;
}

static void sweep_device_wait_until_motor_ready(sweep_device_s device, sweep_error_s* error) {
  SWEEP_ASSERT(device);
  SWEEP_ASSERT(error);
  SWEEP_ASSERT(!device->is_scanning);

  (void)device;
  (void)error;
}

static void sweep_device_attempt_start_scanning(sweep_device_s device, sweep_error_s* error) {
  SWEEP_ASSERT(device);
  SWEEP_ASSERT(error);
  SWEEP_ASSERT(!device->is_scanning);
  (void)error;

  if (device->is_scanning)
    return;

  device->is_scanning = true;
}

static void sweep_device_attempt_set_motor_speed(sweep_device_s device, int32_t hz, sweep_error_s* error) {
  SWEEP_ASSERT(device);
  SWEEP_ASSERT(hz >= 0 && hz <= 10);
  SWEEP_ASSERT(error);
  SWEEP_ASSERT(!device->is_scanning);
  (void)error;

  device->motor_speed = hz;
}

sweep_device_s sweep_device_construct_simple(const char* port, sweep_error_s* error) {
  SWEEP_ASSERT(error);

  return sweep_device_construct(port, 115200, error);
}

sweep_device_s sweep_device_construct(const char* port, int32_t bitrate, sweep_error_s* error) {
  SWEEP_ASSERT(port);
  SWEEP_ASSERT(bitrate > 0);
  SWEEP_ASSERT(error);
  (void)port;
  (void)bitrate;
  (void)error;

  auto out = new sweep_device{/*is_scanning=*/false, /*motor_speed=*/5, /*sample_rate*/ 500, /*nth_scan_request=*/0};
  return out;
}

void sweep_device_destruct(sweep_device_s device) {
  SWEEP_ASSERT(device);

  delete device;
}

void sweep_device_start_scanning(sweep_device_s device, sweep_error_s* error) {
  SWEEP_ASSERT(device);
  SWEEP_ASSERT(error);
  SWEEP_ASSERT(!device->is_scanning);
  (void)error;

  if (device->is_scanning)
    return;

  device->is_scanning = true;
}

void sweep_device_stop_scanning(sweep_device_s device, sweep_error_s* error) {
  SWEEP_ASSERT(device);
  SWEEP_ASSERT(error);
  (void)error;

  device->is_scanning = false;
}

sweep_scan_s sweep_device_get_scan(sweep_device_s device, sweep_error_s* error) {
  SWEEP_ASSERT(device);
  SWEEP_ASSERT(error);
  SWEEP_ASSERT(device->is_scanning);
  (void)error;

  auto out = new sweep_scan{/*count=*/device->is_scanning ? 16 : 0, /*nth=*/device->nth_scan_request};

  device->nth_scan_request += 1;

  // Artificially introduce slowdown, to simulate device rotation
  std::this_thread::sleep_for(std::chrono::milliseconds(100));

  return out;
}

bool sweep_device_get_motor_ready(sweep_device_s device, sweep_error_s* error) {
  SWEEP_ASSERT(device);
  SWEEP_ASSERT(error);
  SWEEP_ASSERT(!device->is_scanning);
  (void)device;
  (void)error;

  return true;
}

int32_t sweep_device_get_motor_speed(sweep_device_s device, sweep_error_s* error) {
  SWEEP_ASSERT(device);
  SWEEP_ASSERT(error);
  SWEEP_ASSERT(!device->is_scanning);
  (void)device;
  (void)error;

  return device->motor_speed;
}

void sweep_device_set_motor_speed(sweep_device_s device, int32_t hz, sweep_error_s* error) {
  SWEEP_ASSERT(device);
  SWEEP_ASSERT(hz >= 0 && hz <= 10);
  SWEEP_ASSERT(error);
  SWEEP_ASSERT(!device->is_scanning);
  (void)error;

  device->motor_speed = hz;
}

int32_t sweep_device_get_sample_rate(sweep_device_s device, sweep_error_s* error) {
  SWEEP_ASSERT(device);
  SWEEP_ASSERT(error);
  SWEEP_ASSERT(!device->is_scanning);
  (void)error;

  return device->sample_rate;
}

void sweep_device_set_sample_rate(sweep_device_s device, int32_t hz, sweep_error_s* error) {
  SWEEP_ASSERT(device);
  SWEEP_ASSERT(hz == 500 || hz == 750 || hz == 1000);
  SWEEP_ASSERT(error);
  SWEEP_ASSERT(!device->is_scanning);
  (void)error;

  device->sample_rate = hz;
}

int32_t sweep_scan_get_number_of_samples(sweep_scan_s scan) {
  SWEEP_ASSERT(scan);

  return scan->count;
}

int32_t sweep_scan_get_angle(sweep_scan_s scan, int32_t sample) {
  SWEEP_ASSERT(scan);
  SWEEP_ASSERT(sample >= 0 && sample < scan->count && "sample index out of bounds");

  int32_t angle = 360;
  int32_t delta = (sample % 4) * 2 + scan->nth;

  switch (sample / 4) {
  case 0:
    angle = 0;
    break;
  case 1:
    angle = 90;
    break;
  case 2:
    angle = 180;
    break;
  case 3:
    angle = 270;
    break;
  }

  return ((angle + delta) % 360) * 1000;
}

int32_t sweep_scan_get_distance(sweep_scan_s scan, int32_t sample) {
  SWEEP_ASSERT(scan);
  SWEEP_ASSERT(sample >= 0 && sample < scan->count && "sample index out of bounds");
  (void)scan;
  (void)sample;

  return 2 * 100; // 2 meter
}

int32_t sweep_scan_get_signal_strength(sweep_scan_s scan, int32_t sample) {
  SWEEP_ASSERT(scan);
  SWEEP_ASSERT(sample >= 0 && sample < scan->count && "sample index out of bounds");
  (void)scan;
  (void)sample;

  return 200;
}

void sweep_scan_destruct(sweep_scan_s scan) {
  SWEEP_ASSERT(scan);

  delete scan;
}

void sweep_device_reset(sweep_device_s device, sweep_error_s* error) {
  SWEEP_ASSERT(device);
  SWEEP_ASSERT(error);
  SWEEP_ASSERT(!device->is_scanning);
  (void)device;
  (void)error;
}


text:
<!doctype html>
<meta charset="utf-8" />
<?php

print "Length of content posted: [" . mb_strlen($_REQUEST["test"]) . "]";

?>


text:
import {SparkPlugin, Page} from '@ciscospark/spark-core';

/**
 * @typedef {Object} Types~Team
 * @property {string} id - (server generated) The unique ID for the team.
 * @property {string} name - The name of the team.
 * @property {isoDate} created - (server generated) The date and time when the
 * team was created, in ISO8601 format.
 */

/**
* @class
* @extends SparkPlugin
 */
const Teams = SparkPlugin.extend({
  /**
   * Create a new team.
   * @instance
   * @param {Types~Team} team
   * @returns {Promise<Types~Team>}
   * @memberof Teams
   * @example
   * var ciscospark = require('../..');
   * ciscospark.teams.create({name: 'Create Team Example'})
   *   .then(function(team) {
   *     var assert = require('assert');
   *     assert(team.id);
   *     assert(team.name);
   *     assert(team.created);
   *     return 'success';
   *   });
   *   // => success
   */
  create(team) {
    return this.request({
      method: `POST`,
      uri: `${this.config.hydraServiceUrl}/teams`,
      body: team
    })
      .then((res) => res.body);
  },

  /**
   * Returns a single team
   * @instance
   * @param {Types~Team|string} team
   * @param {object} options
   * @returns {Promise<Types~Team>}
   * @memberof Teams
   * @example
   * var ciscospark = require('../..');
   * var team;
   * ciscospark.teams.create({name: 'Get Team Example'})
   *   .then(function(r) {
   *     team = r;
   *     return ciscospark.teams.get(team.id);
   *   })
   *   .then(function(team2) {
   *     var assert = require('assert');
   *     assert.equal(team2.id, team.id);
   *     return 'success';
   *   });
   *   // => success
   */
  get(team, options) {
    const id = team.id || team;

    return this.request({
      uri: `${this.config.hydraServiceUrl}/teams/${id}`,
      qs: options
    })
      .then((res) => res.body.items || res.body);
  },

  /**
   * List teams.
   * @instance
   * @param {object} options
   * @param {object} options.max Limit the maximum number of teams in the
   * response.
   * @returns {Promise<Page<Types~Team>>}
   * @memberof Teams
   * @example
   * var ciscospark = require('../..');
   * var createdRooms;
   * Promise.all([
   *   ciscospark.teams.create({name: 'List Teams Example 1'}),
   *   ciscospark.teams.create({name: 'List Teams Example 2'}),
   *   ciscospark.teams.create({name: 'List Teams Example 3'})
   * ])
   *   .then(function(r) {
   *     createdRooms = r;
   *     return ciscospark.teams.list({max: 3});
   *   })
   *   .then(function(teams) {
   *     var assert = require('assert');
   *     assert(teams.length === 3);
   *     for (var i = 0; i < teams.items.length; i++) {
   *       assert(createdRooms.filter(function(room) {
   *         return room.id === teams.items[i].id;
   *       }).length === 1);
   *     }
   *     return 'success';
   *   });
   *   // => success
   */
  list(options) {
    return this.request({
      uri: `${this.config.hydraServiceUrl}/teams/`,
      qs: options
    })
      .then((res) => new Page(res, this.spark));
  },

  /**
   * Update a team.
   * @instance
   * @param {Types~Team} team
   * @returns {Promise<Types~Team>}
   * @memberof Teams
   * @example
   * var ciscospark = require('../..');
   * var teams;
   * ciscospark.teams.create({name: 'Update Team Example'})
   *   .then(function(r) {
   *     teams = r;
   *     teams.name = 'Teams Example (Updated Title)';
   *     return ciscospark.teams.update(teams);
   *   })
   *   .then(function() {
   *     return ciscospark.teams.get(teams.id);
   *   })
   *   .then(function(teams) {
   *     var assert = require('assert');
   *     assert.equal(teams.name, 'Teams Example (Updated Title)');
   *     return 'success';
   *   });
   *   // => success

   */
  update(team) {
    const id = team.id;
    return this.request({
      method: `PUT`,
      uri: `${this.config.hydraServiceUrl}/teams/${id}`,
      body: team
    })
      .then((res) => res.body);
  }
});

export default Teams;


text:
angular.module('formly.render').directive('formlyDynamicName', function formlyDynamicName() {
	'use strict';
	return {
		restrict: 'A',
		priority: 599, // one after ngIf
		controller: function($scope, $element, $attrs) {
			$element.removeAttr('formly-dynamic-name');
			$attrs.$set('name', $scope.$eval($attrs.formlyDynamicName));
			delete $attrs.formlyDynamicName;
			$scope.$emit('formly-dynamic-name-update');
		}
	};
});