text:
<?php namespace Anomaly\Streams\Platform\Traits;

use Anomaly\Streams\Platform\Notification\Event\Transmission;
use Illuminate\Notifications\Notification;

/**
 * Class Transmitter
 *
 * @link   http://pyrocms.com/
 * @author PyroCMS, Inc. <support@pyrocms.com>
 * @author Ryan Thompson <ryan@pyrocms.com>
 */
trait Transmitter
{

    /**
     * Transmit the notification.
     *
     * @param Notification $notification
     */
    public function transmit(Notification $notification)
    {
        app('events')->fire(new Transmission($notification));
    }
}


text:
package com.usst.app.baseInfo.supplier.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.usst.app.baseInfo.supplier.model.Supplier;
import com.usst.app.baseInfo.supplier.service.SupplierService;
import com.usst.app.component.serialNumber.service.SerialNumberService;
import com.usst.app.system.user.model.SysUser;
import com.usst.code.struct.BaseAction;
import com.usst.code.util.PageInfo;

public class SupplierAction extends BaseAction {
	private static final long serialVersionUID = 7519736543727228896L;
	private static final Logger logger = Logger.getLogger(SupplierAction.class);
	private SupplierService supplierService;
	private Supplier supplier;
	private SerialNumberService serialNumberService;

	public void setSupplierService(SupplierService supplierService) {
		this.supplierService = supplierService;
	}

	public void setSerialNumberService(SerialNumberService serialNumberService) {
		this.serialNumberService = serialNumberService;
	}

	public String listJson() {
		logger.info("start list all supplier data!");
		List<Supplier> resultList = null;
		int totalRows = 0;
		try {
			PageInfo pageInfo = createPageInfo();
			resultList = this.supplierService.pageList(pageInfo, this.supplier, true);
			totalRows = pageInfo.getCount();
		} catch (Exception e) {
			logger.error("error occur when list supplier data!", e);
		}
		if (resultList == null) {
			resultList = new ArrayList();
		}
		this.jsonMap = new HashMap();
		this.jsonMap.put("total", Integer.valueOf(totalRows));
		this.jsonMap.put("rows", resultList);

		logger.info("finish list all supplier data!");
		return "success";
	}

	public String list() {
		return "list_supplier";
	}

	public String edit() {
		try {
			logger.info("start to query supplier data!");
			SysUser loginMan = getSessionUserInfo();
			if (this.supplier == null) {
				this.supplier = new Supplier();
			}
			String id = this.supplier.getId();
			if (StringUtils.isBlank(id)) {
				super.initModel(true, this.supplier, loginMan);
			} else {
				this.supplier = ((Supplier) this.supplierService.getModel(id));
				super.initModel(false, this.supplier, loginMan);
			}
		} catch (Exception e) {
			logger.info("error occur when quering supplier data!");
			e.printStackTrace();
		}
		logger.info("finish quering supplier data!");
		return "edit_supplier";
	}

	public void save() {
		try {
			String id = this.supplier.getId();
			if (StringUtils.isBlank(id)) {
				String code = this.serialNumberService.getSerialNumberNoDate("", "Supplier", 4);
				this.supplier.setCode(code);
				this.supplierService.insert(this.supplier);
			} else {
				this.supplierService.update(this.supplier);
			}
			responseFlag(true);
		} catch (Exception e) {
			responseFlag(false);
			logger.error("error occur when save model!", e);
		}
	}

	public void delete() {
		SysUser loginMan = getSessionUserInfo();

		String id = this.supplier.getId();
		logger.info("delete Supplier,id:" + id);
		try {
			String[] idArr = id.split(",");
			for (String idStr : idArr) {
				this.supplierService.delete(idStr);
			}
			logger.info(loginMan.getCode() + " delete Supplier,id:" + id);
			responseFlag(true);
		} catch (Exception e) {
			responseFlag(false);
			logger.info("error occur when " + loginMan.getCode() + " delete Supplier,id:" + id, e);
		}
	}

	public void isCodeExisted() {
		boolean isCodeExisted = true;

		String id = this.supplier.getId();
		String code = this.supplier.getCode();
		logger.info("check isCodeExisted,code:" + code + ";id:" + id);
		try {
			Supplier sub = this.supplierService.getSupplier(this.supplier);
			if (sub == null) {
				isCodeExisted = false;
			} else if (id.equals(sub.getId())) {
				isCodeExisted = false;
			} else {
				isCodeExisted = true;
			}
			logger.info("check isCodeExisted result:" + isCodeExisted);
			responseFlag(isCodeExisted);
		} catch (Exception e) {
			logger.error("error occur when check isCodeExisted!", e);
		}
	}

	public Supplier getSupplier() {
		return this.supplier;
	}

	public void setSupplier(Supplier supplier) {
		this.supplier = supplier;
	}
}

redpajama_set_name: RedPajamaGithub


text:
$(function () {

  $.unblockUI();

  function getRules() {
    var rules = {};

    $('input.required').each(function() {
      rules[$(this).attr('id')] = { required: true };
    });

    return rules;
  }

  $("#content_form").validate({
    rules: getRules(),
    errorClass: "help-block error",
    errorPlacement: function (error, element) {
      error.insertAfter(element);
    },
    highlight: function (label) {
      $(label).closest('.form-group').removeClass('has-success').addClass('has-error');
    },
    success: function (label) {
      $(label).closest('.form-group').removeClass('has-error').addClass('has-success');
    },
    debug: true
  });

});


text: Web Interface for the barbie application


text:
MO_NAMESPACE_BEGIN

MO_CLASS_IMPLEMENT_INHERITS(FPd10RenderShaderBuffer, FRenderProgramBuffer);

//============================================================
// <T>¹¹ÔìäÖȾÆ÷»º³å¡£</T>
//============================================================
FPd10RenderShaderBuffer::FPd10RenderShaderBuffer(){
   MO_CLEAR(_piBuffer);
}

//============================================================
// <T>Îö¹¹äÖȾÆ÷»º³å¡£</T>
//============================================================
FPd10RenderShaderBuffer::~FPd10RenderShaderBuffer(){
   MO_RELEASE(_piBuffer);
}

//============================================================
// <T>ÅäÖô¦Àí¡£</T>
//
// @return ´¦Àí½á¹û
//============================================================
TResult FPd10RenderShaderBuffer::OnSetup(){
   TResult resultCd = FRenderProgramBuffer::OnSetup();
   MO_CHECK(_pDevice, return ENull);
   MO_CHECK(_dataLength > 0, return EOutRange);
   FPd10RenderDevice* pRenderDevice = _pDevice->Convert<FPd10RenderDevice>();
   // ÉèÖÃÃèÊö
   D3D10_BUFFER_DESC descriptor = {0};
   descriptor.ByteWidth = _dataLength;
   descriptor.Usage = D3D10_USAGE_DEFAULT;
   descriptor.BindFlags = D3D10_BIND_CONSTANT_BUFFER;
   descriptor.CPUAccessFlags = 0;
   descriptor.MiscFlags = 0;
   // ÉèÖÃÊý¾Ý
   D3D10_SUBRESOURCE_DATA data = {0};
   data.pSysMem = _pData->Memory();
   data.SysMemPitch = 0;
   data.SysMemSlicePitch = 0;
   // ´´½¨»º³å
   HRESULT dxResult = pRenderDevice->NativeDevice()->CreateBuffer(&descriptor, &data, &_piBuffer);
   if(FAILED(dxResult)){
      MO_FATAL("Create buffer failure.");
      return EFailure;
   }
   return resultCd;
}

//============================================================
// <T>Ìá½»´¦Àí¡£</T>
//
// @return ´¦Àí½á¹û
//============================================================
TResult FPd10RenderShaderBuffer::Commit(){
   MO_CHECK(_pDevice, return ENull);
   TResult resultCd = ESuccess;
   FPd10RenderDevice* pRenderDevice = _pDevice->Convert<FPd10RenderDevice>();
   //............................................................
   // ¸üÐÂÊý¾Ý
   TByte* pData = _pData->Memory();
   TInt length = _pData->Length();
   pRenderDevice->NativeDevice()->UpdateSubresource(_piBuffer, 0, NULL, pData, 0, 0);
   //MO_DEBUG("Update sub resource. (name=%s, memory=0x%08X, length=%d)", (TCharC*)_name, pData, length);
   //GetErrorInfo();
   return resultCd;
}

//============================================================
// <T>°ó¶¨´¦Àí¡£</T>
//
// @return ´¦Àí½á¹û
//============================================================
TResult FPd10RenderShaderBuffer::Bind(){
   // ¼ì²éÊÇ·ñ±ä¸ü
   if(!_statusChanged){
      return EContinue;
   }
   //............................................................
   MO_CHECK(_pDevice, return ENull);
   MO_CHECK(_slot >= 0, return EOutRange);
   TResult resultCd = ESuccess;
   FPd10RenderDevice* pRenderDevice = _pDevice->Convert<FPd10RenderDevice>();
   //............................................................
   // ¸üÐÂÊý¾Ý
   if((_groupCd == ERenderShaderBuffer_Global) || (_groupCd == ERenderShaderBuffer_Technique) || (_groupCd == ERenderShaderBuffer_Effect)){
      pRenderDevice->NativeDevice()->VSSetConstantBuffers(_slot, 1, &_piBuffer);
      pRenderDevice->NativeDevice()->PSSetConstantBuffers(_slot, 1, &_piBuffer);
   }else if(_groupCd == ERenderShaderBuffer_Renderable){
      // ¸üÐÂÏÔʾÏà¹Ø
      if(_shaderCd == ERenderShader_Vertex){
         pRenderDevice->NativeDevice()->VSSetConstantBuffers(_slot, 1, &_piBuffer);
      }else if(_shaderCd == ERenderShader_Fragment){
         pRenderDevice->NativeDevice()->PSSetConstantBuffers(_slot, 1, &_piBuffer);
      }else{
         MO_FATAL("Render shader type is unknown. (shader=%d)", _shaderCd);
      }
   }else{
      MO_FATAL("Render shader group is unknown. (group=%d)", _groupCd);
   }
   return resultCd;
}

MO_NAMESPACE_END


text:
/**
 * Adds commas to a number
 * @param {number} number
 * @param {string} locale
 * @return {string}
 */

const Flickr = require('flickr-sdk');
const fs = require('fs');
const request = require('request');
const config = require('./config.js');

const PLUGIN_FOLDER = 'lr-latest.widget';

const flickr = new Flickr(config.flickr);

let randomAlbum;
let responsePhoto;
let photo;
let url;
let index;

const _createFolder = () => {
  if (!fs.existsSync(`./${PLUGIN_FOLDER}`)){
      fs.mkdirSync(`./${PLUGIN_FOLDER}`);
  }
};

const _saveWallpaper = (response) => {
  _createFolder();
  responsePhoto = response.body.photoset.photo;
  photo = responsePhoto[Math.floor(Math.random() * responsePhoto.length)];
  url = `https://farm${photo.farm}.staticflickr.com/${photo.server}/${photo.id}_${photo.originalsecret}_o.${photo.originalformat}`;
  request(url).pipe(fs.createWriteStream(`${PLUGIN_FOLDER}/wallpaper.${photo.originalformat}`));
};

const _processWallpaper = (promise) => {
  promise
    .then(_saveWallpaper);
};

const _retrieveWallpaper = (randomAlbum) => {
  return flickr
    .request()
    .albums(randomAlbum)
    .media()
    .get({
      extras: 'original_format',
    });
};

const getWallpaper = () => {
  randomAlbum = config.wallpapers[Math.floor(Math.random() * config.wallpapers.length)];
  _processWallpaper(_retrieveWallpaper(randomAlbum));
};

const _savePictures = (response) => {
  let tags = config.tags;
  responsePhoto = response.body.photos.photo;

  _createFolder();

  for (let i = 0; i < responsePhoto.length && tags.length; i += 1) {
    photo = responsePhoto[i];
    index = config.tags.indexOf(photo.tags);

    if (photo.tags && index > -1) {
      url = `https://farm${photo.farm}.staticflickr.com/${photo.server}/${photo.id}_${photo.secret}_z.jpg`;
      request(url).pipe(fs.createWriteStream(`${PLUGIN_FOLDER}/${photo.tags}.jpg`));
      tags.splice(index, 1);
    }
  }
};

const _processPictures = (promise) => {
  promise
    .then(_savePictures);
};

const _retrievePictures = () => {
  return flickr
    .request()
    .people(config.personalId)
    .media()
    .get({
      media: 'photos',
      tags: config.tags.join(),
      sort: 'date-taken-desc',
      extras: 'tags, date_taken, date_upload',
    });
};

const getPictures = () => {
  // randomAlbum = config.galleries[Math.floor(Math.random() * config.galleries.length)];
  _processPictures(_retrievePictures());
};

const init = () => {
  getPictures();
  getWallpaper();
};

init();

module.exports = {
  _createFolder,
  _saveWallpaper,
  _savePictures,
  _retrieveWallpaper,
  _retrievePictures,
  getWallpaper,
  getPictures,

};


text:
case class CaseTest[_](someData: String)

// was: _ already defined, now a fresh name
case class CaseTest2[_, _](someData: String)

class C {
  def f[_](x: Int) = ???
}


text:
"""Rendering views.

A view is a function that returns something. This can be a
:class:`morepath.Response`, but it can also be a structure (such a
dict) that should be rendered *to* a response. If the view is a JSON
view this dumps this structure as JSON. If the view is a HTML view
this structure can be converted to HTML using a template.

:func:`morepath.render_json`, :func:`morepath.render_html` and
:func:`morepath.redirect` are members of the public API.

See also :class:`morepath.directive.ViewRegistry`
"""

import json
from webob.exc import HTTPFound, HTTPNotFound, HTTPForbidden
from webob import Response as BaseResponse

from .request import Response
from .template import TemplateEngineRegistry

class View(object):
    """A view as registered in the view registry.

    :param func: view function. Given a model instance and a request
      argument, this function must return either a structure that can
      be turned into a response or a response.
    :param render: a function used to render view function return value
      as a response.
    :param permission: permission class that the identity must have
      according to permission rules. If the view doesn't have the
      permission access is forbidden.
    :param internal: bool to indicate whether this view is internal.
      If the view is internal you can use it with
      :meth:`morepath.Request.view` but it doesn't have a URL
      and will be 404 Not Found.
    """
    def __init__(self, func, render, permission, internal):
        self.func = func
        self.render = render
        self.permission = permission
        self.internal = internal

    def __call__(self, app, obj, request):
        """Render a model instance.

        If view is internal it cannot be rendered.

        If the identity does not have the permission for
        this object according to the permission rules then
        :class:`webob.exc.HTTPForbidden` is raised.

        Any functions specified using :meth:`morepath.Request.after`
        are run against the response once it is created, if that
        response is not an error.

        :param obj: the model instance
        :param request: the request
        :return: A :class:`webob.response.Response` instance.
        """
        if self.internal:
            raise HTTPNotFound()
        if self.permission is not None and\
           not request.app._permits(request.identity, obj, self.permission):
            raise HTTPForbidden()
        content = self.func(obj, request)
        if isinstance(content, BaseResponse):
            # the view took full control over the response
            response = content
        else:
            response = self.render(content, request)

        # run request after if it's a 2XX or 3XX response
        if response.status[0] in ('2', '3'):
            request.run_after(response)

        return response

def render_view(content, request):
    """Default render function for view if none was supplied.

    This just assumes the content is a string and renders it into
    a response.

    :param content: content as returned by view function.
    :param request: request object
    :return: a response instance with the content.
    """
    return Response(content, content_type='text/plain')

class ViewRegistry(object):
    """A registry of views.

    :param template_engine_registry: a
      :class:`morepath.directive.TemplateEngineRegistry` used to render
      templated views.
    """
    factory_arguments = {
        'template_engine_registry': TemplateEngineRegistry,
    }

    app_class_arg = True

    def __init__(self, template_engine_registry, app_class):
        self.template_engine_registry = template_engine_registry
        self.app_class = app_class

    def predicate_key(self, key_dict):
        """Given a dictionary create a unique predicate key.

        See also :meth:`reg.Registry.key_dict_to_predicate_key`.

        :param key_dict: a dict containing view registration info,
          for instance model, request_method, etc.
        :result: an immutable object representing the predicate.
        """
        return self.app_class.get_view.key_dict_to_predicate_key(key_dict)

    def register_view(self, key_dict, view,
                      render=render_view,
                      template=None,
                      permission=None,
                      internal=False):
        """Register a view.

        :param key_dict: a dict containing view registration info,
          for instance model, request_method, etc.
        :param view: the view function as registered.
        :param render_view: the render function to use to turn the view
          function result value into a response. By default the content
          is interpreted as a string body.
        :param template: the template used to render the view function
          result value into a response. By default there is no template.
        :param permission: the permission class used to check whether the
          identity is permitted to use the view on the model instance.
        :param internal: whether this view is internal or not.
        """
        if template is not None:
            render = self.template_engine_registry.get_template_render(
                template, render)
        v = View(view, render, permission, internal)
        self.app_class.get_view.register(v, **key_dict)

def render_json(content, request):
    """Take dict/list/string/number content and return json response.

    This respects the :meth:`morepath.App.dump_json` directive that
    can be used to serialize any object to JSON. By default this
    serializes Python objects like dicts, strings to JSON.

    :param content: content as returned from view function.
    :param request: a :class:`morepath.Request` instance.
    :return: a :class:`morepath.Response` instance with a serialized
      JSON body.
    """
    return Response(json.dumps(request.app._dump_json(content, request)),
                    content_type='application/json')

def render_html(content, request):
    """Take string and return text/html response.

    :param content: contnet as returned from view function.
    :param request: a :class:`morepath.Request` instance.
    :return: a :class:`morepath.Response` instance with ``content``
      as the body.
    """
    return Response(content, content_type='text/html')

def redirect(location):
    """Return a response object that redirects to location.

    :param location: a URL to redirect to.
    :return: a :class:`webob.exc.HTTPFound` response object. You can
      return this from a view to redirect.
    """
    return HTTPFound(location=location)


text:
import sys
import os

ANY = True
UNIXY = os.sep == '/'
WINDOWS = not UNIXY
JYTHON = sys.platform.startswith('java')
if UNIXY:
    DEFAULT_SYSTEM_ENCODING = 'UTF-8'
    DEFAULT_OUTPUT_ENCODING = 'UTF-8'
else:
    DEFAULT_SYSTEM_ENCODING = 'cp1252'
    DEFAULT_OUTPUT_ENCODING = 'cp437'

def get_system_encoding():
    platform_getters = [(ANY, _get_python_system_encoding),
                        (JYTHON, _get_java_system_encoding),
                        (UNIXY, _get_unixy_encoding),
                        (WINDOWS, _get_windows_system_encoding)]
    return _get_encoding(platform_getters, DEFAULT_SYSTEM_ENCODING)

def get_output_encoding():
    platform_getters = [(ANY, _get_stream_output_encoding),
                        (UNIXY, _get_unixy_encoding),
                        (WINDOWS, _get_windows_output_encoding)]
    return _get_encoding(platform_getters, DEFAULT_OUTPUT_ENCODING)

def _get_encoding(platform_getters, default):
    for platform, getter in platform_getters:
        if platform:
            encoding = getter()
            if _is_valid(encoding):
                return encoding
    return default

def _get_python_system_encoding():
    return sys.getfilesystemencoding()

def _get_java_system_encoding():
    from java.lang import System
    return System.getProperty('file.encoding')

def _get_unixy_encoding():
    for name in 'LANG', 'LC_CTYPE', 'LANGUAGE', 'LC_ALL':
        if name in os.environ:
            # Encoding can be in format like `UTF-8` or `en_US.UTF-8`
            encoding = os.environ[name].split('.')[-1]
            if _is_valid(encoding):
                return encoding
    return None

def _get_stream_output_encoding():
    # http://bugs.jython.org/issue1568
    if WINDOWS and JYTHON:
        if sys.platform.startswith('java1.5') or sys.version_info < (2, 5, 2):
            return None
    # Stream may not have encoding attribute if it is intercepted outside RF
    # in Python. Encoding is None if process's outputs are redirected.
    for stream in sys.__stdout__, sys.__stderr__, sys.__stdin__:
        encoding = getattr(stream, 'encoding', None)
        if _is_valid(encoding):
            return encoding
    return None

def _get_windows_system_encoding():
    from ctypes import cdll
    return _call_ctypes(cdll.kernel32.GetACP)

def _get_windows_output_encoding():
    from ctypes import cdll
    return _call_ctypes(cdll.kernel32.GetOEMCP)

def _call_ctypes(method):
    method.argtypes = ()  # needed w/ jython (at least 2.5)
    try:
        return 'cp%s' % method()
    except Exception:  # Has failed on IronPython at least once
        return None

def _is_valid(encoding):
    if not encoding:
        return False
    try:
        'test'.encode(encoding)
    except LookupError:
        return False
    else:
        return True


text:
<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.keedio.flume.interceptor.cacheable</groupId>
    <artifactId>flume-cacheable-interceptor</artifactId>
    <version>0.0.12</version>
    <packaging>jar</packaging>

    <name>flume cacheable interceptor</name>
    <description>Enriquece en base a un criterio de selección de campos alojados en un archivo externo en formato CSV</description>

    <licenses>
        <license>
            <name>The Apache License, Version 2.0</name>
            <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
        </license>
    </licenses>

    <url>https://github.com/keedio/CacheableInterceptor</url>

    <developers>
        <developer>
            <name>Luca Rosellini</name>
            <email>lrosellini@keedio.org</email>
            <organization>Keedio</organization>
            <organizationUrl>http://www.keedio.com</organizationUrl>
        </developer>
        <developer>
            <name>Emmanuelle Raffenne</name>
            <email>eraffenne@keedio.org</email>
            <organization>Keedio</organization>
            <organizationUrl>http://www.keedio.com</organizationUrl>
        </developer>
        <developer>
            <name>Luis Lázaro Medina</name>
            <email>lalazaro@keedio.org</email>
            <organization>Keedio</organization>
            <organizationUrl>http://www.keedio.com</organizationUrl>
        </developer>
    </developers>

    <scm>
        <connection>scm:git:git@github.com:keedio/CacheableInterceptor.git</connection>
        <developerConnection>scm:git:git@github.com:keedio/CacheableInterceptor.git</developerConnection>
        <url>https://github.com/keedio/CacheableInterceptor</url>
    </scm>

    <properties>
        <!-- Generic properties -->
        <java.version>1.7</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

        <!--  Dependency versions -->
        <flume.core.version>1.6.0</flume.core.version>
        <spring-framework.version>4.1.5.RELEASE</spring-framework.version>
        <ehcache.version>2.9.1</ehcache.version>
        <testng.version>6.1.1</testng.version>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring-framework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring-framework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring-framework.version}</version>
        </dependency>
        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache</artifactId>
            <version>${ehcache.version}</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
            <version>1.9.5</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.flume</groupId>
            <artifactId>flume-ng-core</artifactId>
            <version>${flume.core.version}</version>
            <scope>provided</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.apache.avro</groupId>
                    <artifactId>avro</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.apache.avro</groupId>
                    <artifactId>avro-ipc</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.keedio.flume.interceptor.enrichment</groupId>
            <artifactId>flume-enrichment-interceptor</artifactId>
            <version>0.1.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.opencsv</groupId>
            <artifactId>opencsv</artifactId>
            <version>3.2</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-core-asl</artifactId>
            <version>1.9.13</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.13</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>com.googlecode.juniversalchardet</groupId>
            <artifactId>juniversalchardet</artifactId>
            <version>1.0.3</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.github.tony19</groupId>
            <artifactId>named-regexp</artifactId>
            <version>0.2.3</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.18.1</version>
                    <configuration>
                        <forkCount>2</forkCount>
                        <reuseForks>false</reuseForks>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>

        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <transformers>
                        <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                            <resource>META-INF/spring.schemas</resource>
                        </transformer>
                        <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                            <resource>META-INF/spring.handlers</resource>
                        </transformer>
                    </transformers>
                </configuration>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>


text:
var React = require('React');

var a = React.createElement(
  Foo,
  null,
  React.createElement('div', { foo: 'bar' }),
  React.createElement(
    'span',
    null,
    'blah'
  )
);


text:
function noise = noiseCreate(noiseType, y)

% NOISECREATE Initialise a noise structure.
% FORMAT
% DESC takes a noise type and a target vector and initialises a
% noise structure from it. The parameters of the noise structure
% are the set by calling noiseParamInit.
% ARG noiseType : the type of noise to be created (e.g. 'gaussian',
% 'probit', 'ncnm').
% ARG y : the target vector.
%
% COPYRIGHT : Neil D. Lawrence, 2004, 2005
%
% SEEALSO : noiseParamInit

% GPMAT

if isstruct(noiseType)
  noise = noiseType;
  return
elseif iscell(noiseType)
  % compound noise type
  noise.type = 'cmpnd';
  if nargin > 1
    for i = 1:length(noiseType)
      noise.comp{i} = noiseCreate(noiseType{i}, y(:, i));
    end
  else
    for i = 1:length(noiseType)
      noise.comp{i} = noiseCreate(noiseType{i});
    end
  end
else
  noise.type = noiseType;
end

if nargin>1
  noise = noiseParamInit(noise, y);
end

% Check if the noise model has bespoke site update code
if exist([noise.type 'NoiseSites'])==2
  noise.updateSites = 1;
else
  noise.updateSites = 0;
end

% Check if the model has bespoke nu and g update code.
if exist([noise.type 'NoiseNuG'])==2
  noise.updateNuG = 1;
else
  noise.updateNuG = 0;
end


text:
export DEST="./.exvim.fv"
export TOOLS="/home/ylf/.vim/tools/"
export TMP="${DEST}/_inherits"
export TARGET="${DEST}/inherits"
sh ${TOOLS}/shell/bash/update-inherits.sh


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Tagging;
using Microsoft.VisualStudio.Utilities;

namespace Microsoft.VisualStudio.LanguageServices.Implementation.Preview
{
    [Export(typeof(IViewTaggerProvider))]
    [TagType(typeof(HighlightTag))]
    [ContentType(ContentTypeNames.RoslynContentType)]
    [ContentType(ContentTypeNames.XamlContentType)]
    internal class PreviewTaggerProvider : IViewTaggerProvider
    {
        public ITagger<T> CreateTagger<T>(ITextView textView, ITextBuffer buffer) where T : ITag
        {
            if (PreviewUpdater.TextView == textView)
            {
                return PreviewUpdater.Tagger as ITagger<T>;
            }

            return null;
        }
    }
}


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <meta name="viewport" content="width=device-width">

        <title>Random Thoughts : Rough Tricks</title>
        <meta name="description" content="A wiki of my random thoughts.">

	<link rel="stylesheet" type="text/css"
	      href="http://spratt.github.io/Computer-Modern/cmserif.css" />

        <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css" rel="stylesheet">
        <link rel="stylesheet" href="/css/syntax.css">
        <link rel="stylesheet" href="/css/main.css">

Random Thoughts
    A wiki of my random thoughts.

Home

About

Machine Learning

Convolutional Auto-encoder

Extreme Learning Machine

Neuroscience

Information Theory

Neural Decoding

Neural Encoding

Synapse

Nervous System

Mechanistic Models

Interpretive Models

Descriptive Models

Neuron

Computer Science

Rough Tricks

Using ctexart

Linux Tricks

Set up Emacs

References

Model Pool

NSC Info

Learning Deep Learning

Tutorial

Feedforword Model

Feedforward Layer

Google Charts

Softmax Regression

Recurrent Neural Neworks

Multi Layer Perceptron Layers

ConvNets

Auto-encoder

Deep Learning Prequel

ConvNetJS

Life Journal

Daily Journal

The Killer Machine

A Story of My OS

Rough Tricks

I'm learning stuffs everyday. Sometimes when I had an idea, and tried to implement it, I will do lots of searches and trails in order to complete the mission. But I'm a horrible person of memorizing these tricks (especially on web programming). Hence, I had this page to document all kinds of tricks related to programming and application design.

highlight.js Language Highlighting Reference

Sometimes I forget the shortcut of the programming language when I use code highlighting, you can find it here.

Customize HTML Table Style

table {
    border-collapse: collapse;
}

table, th, td{
    border: 1px solid #dedede;
}

tr:nth-child(even){
    background: #f2f2f2
}

tr:nth-child(odd){
    background: #fff
}

.table th, .table td{
    padding: 20px;
}

tr:hover, td:hover{
    background: #ffff99;
}

Use Google Maps

A good start of this is to check out Google's documentation: Add a Google Map to your website. Here I give an example of include Google Map in GitHub pages.

First of all, you need to include Google Maps javascript in your layout:

<script src="https://maps.googleapis.com/maps/api/js"></script>

You can usually find layout scripts in _layout (example).

#map-canvas {
    width: 500px;
    height: 400px;
}

Here you can set the width and height of the map that you want to display.

Then, in you post, you need to define the specifics by implementing initialize function:

<script>
    function initialize() {
        var mapCanvas = document.getElementById('map-canvas');
        var mapOptions = {
            center: new google.maps.LatLng(44.5403, -78.5463),
            zoom: 8,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        var map = new google.maps.Map(mapCanvas, mapOptions)
    }
    google.maps.event.addDomListener(window, 'load', initialize);
</script>

In mapOptions, you can specify details of your desire map. You can find all supported options from here.

After you did everything, you can simply include the map as follows:

<div id="map-canvas"></div>

Google Charts

I'm looking for a way of visualizing my data in website, and then I found this nice API that is written by Google, namely Google Charts, you can find the full documentation here

Setup Theano in OSX

Setting up Theano on my MacBook Pro used to be hard. I don't have a GPU on it, and apparently it's hard to get all requirements easily for OSX. I found the solution today, first, install Anaconda, a nice python distribution that is designed for scientific computing.

However, you will notice that Anaconda itself does not offer you a maintained install of Theano. Then we have to get it from another place: binstar.

You can install the OSX build Theano by:

conda install -c https://conda.binstar.org/shoyer theano

Test for embedding YouTube Videos

Generate a pure HTML site

                    Documentation for Random Thoughts

Except where otherwise noted, content on this site is licensed under a Creative Commons Attribution 4.0 International License

CrowdProcess Is Running On Your Browser


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Lycopsis obtusifolia Willd.

### Remarks
null


text:
package com.ilivoo.jackson.example;

import java.util.List;

import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
 *1. mapper.configure(SerializationFeature.INDENT_OUTPUT, true); 输出漂亮的格式
 *2. mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);忽略在json转换成对象的时候, 但是对象中没有相关的属性, 此时就不会报错
 */
public class ObjectMapperTest {
	private static ObjectMapper mapper = new ObjectMapper();

	public static void main(String[] args) {
		ObjectMapperTest omt = new ObjectMapperTest();
		omt.testStatic();
	}

	public void testStatic(){
		List<Module> modules = ObjectMapper.findModules();
		System.out.println(modules.size());
		for(Module module: modules){
			System.out.println(module.getModuleName());
		}
	}

}


text:
import argparse
import os
import json
import csv
import scipy as sp
import cv2

MATCH_FILE = "matches.f.txt"

def showKeypointMatch(matchFolder, matchFile, ind1, ind2):
    sfm_data_dir = os.path.join(matchFolder,"sfm_data.json")
    matchFile = os.path.join(matchFolder,matchFile)

    with open(sfm_data_dir) as sfm_data_file:
        sfm_data = json.load(sfm_data_file)

    rootpath = sfm_data["root_path"]

    file1 = sfm_data["views"][ind1]["value"]["ptr_wrapper"]["data"]["filename"]
    img1 = os.path.join(rootpath,file1)
    img1Mat = cv2.imread(img1)
    feat1 = os.path.join(matchFolder,file1[0:-3]+"feat")

    file2 = sfm_data["views"][ind2]["value"]["ptr_wrapper"]["data"]["filename"]
    img2 = os.path.join(rootpath,file2)
    img2Mat = cv2.imread(img2)
    feat2 = os.path.join(matchFolder,file2[0:-3]+"feat")

    feat1Data = [ row for row in csv.reader(open(feat1, "r"), delimiter=' ') if len(row) != 0]
    feat2Data = [ row for row in csv.reader(open(feat2, "r"), delimiter=' ') if len(row) != 0]
    matchData = []
    with open(matchFile, "r") as f:
        reader = csv.reader(f, delimiter=' ')
        while True:
            try:
                imagePair = next(reader)
                matchNum = next(reader)
                for x in range(int(matchNum[0])):
                    keypointPair = next(reader)
                    if (int(imagePair[0])==ind1 and int(imagePair[1])==ind2):
                        matchData.append([int(keypointPair[0]),int(keypointPair[1])])
                    elif (int(imagePair[0])==ind2 and int(imagePair[1])==ind1):
                        matchData.append([int(keypointPair[1]),int(keypointPair[0])])
            except csv.Error:
                print "Error"
            except StopIteration:
                break

    # visualization
    h1, w1 = img1Mat.shape[:2]
    h2, w2 = img2Mat.shape[:2]
    view = sp.zeros((max(h1, h2), w1 + w2, 3), sp.uint8)
    view[:h1, :w1] = img1Mat
    view[:h2, w1:] = img2Mat

    for m in matchData:
        # draw the keypoints
        # print m.queryIdx, m.trainIdx, m.distance
        color = tuple([sp.random.randint(0, 255) for _ in xrange(3)])
        cv2.line(view, (int(float(feat1Data[m[0]][0])), int(float(feat1Data[m[0]][1]))), (int(float(feat2Data[m[1]][0])) + w1, int(float(feat2Data[m[1]][1]))), color)

    cv2.imshow("image 1", cv2.resize(img1Mat, (0,0), fx=0.5, fy=0.5))
    cv2.imshow("image 2", cv2.resize(img2Mat, (0,0), fx=0.5, fy=0.5))
    cv2.imshow("matching", cv2.resize(view, (0,0), fx=0.5, fy=0.5))
    cv2.waitKey(1)

def main():
    description = 'This script is for visualizing putative matching result created by OpenMVG. '
    parser = argparse.ArgumentParser(description=description)
    parser.add_argument('match_dir', action='store', nargs=None, const=None, \
                        default=None, type=str, choices=None, metavar=None, \
                        help='Directory path where matches results is stored.')
    parser.add_argument('ind1', action='store', nargs=None, const=None, \
                        default=None, type=int, choices=None, metavar=None, \
                        help='view index 1.')
    parser.add_argument('ind2', action='store', nargs=None, const=None, \
                        default=None, type=int, choices=None, metavar=None, \
                        help='view index 2.')
    args = parser.parse_args()
    matchFolder = args.match_dir
    ind1 = args.ind1
    ind2 = args.ind2

    while True:
        print "show matching images : ",ind1," <-> ",ind2
        showKeypointMatch(matchFolder, MATCH_FILE, ind1, ind2)
        key = cv2.waitKey(-1)
        if key==65362: # up
            ind1 += 1
        elif key==65364: # down
            ind1 -= 1
        elif key==65361: # left
            ind2 += 1
        elif key==65363: # right
            ind2 -= 1
        elif key==27:
            break

if __name__ == "__main__":
    main()


text:
#pragma once
#include <aws/route53resolver/Route53Resolver_EXPORTS.h>
#include <aws/route53resolver/Route53ResolverRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Route53Resolver
{
namespace Model
{

  /**
   */
  class AWS_ROUTE53RESOLVER_API GetResolverRuleAssociationRequest : public Route53ResolverRequest
  {
  public:
    GetResolverRuleAssociationRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "GetResolverRuleAssociation"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
The ID of the Resolver rule association that you want to get information
     * about.

     */
    inline const Aws::String& GetResolverRuleAssociationId() const{ return m_resolverRuleAssociationId; }

    /**
     *
The ID of the Resolver rule association that you want to get information
     * about.

     */
    inline bool ResolverRuleAssociationIdHasBeenSet() const { return m_resolverRuleAssociationIdHasBeenSet; }

    /**
     *
The ID of the Resolver rule association that you want to get information
     * about.

     */
    inline void SetResolverRuleAssociationId(const Aws::String& value) { m_resolverRuleAssociationIdHasBeenSet = true; m_resolverRuleAssociationId = value; }

    /**
     *
The ID of the Resolver rule association that you want to get information
     * about.

     */
    inline void SetResolverRuleAssociationId(Aws::String&& value) { m_resolverRuleAssociationIdHasBeenSet = true; m_resolverRuleAssociationId = std::move(value); }

    /**
     *
The ID of the Resolver rule association that you want to get information
     * about.

     */
    inline void SetResolverRuleAssociationId(const char* value) { m_resolverRuleAssociationIdHasBeenSet = true; m_resolverRuleAssociationId.assign(value); }

    /**
     *
The ID of the Resolver rule association that you want to get information
     * about.

     */
    inline GetResolverRuleAssociationRequest& WithResolverRuleAssociationId(const Aws::String& value) { SetResolverRuleAssociationId(value); return *this;}

    /**
     *
The ID of the Resolver rule association that you want to get information
     * about.

     */
    inline GetResolverRuleAssociationRequest& WithResolverRuleAssociationId(Aws::String&& value) { SetResolverRuleAssociationId(std::move(value)); return *this;}

    /**
     *
The ID of the Resolver rule association that you want to get information
     * about.

     */
    inline GetResolverRuleAssociationRequest& WithResolverRuleAssociationId(const char* value) { SetResolverRuleAssociationId(value); return *this;}

  private:

    Aws::String m_resolverRuleAssociationId;
    bool m_resolverRuleAssociationIdHasBeenSet = false;
  };

} // namespace Model
} // namespace Route53Resolver
} // namespace Aws


text:
package com.github.wesleyegberto.fastpass;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@SpringBootApplication
@EnableEurekaClient
public class M2FastpassServiceApplication {

	public static void main(String[] args) {
		SpringApplication.run(M2FastpassServiceApplication.class, args);
	}

}


text:
{% extends "base.html" %}

{% block title %}
{{flatpage.title}}{{block.super}}
{% endblock %}

{% block content %}

{{ flatpage.title }}

		    {{ flatpage.content }}

{% endblock %}


text:
<?php

/* MylibberMylibBundle:Book:list.html.twig */
class __TwigTemplate_a4f405deceec706e51316b2f69ac618e extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = $this->env->loadTemplate("MylibberMylibBundle::layout.html.twig");

        $this->blocks = array(
            'bookName' => array($this, 'block_bookName'),
            'body' => array($this, 'block_body'),
            'sidebar' => array($this, 'block_sidebar'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "MylibberMylibBundle::layout.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 3
    public function block_bookName($context, array $blocks = array())
    {
        echo twig_escape_filter($this->env, $this->getAttribute($this->getContext($context, "book"), "bookName"), "html", null, true);
    }

    // line 5
    public function block_body($context, array $blocks = array())
    {
        // line 6
        echo "

       ";
        // line 7
        $context["i"] = 0;
        // line 8
        $context['_parent'] = (array) $context;
        $context['_seq'] = twig_ensure_traversable($this->getContext($context, "books"));
        foreach ($context['_seq'] as $context["_key"] => $context["book"]) {
            // line 9
            echo "    ";
            $context["i"] = ($this->getContext($context, "i") + 1);
            // line 10
            echo "

            ";
            // line 11
            echo twig_escape_filter($this->env, $this->getContext($context, "i"), "html", null, true);
            echo ".
            书籍名称:";
            // line 12
            echo twig_escape_filter($this->env, $this->getAttribute($this->getContext($context, "book"), "bookName"), "html", null, true);
            echo "
            作者: ";
            // line 13
            echo twig_escape_filter($this->env, $this->getAttribute($this->getContext($context, "book"), "bookAuthor"), "html", null, true);
            echo "
            ISBN: ";
            // line 14
            echo twig_escape_filter($this->env, $this->getAttribute($this->getContext($context, "book"), "bookIsbn"), "html", null, true);
            echo "

            ";
            // line 16
            if (($this->getAttribute($this->getContext($context, "book"), "BookBorr") == 1)) {
                echo " 可借阅  ";
            } else {
                echo " 不可借阅 ";
            }
            // line 17
            echo "            env, $this->env->getExtension('routing')->getPath("MylibberMylibBundle_detail", array("id" => $this->getAttribute($this->getContext($context, "book"), "Id"))), "html", null, true);
            echo "\">详细信息...

";
        }
        $_parent = $context['_parent'];
        unset($context['_seq'], $context['_iterated'], $context['_key'], $context['book'], $context['_parent'], $context['loop']);
        $context = array_merge($_parent, array_intersect_key($context, $_parent));
        // line 21
        echo "

";
    }

    // line 26
    public function block_sidebar($context, array $blocks = array())
    {
        // line 27
        echo "
书籍检索
<form action=\"";
        // line 29
        echo twig_escape_filter($this->env, $this->env->getExtension('routing')->getPath("MylibberMylibBundle_search"), "html", null, true);
        echo "\" method=\"get\" name=\"f\" onsubmit=\"return chkForm(this)\" id=\"f\">

                请输入检索关键字:
                    <input type=\"text\" name=\"strText\" id=\"strText\" value=\"\">

                请选择检索类型:

                    <select class=\"option\" name=\"SearchType\" size=\"1\" style=\"width:100px;\">
                        <option value=\"title\">题  名</option>
                        <option value=\"isbn\">ISBN/ISSN</option>
                    </select>

                    <input type=\"submit\" class=\"submit\" value=\"检索\">

    </form>
";
    }

    public function getTemplateName()
    {
        return "MylibberMylibBundle:Book:list.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  101 => 29,  97 => 27,  94 => 26,  86 => 21,  75 => 17,  69 => 16,  64 => 14,  60 => 13,  56 => 12,  52 => 11,  49 => 10,  46 => 9,  42 => 8,  40 => 7,  37 => 6,  34 => 5,  28 => 3,);
    }
}


text:
import WbInputDatePicker from './inputPicker.vue';
import DatePicker from './datePicker.vue';

export default {
    WbInputDatePicker, DatePicker
}


text:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Magicolo;

namespace Magicolo.AudioTools {
	[System.Serializable]
	public class PureDataSequenceTrackStep {

		public int patternIndex = -1;
	}
}


text:
/*
 * Definition of CCM:
 * http://csrc.nist.gov/publications/nistpubs/800-38C/SP800-38C_updated-July20_2007.pdf
 * RFC 3610 "Counter with CBC-MAC (CCM)"
 *
 * Related:
 * RFC 5116 "An Interface and Algorithms for Authenticated Encryption"
 */

/* Includes ------------------------------------------------------------------*/
#include "mbedtls/ccm.h"

#if defined(MBEDTLS_CCM_C)
#if defined(MBEDTLS_CCM_ALT)

#include <string.h>

#include "mbedtls/platform.h"
#include "mbedtls/platform_util.h"

#include "platform/PlatformMutex.h"
#include "platform/SingletonPtr.h"

static SingletonPtr<PlatformMutex> ccm_mutex;

#define MBEDTLS_DEBUG 0

/* Parameter validation macros */
#define CCM_VALIDATE_RET( cond ) \
    MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_CCM_BAD_INPUT )
#define CCM_VALIDATE( cond ) \
    MBEDTLS_INTERNAL_VALIDATE( cond )

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
#define CCM_ENCRYPT 0
#define CCM_DECRYPT 1

#define H_LENGTH 2 /* Formatting of the Associated Data */
/* If 0 < a < 2e16-2e8, */
/* then a is encoded as [a]16, i.e., two octets */

/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/*
 * Initialize context
 */
void mbedtls_ccm_init(mbedtls_ccm_context *ctx)
{
    CCM_VALIDATE(ctx != NULL);

    ccm_mutex->lock();
    cryp_context_count++;
    ccm_mutex->unlock();

    cryp_zeroize((void *)ctx, sizeof(mbedtls_ccm_context));

#if (MBEDTLS_DEBUG)
    printf("[ALT] mbedtls_ccm_init %u\n", cryp_context_count);
#endif
}

int mbedtls_ccm_setkey(mbedtls_ccm_context *ctx,
                       mbedtls_cipher_id_t cipher,
                       const unsigned char *key,
                       unsigned int keybits)
{
    unsigned int i;
    int ret = 0;

#if (MBEDTLS_DEBUG)
    printf("[ALT] mbedtls_ccm_setkey\n");
#endif

    CCM_VALIDATE_RET(ctx != NULL);
    CCM_VALIDATE_RET(key != NULL);

    /* Protect context access                                  */
    /* (it may occur at a same time in a threaded environment) */
#if defined(MBEDTLS_THREADING_C)
    if (mbedtls_mutex_lock(&cryp_mutex) != 0) {
        return (MBEDTLS_ERR_THREADING_MUTEX_ERROR);
    }
#endif /* MBEDTLS_THREADING_C */

    switch (keybits) {
        case 128:
            ctx->hcryp_ccm.Init.KeySize = CRYP_KEYSIZE_128B;;
            break;

        case 192:
#if ( USE_AES_KEY192 == 1 )
            ctx->hcryp_ccm.Init.KeySize = CRYP_KEYSIZE_192B;
            break;
#else
            ret = MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED;
            goto exit;
#endif /* USE_AES_KEY192 */

        case 256:
            ctx->hcryp_ccm.Init.KeySize = CRYP_KEYSIZE_256B;
            break;

        default :
            ret = MBEDTLS_ERR_CCM_BAD_INPUT;
            goto exit;
    }

    /* Format and fill AES key  */
    for (i = 0; i < (keybits / 32) ; i++) {
        GET_UINT32_BE(ctx->ccm_key[i], key, 4 * i);
    }

    /* include the appropriate instance name */
#if defined (AES)
    ctx->hcryp_ccm.Instance = AES;
#elif defined (AES1)
    ctx->hcryp_ccm.Instance = AES1;
#else /* CRYP */
    ctx->hcryp_ccm.Instance = CRYP;
#endif /* AES */

    ctx->hcryp_ccm.Init.DataType = CRYP_DATATYPE_8B;
    ctx->hcryp_ccm.Init.pKey = ctx->ccm_key;
    ctx->hcryp_ccm.Init.pInitVect  = NULL;
    ctx->hcryp_ccm.Init.Algorithm  = CRYP_AES_CCM;
    ctx->hcryp_ccm.Init.Header     = NULL;
    ctx->hcryp_ccm.Init.HeaderSize = 0;
    ctx->hcryp_ccm.Init.B0 = NULL;
    ctx->hcryp_ccm.Init.DataWidthUnit = CRYP_DATAWIDTHUNIT_BYTE;

    if (HAL_CRYP_Init(&ctx->hcryp_ccm) != HAL_OK) {
        ret = MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED;
        goto exit;
    }

    /* allow multi-context of CRYP : save context */
    ctx->ctx_save_cr = ctx->hcryp_ccm.Instance->CR;

exit :
    /* Free context access */
#if defined(MBEDTLS_THREADING_C)
    if (mbedtls_mutex_unlock(&cryp_mutex) != 0) {
        ret = MBEDTLS_ERR_THREADING_MUTEX_ERROR;
    }
#endif /* MBEDTLS_THREADING_C */

    return (ret);
}

/*
 * Free context
 */
void mbedtls_ccm_free(mbedtls_ccm_context *ctx)
{
#if (MBEDTLS_DEBUG)
    printf("[ALT] mbedtls_ccm_free %u\n", cryp_context_count);
#endif

    if (ctx == NULL) {
        return;
    }

    ccm_mutex->lock();

    if (cryp_context_count > 0) {
        cryp_context_count--;

        /* Shut down CRYP on last context */
        if (cryp_context_count == 0) {
            HAL_CRYP_DeInit(&ctx->hcryp_ccm);
        }
    }

    ccm_mutex->unlock();

    cryp_zeroize((void *)ctx, sizeof(mbedtls_ccm_context));
}

/*
 * Authenticated encryption or decryption
 */
static int ccm_auth_crypt(mbedtls_ccm_context *ctx, int mode, size_t length,
                          const unsigned char *iv, size_t iv_len,
                          const unsigned char *add, size_t add_len,
                          const unsigned char *input, unsigned char *output,
                          unsigned char *tag, size_t tag_len)
{
    int ret = 0;
    unsigned char i;
    unsigned char q;
    size_t len_left;
    unsigned int j;

    __ALIGN_BEGIN unsigned char b0[16] __ALIGN_END;  /* Formatting of B0   */
    __ALIGN_BEGIN uint32_t b0_32B[4]   __ALIGN_END;  /* B0 data swapping   */
    unsigned char *b1_padded_addr = NULL;            /* Formatting of B1   */
    unsigned char *b1_aligned_addr = NULL;
    size_t b1_length;                                /* B1 with padding    */
    uint8_t b1_padding;                              /* B1 word alignement */

    __ALIGN_BEGIN uint8_t mac[16]      __ALIGN_END;  /* temporary mac      */

    CCM_VALIDATE_RET(mode != CCM_ENCRYPT || mode != CCM_DECRYPT);

    /*
     * Check length requirements: SP800-38C A.1
     * Additional requirement: a < 2^16 - 2^8 to simplify the code.
     * 'length' checked later (when writing it to the first block)
     *
     * Also, loosen the requirements to enable support for CCM* (IEEE 802.15.4).
     */

    /* tag_len, aka t, is an element of {4, 6, 8, 10, 12, 14, 16} */
    if (tag_len < 4 || tag_len > 16 || tag_len % 2 != 0) {
        return (MBEDTLS_ERR_CCM_BAD_INPUT);
    }

    /* Also implies q is within bounds */
    /* iv_len, aka n, is an element of {7, 8, 9, 10, 11, 12, 13} */
    if (iv_len < 7 || iv_len > 13) {
        return (MBEDTLS_ERR_CCM_BAD_INPUT);
    }

    /* add_len, aka a, a < 2^16 - 2^8 */
    if (add_len > 0xFF00) {
        return (MBEDTLS_ERR_CCM_BAD_INPUT);
    }

    /* The octet length of Q, denoted q */
    q = 15 - (unsigned char) iv_len;

    /*
     * First block B_0:
     * 0        .. 0        flags
     * 1        .. iv_len   nonce (aka iv)
     * iv_len+1 .. 15       length
     *
     * With flags as (bits):
     * 7        0
     * 6        add present?
     * 5 .. 3   (t - 2) / 2
     * 2 .. 0   q - 1
     */
    memset(b0, 0, 16);
    if (add_len > 0) {
        b0[0] |= 0x40;
    }
    b0[0] |= ((tag_len - 2) / 2) << 3;
    b0[0] |= q - 1;

    /* Nonce concatenation */
    memcpy(b0 + 1, iv, iv_len);

    /* Data length concatenation */
    for (i = 0, len_left = length; i < q; i++, len_left >>= 8) {
        b0[15 - i] = (unsigned char)(len_left & 0xFF);
    }

    if (len_left > 0) {
        return (MBEDTLS_ERR_CCM_BAD_INPUT);
    }

    /* Protect context access                                  */
    /* (it may occur at a same time in a threaded environment) */
#if defined(MBEDTLS_THREADING_C)
    if (mbedtls_mutex_lock(&cryp_mutex) != 0) {
        return (MBEDTLS_ERR_THREADING_MUTEX_ERROR);
    }
#endif /* MBEDTLS_THREADING_C */

    /* allow multi-context of CRYP use: restore context */
    ctx->hcryp_ccm.Instance->CR = ctx->ctx_save_cr;
    /*
    * If there is additional data, update with
    * add_len, add, 0 (padding to a block boundary)
    */
    if (add_len > 0) {
        /* Extra bytes to deal with data padding such that         */
        /* the resulting string can be partitioned into words      */
        b1_padding = ((add_len + H_LENGTH) % 4);
        b1_length = add_len + H_LENGTH + b1_padding;

        /* reserve extra bytes to deal with 4-bytes memory alignement */
        b1_padded_addr =
            mbedtls_calloc(1, b1_length + 3);

        if (b1_padded_addr == NULL) {
            ret = MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED;
            goto exit;
        }

        /* move up to a 4-bytes aligned address in the reserved memory chuck */
        b1_aligned_addr =
            (unsigned char *)((uint32_t)(b1_padded_addr + 3) & 0xFFFFFFFC);

        /* Header length */
        b1_aligned_addr[0] = (unsigned char)((add_len >> 8) & 0xFF);
        b1_aligned_addr[1] = (unsigned char)((add_len) & 0xFF);

        /* data concatenation */
        memcpy(b1_aligned_addr + H_LENGTH, add, add_len);

        /* blocks (B) associated to the Associated Data (A) */
        ctx->hcryp_ccm.Init.Header     = (uint32_t *)b1_aligned_addr;

        ctx->hcryp_ccm.Init.HeaderSize = b1_length / 4;
    } else {
        ctx->hcryp_ccm.Init.Header = NULL;
        ctx->hcryp_ccm.Init.HeaderSize = 0;
    }

    /* first authentication block */
    for (j = 0; j < 4; j++) {
        GET_UINT32_BE(b0_32B[j], b0, 4 * j);
    }

    ctx->hcryp_ccm.Init.B0         = b0_32B;

    /* reconfigure the CRYP */
    if (HAL_CRYP_SetConfig(&ctx->hcryp_ccm, &ctx->hcryp_ccm.Init) != HAL_OK) {
        ret = MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED;
        goto free_block;
    }

    /* blocks (B) associated to the plaintext message (P) */
    if (mode == CCM_DECRYPT) {
        if (HAL_CRYP_Decrypt(&ctx->hcryp_ccm,
                             (uint32_t *)input,
                             length,
                             (uint32_t *)output,
                             ST_CRYP_TIMEOUT) != HAL_OK) {
            ret = MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED;
            goto free_block;
        }
    } else {
        if (HAL_CRYP_Encrypt(&ctx->hcryp_ccm,
                             (uint32_t *)input,
                             length,
                             (uint32_t *)output,
                             ST_CRYP_TIMEOUT) != HAL_OK) {
            ret = MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED;
            goto free_block;
        }
    }

    /* Tag has a variable length */
    memset(mac, 0, sizeof(mac));

    /* Generate the authentication TAG */
    if (HAL_CRYPEx_AESCCM_GenerateAuthTAG(&ctx->hcryp_ccm,
                                          (uint32_t *)mac,
                                          ST_CRYP_TIMEOUT) != HAL_OK) {
        ret = MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED;
        goto free_block;
    }

    memcpy(tag, mac, tag_len);

    /* allow multi-context of CRYP : save context */
    ctx->ctx_save_cr = ctx->hcryp_ccm.Instance->CR;

free_block:
    if (add_len > 0) {
        mbedtls_free(b1_padded_addr);
    }

exit:
    /* Free context access */
#if defined(MBEDTLS_THREADING_C)
    if (mbedtls_mutex_unlock(&cryp_mutex) != 0) {
        ret = MBEDTLS_ERR_THREADING_MUTEX_ERROR;
    }
#endif /* MBEDTLS_THREADING_C */

    return (ret);
}

/*
 * Authenticated encryption
 */
int mbedtls_ccm_star_encrypt_and_tag(mbedtls_ccm_context *ctx, size_t length,
                                     const unsigned char *iv, size_t iv_len,
                                     const unsigned char *add, size_t add_len,
                                     const unsigned char *input, unsigned char *output,
                                     unsigned char *tag, size_t tag_len)
{
    CCM_VALIDATE_RET(ctx != NULL);
    CCM_VALIDATE_RET(iv != NULL);
    CCM_VALIDATE_RET(add_len == 0 || add != NULL);
    CCM_VALIDATE_RET(length == 0 || input != NULL);
    CCM_VALIDATE_RET(length == 0 || output != NULL);
    CCM_VALIDATE_RET(tag_len == 0 || tag != NULL);
    return (ccm_auth_crypt(ctx, CCM_ENCRYPT, length, iv, iv_len,
                           add, add_len, input, output, tag, tag_len));
}

int mbedtls_ccm_encrypt_and_tag(mbedtls_ccm_context *ctx, size_t length,
                                const unsigned char *iv, size_t iv_len,
                                const unsigned char *add, size_t add_len,
                                const unsigned char *input, unsigned char *output,
                                unsigned char *tag, size_t tag_len)
{
    CCM_VALIDATE_RET(ctx != NULL);
    CCM_VALIDATE_RET(iv != NULL);
    CCM_VALIDATE_RET(add_len == 0 || add != NULL);
    CCM_VALIDATE_RET(length == 0 || input != NULL);
    CCM_VALIDATE_RET(length == 0 || output != NULL);
    CCM_VALIDATE_RET(tag_len == 0 || tag != NULL);
    if (tag_len == 0) {
        return (MBEDTLS_ERR_CCM_BAD_INPUT);
    }

    return (mbedtls_ccm_star_encrypt_and_tag(ctx, length, iv, iv_len, add,
                                             add_len, input, output, tag, tag_len));
}

/*
 * Authenticated decryption
 */
int mbedtls_ccm_star_auth_decrypt(mbedtls_ccm_context *ctx, size_t length,
                                  const unsigned char *iv, size_t iv_len,
                                  const unsigned char *add, size_t add_len,
                                  const unsigned char *input, unsigned char *output,
                                  const unsigned char *tag, size_t tag_len)
{
    int ret;
    unsigned char check_tag[16];
    unsigned char i;
    int diff;

    CCM_VALIDATE_RET(ctx != NULL);
    CCM_VALIDATE_RET(iv != NULL);
    CCM_VALIDATE_RET(add_len == 0 || add != NULL);
    CCM_VALIDATE_RET(length == 0 || input != NULL);
    CCM_VALIDATE_RET(length == 0 || output != NULL);
    CCM_VALIDATE_RET(tag_len == 0 || tag != NULL);

    if ((ret = ccm_auth_crypt(ctx, CCM_DECRYPT, length,
                              iv, iv_len, add, add_len,
                              input, output, check_tag, tag_len)) != 0) {
        return (ret);
    }

    /* Check tag in "constant-time" */
    for (diff = 0, i = 0; i < tag_len; i++) {
        diff |= tag[i] ^ check_tag[i];
    }

    if (diff != 0) {
        mbedtls_platform_zeroize(output, length);
        return (MBEDTLS_ERR_CCM_AUTH_FAILED);
    }

    return (0);
}

int mbedtls_ccm_auth_decrypt(mbedtls_ccm_context *ctx, size_t length,
                             const unsigned char *iv, size_t iv_len,
                             const unsigned char *add, size_t add_len,
                             const unsigned char *input, unsigned char *output,
                             const unsigned char *tag, size_t tag_len)
{
    CCM_VALIDATE_RET(ctx != NULL);
    CCM_VALIDATE_RET(iv != NULL);
    CCM_VALIDATE_RET(add_len == 0 || add != NULL);
    CCM_VALIDATE_RET(length == 0 || input != NULL);
    CCM_VALIDATE_RET(length == 0 || output != NULL);
    CCM_VALIDATE_RET(tag_len == 0 || tag != NULL);

    if (tag_len == 0) {
        return (MBEDTLS_ERR_CCM_BAD_INPUT);
    }

    return (mbedtls_ccm_star_auth_decrypt(ctx, length, iv, iv_len, add,
                                          add_len, input, output, tag, tag_len));
}

#endif /*MBEDTLS_CCM_ALT*/
#endif /*MBEDTLS_CCM_C*/


text:
require 'rubygems'
require 'test/unit'

$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'zlib-crc32_combine'

class Test::Unit::TestCase
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bulletin of the Faculty of Agriculture, Yamaguchi University 5: 234 (1954)

#### Original name
Heteropatella setulosa I. Hino & Katum.

### Remarks
null


text:
import unittest

from driftconfig.util import get_drift_config
from drift.core.extensions.apikeyrules import get_api_key_rule
from drift.tests import DriftTestCase
from drift.systesthelper import setup_tenant

class ApiKeyRulesTest(DriftTestCase):

    @classmethod
    def setUpClass(cls):

        config_size = {
            'num_org': 5,
            'num_tiers': 2,
            'num_deployables': 4,
            'num_products': 2,
            'num_tenants': 2,
        }

        ts = setup_tenant(config_size=config_size, use_app_config=False)
        cls.ts = ts
        cls.tier_name = ts.get_table('tiers').find()[0]['tier_name']
        cls.product_name = ts.get_table('products').find()[0]['product_name']
        cls.tenant_name_1 = ts.get_table('tenant-names').find({'product_name': cls.product_name})[0]['tenant_name']
        cls.tenant_name_2 = ts.get_table('tenant-names').find({'product_name': cls.product_name})[1]['tenant_name']
        cls.tenant_name_3 = ts.get_table('tenant-names').find({'product_name': cls.product_name})[1]['tenant_name']
        cls.deployable_1 = ts.get_table('deployables').find({'tier_name': cls.tier_name})[0]['deployable_name']
        cls.conf = get_drift_config(
            ts=ts,
            tenant_name=cls.tenant_name_1,
            tier_name=cls.tier_name,
            deployable_name=cls.deployable_1,
        )
        cls._add_rules()

    @classmethod
    def _add_rules(cls):
        """The location of this function is for convenience as the test function comes right after it."""

        # Make a few rules to test various cases:
        # Rule 1: reject clients 1.6.0 and 1.6.2 and ask them to upgrade.
        # Rule 2: redirect client 1.6.5 to another tenant.
        # Rule 3: always let client 1.6.5, and 1.6.6 pass through.
        # Rule 4: redirect client 1.6.7 to another host.
        # Rule 5: reject all clients with message "server is down".
        rules = [
            ('upgrade-client-1.6', ["1.6.0", "1.6.2"], 'reject', [404, {"action": "upgrade_client"}]),
            ('redirect-to-new-tenant', ["1.6.5"], 'redirect', {'tenant_name': cls.tenant_name_2}),
            ('always-pass', ["1.6.5", "1.6.6"], 'pass', cls.tenant_name_1),
            ('redirect-to-new-host', ["1.6.7"], 'redirect', {'host_name': cls.tenant_name_3 + '.example.com'}),
            ('downtime-message', [], 'reject', [503, {"message": "The server is down for maintenance."}]),
        ]

        api_key_rules = cls.ts.get_table('api-key-rules')

        for i, (rule_name, version_pattern, rule_type, custom) in enumerate(rules):
            row = api_key_rules.add({
                'product_name': cls.product_name,
                'rule_name': rule_name,
                'assignment_order': i,
                'version_patterns': version_pattern,
                'rule_type': rule_type,
            })
            if rule_type == 'reject':
                row['reject'] = {'status_code': custom[0], 'response_body': custom[1]}
            elif rule_type == 'redirect':
                row['redirect'] = custom

            row['response_header'] = {'Test-Rule-Name': rule_name}  # To test response headers

        cls.ts.get_table('api-keys').add({
            'api_key_name': cls.product_name,
            'product_name': cls.product_name
        })

        cls.ts.get_table('api-keys').add({
            'api_key_name': 'custom-key',
            'key_type': 'custom',
        })

    def test_custom_key(self):
        # Only keys of type 'product' need to be associated with a product. Custom keys can
        # be universal and thus implicitly excempt from any product rule.
        headers = {
            "Drift-Api-Key": "custom-key",
        }
        url = "https://%s.kaleo.io/drift" % self.tenant_name_1
        rule = get_api_key_rule(headers, url, self.conf)
        self.assertIsNone(rule)

    def test_no_api_key_means_pass(self):
        # The reason for this is that some endpoints don't need
        # a key and this is enforced by nginx before it gets here
        url = "https://%s.kaleo.io/drift" % self.tenant_name_1
        rule = get_api_key_rule({}, url, self.conf)
        self.assertIsNone(rule)

    def test_pass_rule_passes(self):
        headers = {
            "Drift-Api-Key": "%s:%s" % (self.product_name, "1.6.6")
        }
        url = "https://%s.kaleo.io/drift" % self.tenant_name_1
        rule = get_api_key_rule(headers, url, self.conf)
        self.assertIsNotNone(rule)
        self.assertIsNone(rule["status_code"])

    def test_reject_rule_rejects(self):
        headers = {
            "Drift-Api-Key": "%s:%s" % (self.product_name, "1.6.1")
        }
        url = "https://%s.kaleo.io/drift" % self.tenant_name_1
        rule = get_api_key_rule(headers, url, self.conf)
        self.assertIsNotNone(rule)
        self.assertEqual(rule['status_code'], 503)
        self.assertEqual(rule['response_body']['message'], "The server is down for maintenance.")

    def test_upgrade_rule_passes_with_info(self):
        headers = {
            "Drift-Api-Key": "%s:%s" % (self.product_name, "1.6.0")
        }
        url = "https://%s.kaleo.io/drift" % self.tenant_name_1
        rule = get_api_key_rule(headers, url, self.conf)
        self.assertIsNotNone(rule)
        self.assertEqual(rule['status_code'], 404)
        self.assertEqual(rule['response_body']['action'], "upgrade_client")

    def test_redirect_rule_redirects_tenant(self):
        headers = {
            "Drift-Api-Key": "%s:%s" % (self.product_name, "1.6.5")
        }
        url = "https://%s.kaleo.io/drift" % self.tenant_name_1
        rule = get_api_key_rule(headers, url, self.conf)
        self.assertIsNotNone(rule)
        self.assertEqual(rule['status_code'], 307)
        self.assertEqual(rule['response_header']['Location'], "https://%s.kaleo.io/drift" % self.tenant_name_2)

    def test_redirect_rule_redirects_hostname(self):
        headers = {
            "Drift-Api-Key": "%s:%s" % (self.product_name, "1.6.7")
        }
        url = "https://%s.kaleo.io/drift" % self.tenant_name_1
        rule = get_api_key_rule(headers, url, self.conf)
        self.assertIsNotNone(rule)
        self.assertEqual(rule['status_code'], 307)
        self.assertEqual(rule['response_header']['Location'], "https://%s.example.com/drift" % self.tenant_name_3)

    def test_redirect_rule_passes_when_redirected(self):
        headers = {
            "Drift-Api-Key": "%s:%s" % (self.product_name, "1.6.5")
        }
        url = "https://%s.kaleo.io/drift" % self.tenant_name_2
        rule = get_api_key_rule(headers, url, self.conf)
        self.assertIsNotNone(rule)
        self.assertIsNone(rule['status_code'])

if __name__ == '__main__':
    unittest.main()


text:
var fs = require('fs')
var knox = require('knox')
var mime = require('mime')
var waitress = require('waitress')

/**
 * @class Retry
 * @constructor
 * @param opts {Object} an object containing config parameters
 *   `key`, `secret` and `bucket` are all requried.
 *   `region` is the S3 region. It defaults to us-west-2
 *   `maxRetries` is the number of times to retry before failing. It defaults to 3
 *   `backoffInterval` is a multiplier used to calculate exponential backoff.
 *   It defaults to 51.
 * @param knox {Object} knox library by default, or mocked version for testing
 * @param mime {Object} mime lib by default, or mocked version for testing
 */
function Retry(opts, s3Lib, mimeLib) {
  // Inject deps for testing
  if (typeof s3Lib === 'undefined') {
    s3Lib = knox
  }
  this.knox = s3Lib

  if (typeof mimeLib === 'undefined') {
    mimeLib = mime
  }
  this.mime = mimeLib

  validateRequiredOptions(opts)

  this.key = opts.key
  this.secret = opts.secret
  this.bucket = opts.bucket
  this.region = opts.region || 'us-west-2'

  this.s3Client = this.knox.createClient(opts)

  this.maxRetries = opts.maxRetries || 3
  this.backoffInterval = opts.backoffInterval || 51
}

function validateRequiredOptions(opts) {
  if (!opts.hasOwnProperty('key')) {
    throw new Error("Missing required 'key' option from opts.")
  }
  else if (!opts.hasOwnProperty('secret')) {
    throw new Error("Missing required 'secret' option from opts.")
  }
  else if (!opts.hasOwnProperty('bucket')) {
    throw new Error("Missing required 'bucket' option from opts.")
  }
}

Retry.prototype.calculateBackoff = function(numRetries) {
  var randMultiplier = Math.ceil(Math.random() * (Math.pow(2, numRetries + 2) - 1))
  return this.backoffInterval * randMultiplier
}

/**
 * Upload a file at sourcePath with automatic retries and exponential backoff
 *
 * @param sourcePath {String} location of the file to upload on the fs
 * @param destination {String} path in s3 to upload file to
 * @param cb {Function} function(err) called when upload is done or has failed too many times
 */
Retry.prototype.upload = function(sourcePath, destination, cb) {
  var self = this

  fs.readFile(sourcePath, function(err, file) {
    if (err) {
      return cb(err)
    }

    var headers = {
      'Content-Type': self.mime.lookup(sourcePath),
      'Content-Length': file.length
    }

    self.uploadWithRetries(file, headers, destination, cb)
  })
}

/**
 * Upload a buffer with accompanying headers to S3.
 *
 * @param buffer {Buffer} buffer to put to s3
 * @param headers {Object} headers. Will set default Content-Type and
 *   Content-Length if none is provided.
 * @param destination {String} path to put buffer to
 * @param cb {Funtion} function(err, res) called when upload has succeeded
 *   or failed too many times.
 */
Retry.prototype.uploadBuffer = function(buffer, headers, destination, cb) {
  this.uploadWithRetries(buffer, headers, destination, cb)
}

/**
 * Upload a buffer with accompanying headers to s3. Recursively calls itself
 * until `timesRetried` exceeds `this.maxRetries`.
 *
 * @private
 * @param data {Buffer} data to put to S3
 * @param headers {Object} headers to send with request to S3. Will set a default
 *   Content-Length and Content-Type if none is provided.
 * @param destination {String} path to put the buffer to S3
 * @param timesRetried {Number} number of times this current upload has retried.
 *   Defaults to 0 if not passed in, and will increment every time an upload fails.
 * @param cb {Function} function(err, res) called when upload is done or has failed
 *   too many times.
 */
Retry.prototype.uploadWithRetries = function(data, headers, destination, timesRetried, cb) {
  var self = this
  // prevent callback from being called twice
  var callbackCalled = false

  // sometimes knox failures will give EPIPE errors after sending a non-200
  // status code, so we have to guard against recusing twice
  var recursionScheduled = false

  // Set content type and length if they aren't included
  headers = headers || {}
  if (!headers['Content-Type']) {
    headers['Content-Type'] = 'application/octet-stream'
  }
  if (headers['Content-Length'] == undefined) {
    headers['Content-Length'] = data.length
  }

  if (typeof timesRetried === 'function') {
    cb = timesRetried
    // start at -1 so we can increment up to 0 on the first call
    timesRetried = -1
  }

  timesRetried++

  function endWithError(err) {
    if (callbackCalled) {
      return
    }
    if (timesRetried >= self.maxRetries) {
      if (!callbackCalled) {
        callbackCalled = true
        return cb(err, null, timesRetried)
      }
    }
    else {
      if (recursionScheduled) {
        return
      }
      recursionScheduled = true
      setTimeout(self.uploadWithRetries.bind(self),
        self.calculateBackoff(timesRetried), data, headers, destination,
        timesRetried, cb)
    }
  }

  function endWithResponse(res) {
    if (res.statusCode !== 200) {
      return endWithError(new Error('Invalid status code: ' + res.statusCode))
    }

    if (!callbackCalled) {
      callbackCalled = true
      return cb(null, res, timesRetried)
    }
  }

  var client = this.s3Client.put(destination, headers)
  client.on('response', endWithResponse)
  client.on('error', endWithError)

  client.end(data)
}

/**
 * Upload a file at sourcePath with automatic retries and exponential backoff
 *
 * @param files {Object} {src: /path, dest: /path} location and destination of the file to upload on the fs
 * @param cb {Function} function(err) called when all uploads are done or have failed too many times
 */
Retry.prototype.uploadFiles = function(files, cb) {
  var self = this
  var done = waitress(files.length, cb);

  files.forEach(function(file) {
    self.upload(file.src, file.dest, done);
  });
}

module.exports = Retry


text:
package kina.utils;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import kina.annotations.ClusterKey;
import kina.annotations.Field;
import kina.annotations.Key;
import kina.annotations.PartitionKey;
import org.apache.cassandra.db.marshal.AbstractType;
import org.apache.cassandra.db.marshal.UTF8Type;

/**
 * Created by luca on 12/08/14.
 */
public class CassandraUtils {
	/**
	 * Returns the field name as known by the datastore. If the provided field object Field annotation
	 * specifies the fieldName property, the value of this property will be returned, otherwise the java field name
	 * will be returned.
	 *
	 * @param field the Field object associated to the property for which we want to resolve the name.
	 * @return the field name.
	 */
	public static String kinaFieldName(java.lang.reflect.Field field) {

		Field fieldAnnotation = field.getAnnotation(Field.class);
		Key genericKeyAnnotation = field.getAnnotation(Key.class);
		PartitionKey partitionKeyAnnotation = field.getAnnotation(PartitionKey.class);
		ClusterKey clusterKeyAnnotation = field.getAnnotation(ClusterKey.class);

		String fieldName = null;

		if (fieldAnnotation != null){
			fieldName = fieldAnnotation.fieldName();
		} else if (genericKeyAnnotation != null){
			fieldName = genericKeyAnnotation.fieldName();
		} else if (partitionKeyAnnotation != null){
			fieldName = partitionKeyAnnotation.fieldName();
		} else if (clusterKeyAnnotation != null){
			fieldName = clusterKeyAnnotation.fieldName();
		}

		if (StringUtils.isNotEmpty(fieldName)) {
			return fieldName;
		} else {
			return field.getName();
		}
	}

	/**
	 * Utility method that filters out all the fields _not_ annotated
	 * with the {@link kina.annotations.Field} annotation.
	 *
	 * @param clazz the Class object for which we want to resolve kina fields.
	 * @return an array of kina Field(s).
	 */
	public static java.lang.reflect.Field[] filterKinaFields(Class clazz) {
		java.lang.reflect.Field[] fields = Utils.getAllFields(clazz);
		List<java.lang.reflect.Field> filtered = new ArrayList<>();
		for (java.lang.reflect.Field f : fields) {
			if (f.isAnnotationPresent(Field.class) ||
				f.isAnnotationPresent(Key.class) ||
				f.isAnnotationPresent(PartitionKey.class) ||
				f.isAnnotationPresent(ClusterKey.class)) {

				filtered.add(f);
			}
		}
		return filtered.toArray(new java.lang.reflect.Field[filtered.size()]);
	}

	public static Class<? extends AbstractType> validationClass(java.lang.reflect.Field field){
		Field fieldAnnotation = field.getAnnotation(Field.class);
		Key genericKeyAnnotation = field.getAnnotation(Key.class);
		PartitionKey partitionKeyAnnotation = field.getAnnotation(PartitionKey.class);
		ClusterKey clusterKeyAnnotation = field.getAnnotation(ClusterKey.class);

		Class<? extends AbstractType> res = null;

		if (fieldAnnotation != null){
			res = fieldAnnotation.validationClass();
		} else if (genericKeyAnnotation != null){
			res = UTF8Type.class;
		} else if (partitionKeyAnnotation != null){
			res = partitionKeyAnnotation.validationClass();
		} else if (clusterKeyAnnotation != null){
			res = clusterKeyAnnotation.validationClass();
		}

		return res;
	}

	/**
	 * Returns true is given field is part of the table key.
	 *
	 * @param field the Field object we want to process.
	 * @return true if the field is part of the cluster key or the partition key, false otherwise.
	 */
	public static boolean isKey(java.lang.reflect.Field field){

		Key genericKeyAnnotation = field.getAnnotation(Key.class);
		PartitionKey partitionKeyAnnotation = field.getAnnotation(PartitionKey.class);
		ClusterKey clusterKeyAnnotation = field.getAnnotation(ClusterKey.class);

		return genericKeyAnnotation != null || partitionKeyAnnotation !=null || clusterKeyAnnotation != null;
	}

	/**
	 * Returns true is given field is part of the table key.
	 *
	 * @param field the Field object we want to process.
	 * @return true if the field is part of the cluster key or the partition key, false otherwise.
	 */
	public static boolean isClusterKey(java.lang.reflect.Field field){

		ClusterKey annotation = field.getAnnotation(ClusterKey.class);

		return annotation != null;
	}

	/**
	 * Returns true is given field is part of the table key.
	 *
	 * @param field the Field object we want to process.
	 * @return true if the field is part of the cluster key or the partition key, false otherwise.
	 */
	public static boolean isPartitionKey(java.lang.reflect.Field field){

		Key genericKeyAnnotation = field.getAnnotation(Key.class);
		PartitionKey partitionKeyAnnotation = field.getAnnotation(PartitionKey.class);

		return genericKeyAnnotation != null || partitionKeyAnnotation !=null;
	}

	/**
	 * Return a pair of Field[] whose left element is
	 * the array of keys fields.
	 * The right element contains the array of all other non-key fields.
	 *
	 * @param clazz the Class object
	 * @return a pair object whose first element contains key fields, and whose second element contains all other columns.
	 */
	public static Pair<java.lang.reflect.Field[], java.lang.reflect.Field[]> filterKeyFields(Class clazz) {
		java.lang.reflect.Field[] filtered = filterKinaFields(clazz);
		List<java.lang.reflect.Field> keys = new ArrayList<>();
		List<java.lang.reflect.Field> others = new ArrayList<>();

		for (java.lang.reflect.Field field : filtered) {
			if (isKey(field)) {
				keys.add(field);
			} else {
				others.add(field);
			}
		}

		return Pair.create(keys.toArray(new java.lang.reflect.Field[keys.size()]), others.toArray(new java.lang.reflect.Field[others.size()]));
	}
}


text:
#ifndef ABESHADER_H
#define ABESHADER_H

#include "GL/glew.h"
#include "glm/glm.hpp"

#include <string>

namespace abege {

class ABEShader {
 public:
    unsigned int ID;

    ABEShader() {}
    ABEShader(const char *vertexPath, const char *fragmentPath);

    void use() {
        glUseProgram(ID);
    }

    void setBool(const std::string &name, bool value) const {
        glUniform1i(glGetUniformLocation(ID, name.c_str()), (int) value);
    }

    void setInt(const std::string &name, int value) const {
        glUniform1i(glGetUniformLocation(ID, name.c_str()), value);
    }

    void setFloat(const std::string &name, float value) const {
        glUniform1f(glGetUniformLocation(ID, name.c_str()), value);
    }

    void setVec2(const std::string &name, const glm::vec2 &value) const {
        glUniform2fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]);
    }

    void setVec2(const std::string &name, float x, float y) const {
        glUniform2f(glGetUniformLocation(ID, name.c_str()), x, y);
    }

    void setVec3(const std::string &name, const glm::vec3 &value) const {
        glUniform3fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]);
    }

    void setVec3(const std::string &name, float x, float y, float z) const {
        glUniform3f(glGetUniformLocation(ID, name.c_str()), x, y, z);
    }

    void setVec4(const std::string &name, const glm::vec4 &value) const {
        glUniform4fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]);
    }

    void setVec4(const std::string &name, float x, float y, float z, float w) {
        glUniform4f(glGetUniformLocation(ID, name.c_str()), x, y, z, w);
    }

    void setMat2(const std::string &name, const glm::mat2 &mat) const {
        glUniformMatrix2fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]);
    }

    void setMat3(const std::string &name, const glm::mat3 &mat) const {
        glUniformMatrix3fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]);
    }

    void setMat4(const std::string &name, const glm::mat4 &mat) const {
        glUniformMatrix4fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]);
    }

 private:
    const std::string TAG = "ABEShader";

    void compile(std::string vertexCode, std::string fragmentCode);
    void compile(const char *vertexCode, const char *fragmentCode);
    void checkCompileErrors(GLuint shader, std::string type);

    std::string readFromFile(std::string path);
};

} // namespace abege.

#endif // ABESHADER_H


text:
namespace NServiceKit.OrmLite.Oracle.DbSchema
{
    /// Values that represent ProcedureType.
	public enum ProcedureType
	{
        /// An enum constant representing the selectable option.
		Selectable = 0,

        /// An enum constant representing the executable option.
		Executable = 1
	}
}


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

Simple paired client/server:
You make a client that spawns a server,
and you tell it what to do.

It's especially easy to run Python-like interpreters such as Autodesk Maya,
you can execute Maya commands from your pure-Python tool to e.g. batch-process assets.

But any environment that supports [ZeroMQ][zmq] can be automated, sky's the limit.

## Getting Started
Lets do a simple example. This guide is based on Windows but should be easy to adapt to Linux/Mac.

* Make a folder somewhere to hold this experiment
* Open a command line prompt in that folder

You probably want to activate a virtualenv for this,
to avoid polluting your global modules:

    > virtualenv .venv
    > .venv\Scripts\activate

Good, now Python modules we install will only go to this folder.
Let's do our simple experiment:

    > pip install git+https://github.com/gaggle/pairedmq.git
    > python
    >>> from evalexec.client import EvalExecClient
    >>> c = EvalExecClient()
    >>> c.eval("1 + 1")
    2

Great, you just sent that expression to the server process,
it got calculated,
and returned to your client.

## The Next Step
This library provides 5 extendable classes, so you can customize behavior to your liking:

    pairedmq.client.Client
    pairedmq.server.Server
    pairedmq.evalexec.client.EvalExecClient
    pairedmq.evalexec.server.EvalExecClient
    pairedmq.mayaclient.client.MayaClient

You can inherit from either of these and override/extend as you please.
The `pairedmq` baseclasses needs just one override each to get going,
the `evalexec` classes are good to go as-is (they spawn a normal python process),
and if your needs are specifically to run Maya you can use the `MayaClient` class.

## Using Maya
Lets kick it up a notch and try interacting with Autodesk Maya.
With this technique we can write pure-Python tools that uses Maya for calculations,
which has several benefits over using the Maya Python interpreter directly:

* You're not tied to the Python version that comes with Maya
* You're not limited to libraries that may or may not exist for Maya's Python
* You're not tied to any stability issues of Maya

And it's pretty easy to do:

First of all it's necessary to install ZMQ into Maya
(It's the underlying communication library through which client and server talks together).
[This page has precompiled zip files specifically made for Maya][mayabinaries].
Download the file matching your Maya version
and extract it into `<maya version>/Python/Lib/site-packages`.

Usually:
* Windows: `"C:\Program Files\Autodesk\<Maya version>\Python/Lib/site-packages"`
* Mac: `"/applications/autodesk/<maya version>/Python/Lib/site-packages"`

The `site-packages` folder should end up containing a `zmq` folder.

Now let's create a `MayaClient`:

    > python
    >>> from pairedmq.mayaclient.client import MayaClient
    >>> c = MayaClient(<path to mayapy.exe>)

That `exe` string has to point to where you have Maya installed, usually it's:

* Windows: `r"C:\Program Files\Autodesk\<Maya version>\bin\mayabatch.exe"`
* Mac: `r"/applications/autodesk/<maya version>/bin/mayabatch"` on Mac

And finally let's create a sphere and get its radius:

    >>> c.exec_("import pymel.core as pmc", timeout=60000)
    >>> c.exec_("t, s = pmc.polySphere()")
    >>> c.eval("s.radius.get()")
    1.0

That's it, the full power of Maya is in your hands. Now make something cool!

## Thanks
This whole library is based on examples
from the wonderful book [Practical Maya Programming with Python][book] by [Rob Galanakis][robg].
If you are dealing with Maya in any technical capacity I cannot recommend this book enough.

[zmq]: http://zeromq.org
[mayabinaries]: http://www.robg3d.com/maya-windows-binaries/
[robg]: http://github.com/rgalanakis
[book]: https://www.packtpub.com/hardware-and-creative/practical-maya-programming-python


text:
<?php

session_start();

$myusername = $_SESSION['myusername'];
$mypassword = $_SESSION['mypassword'];
$user_id = $_SESSION['user_id'];
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="79512499"; // Mysql password
$db_name="innovateme"; // Database name
$tbl_name="users"; // Table name

/*
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);
*/

mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

$sql="SELECT * FROM $tbl_name WHERE user_id='$user_id'";
$result=mysql_query($sql);

$row = mysql_fetch_assoc($result);

$firstname_header = $row['first_name'];
$lastname_header = $row['last_name'];

?>

<meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">

        <link rel="stylesheet" type="text/css" href="css/style.css" />
        <link href='http://fonts.googleapis.com/css?family=Lato:300,400,700' rel='stylesheet' type='text/css' />

		<link rel="stylesheet" type="text/css" href="css/noJS.css" />

 <link href="http://fonts.googleapis.com/css?family=Ubuntu:bold" rel="stylesheet" type="text/css">

<link rel="stylesheet" href="search.css" type="text/css" />

 <link rel="stylesheet" type="text/css" href="headerstylesheet.css">

Loading

					  <?php
						 if (empty($firstname_header)) {
							echo 'Login';
						 } else {
							echo "$firstname_header $lastname_header";

						echo '
';
						echo '
Home
';
						echo '
Profile
'	;
						echo '
My Network
';
						echo '
Settings
';
						echo '
Log out
';
						echo '
';
						}
					  ?>


text:
static NSString *LargeThumbnailName = @"Large Square";
static NSString *LargeName = @"Large";
static NSString *OrigName = @"Original";

@implementation GETFlickrPhotoURLSOperation

- (NSURL *)url
{
    NSString *urlString =
        [NSString stringWithFormat:@"https://api.flickr.com/services/rest/"
                                   @"?method=flickr.photos.getSizes&api_key=ee45c17f38db74644ecc1898e18c558a&photo_"
                                   @"id=%@&format=json&nojsoncallback=1",
                                   self.photo.identifier];
    return [NSURL URLWithString:urlString];
}

- (id)parsedObject:(NSData *)data
{
    NSError *error = nil;
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
    if (!error) {
        NSDictionary *sizesDict = dict[@"sizes"];
        if ([sizesDict isKindOfClass:[NSDictionary class]]) {
            NSArray *sizes = sizesDict[@"size"];

            NSString *thumbnailPath = nil;
            NSString *fullImagePath = nil;

            for (NSDictionary *sizeDict in sizes) {
                if ([sizeDict[@"label"] isEqualToString:LargeThumbnailName]) {
                    thumbnailPath = sizeDict[@"source"];
                }
                else if ([sizeDict[@"label"] isEqualToString:LargeName]) {
                    fullImagePath = sizeDict[@"source"];
                }
                else if ([sizeDict[@"label"] isEqualToString:OrigName]) {
                    fullImagePath = sizeDict[@"source"];
                }
            }

            self.photo.thumbnailURL = (thumbnailPath) ? [NSURL URLWithString:thumbnailPath] : nil;
            self.photo.photoURL = (fullImagePath) ? [NSURL URLWithString:fullImagePath] : nil;
        }
    }

    return self.photo;
}
@end


text:
/**
 * @module component/view
 * @requires module:component
 */
define(function(require, exports, module) {
  "use strict";

  // WebApp internals.
  var Component = require("../component");

  /**
   * A default view, `<webapp-view>`, that can be used in markup.
   *
   * @public
   * @memberOf module:component/view
   */
  var ViewComponent = Component.extend({
    selector: "webapp-view",

    constructor: function() {
      ViewComponent.super("constructor", this, arguments);
      this.channel.subscribe(this.render, this);
    }
  });

  module.exports = ViewComponent;
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<openapoc_rules>
  <organisation ID="ORG_X-COM" balance="5000000" income="0" name="STR_X-COM"/>
  <organisation ID="ORG_ALIEN" balance="0" income="0" name="STR_ALIEN"/>
  <organisation ID="ORG_GOVERNMENT" balance="0" income="0" name="STR_GOVERNMENT"/>
  <organisation ID="ORG_MEGAPOL" balance="0" income="0" name="STR_MEGAPOL"/>
  <organisation ID="ORG_CULT_OF_SIRIUS" balance="0" income="0" name="STR_CULT_OF_SIRIUS"/>
  <organisation ID="ORG_MARSEC" balance="0" income="0" name="STR_MARSEC"/>
  <organisation ID="ORG_SUPERDYNAMICS" balance="0" income="0" name="STR_SUPERDYNAMICS"/>
  <organisation ID="ORG_GENERAL_METRO" balance="0" income="0" name="STR_GENERAL_METRO"/>
  <organisation ID="ORG_CYBERWEB" balance="0" income="0" name="STR_CYBERWEB"/>
  <organisation ID="ORG_TRANSTELLAR" balance="0" income="0" name="STR_TRANSTELLAR"/>
  <organisation ID="ORG_SOLMINE" balance="0" income="0" name="STR_SOLMINE"/>
  <organisation ID="ORG_SENSOVISION" balance="0" income="0" name="STR_SENSOVISION"/>
  <organisation ID="ORG_LIFETREE" balance="0" income="0" name="STR_LIFETREE"/>
  <organisation ID="ORG_NUTRIVEND" balance="0" income="0" name="STR_NUTRIVEND"/>
  <organisation ID="ORG_EVONET" balance="0" income="0" name="STR_EVONET"/>
  <organisation ID="ORG_SANCTUARY_CLINIC" balance="0" income="0" name="STR_SANCTUARY_CLINIT"/>
  <organisation ID="ORG_NANOTECH" balance="0" income="0" name="STR_NANOTECH"/>
  <organisation ID="ORG_ENERGEN" balance="0" income="0" name="STR_ENERGEN"/>
  <organisation ID="ORG_SYNTHEMESH" balance="0" income="0" name="STR_SYNTHEMESH"/>
  <organisation ID="ORG_GRAVBALL_LEAGUE" balance="0" income="0" name="STR_GRAVBALL_LEAGUE"/>
  <organisation ID="ORG_PSYKE" balance="0" income="0" name="STR_PSYKE"/>
  <organisation ID="ORG_DIABLO" balance="0" income="0" name="STR_DIABLO"/>
  <organisation ID="ORG_OSIRON" balance="0" income="0" name="STR_OSIRON"/>
  <organisation ID="ORG_S_E_L_F_" balance="0" income="0" name="STR_S_E_L_F_"/>
  <organisation ID="ORG_MUTANT_ALLIANCE" balance="0" income="0" name="STR_MUTANT_ALLIANCE"/>
  <organisation ID="ORG_EXTROPIANS" balance="0" income="0" name="STR_EXTROPIANS"/>
  <organisation ID="ORG_TECHNOCRATS" balance="0" income="0" name="STR_TECHNOCRATS"/>
  <organisation ID="ORG_CIVILIAN" balance="0" income="0" name="STR_CIVILIAN"/>
</openapoc_rules>