text:
package biz.neustar.ultra.rest.dto;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;

import java.util.Map;

/**
 * Task request to create background task.
 *
 * @author Girish Mahajan
 */
@JsonInclude(Include.NON_NULL)
public class TaskRequest {

    /**
     * Task action.
     */
    private TaskAction action;
    /**
     * Input values key-value pair.
     */
    private Map<String, Object> param;

    /**
     * Default constructor.
     */
    public TaskRequest() {
        super();
    }

    /**
     * Parameterized constructor.
     *
     * @param action The task action.
     * @param param  The JSON input for zone snapshot task.
     */
    public TaskRequest(TaskAction action, Map<String, Object> param) {
        super();
        this.action = action;
        this.param = param;
    }

    /**
     * Returns task action.
     *
     * @return The task action.
     */
    public TaskAction getAction() {
        return action;
    }

    /**
     * Set the task action.
     *
     * @param action The {@link TaskAction} value.
     */
    public void setAction(TaskAction action) {
        this.action = action;
    }

    /**
     * Returns the key-value pairs of inputs.
     *
     * @return The Map of input key-value pair.
     */
    public Map<String, Object> getParam() {
        return param;
    }

    /**
     * Sets the input in key-value pair for background task.
     *
     * @param param The map of key-value pair.
     */
    public void setParam(Map<String, Object> param) {
        this.param = param;
    }

    /*
     * (non-Javadoc)
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public final String toString() {
        return MoreObjects.toStringHelper(this).add("action", getAction()).add("param", getParam()).toString();
    }

    /*
     * (non-Javadoc)
     *
     * @see java.lang.Object#hashCode()
     */
    @Override
    public final int hashCode() {
        return Objects.hashCode(getAction(), getParam());
    }

    /*
     * (non-Javadoc)
     *
     * @see java.lang.Object#equals(java.lang.Object)
     */
    @Override
    public final boolean equals(final Object obj) {
        if (!(obj instanceof TaskRequest)) {
            return false;
        }
        final TaskRequest other = (TaskRequest) obj;
        return Objects.equal(getAction(), other.getAction()) && Objects.equal(getParam(), other.getParam());
    }

    /**
     * Task action types.
     */
    public enum TaskAction {
        ZONE_SNAPSHOT,
        MIGRATE_MDNS_ZONES
    }
}


text:
using System;
using System.CodeDom;
using System.Collections.Generic;
using System.Linq;

namespace RazorGenerator.Core
{
    public class RemoveLineHiddenPragmas : RazorCodeTransformerBase
    {
        private const string LinePragmaText = "#line hidden";

        public override void ProcessGeneratedCode(CodeCompileUnit codeCompileUnit, CodeNamespace generatedNamespace, CodeTypeDeclaration generatedClass, CodeMemberMethod executeMethod)
        {
            var linePragmaStatements = new List<CodeSnippetTypeMember>();
            foreach (var member in generatedClass.Members.OfType<CodeSnippetTypeMember>())
            {
                if (member.Text.TrimEnd().Equals(LinePragmaText, StringComparison.OrdinalIgnoreCase))
                {
                    // If the snippet is entirely a line pragma, mark it for removal.
                    linePragmaStatements.Add(member);
                }
                if (member.Text.StartsWith(LinePragmaText, StringComparison.OrdinalIgnoreCase))
                {
                    member.Text = member.Text.Substring(LinePragmaText.Length);
                }
            }

            foreach (var item in linePragmaStatements)
            {
                generatedClass.Members.Remove(item);
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
"""The ``spyne.server.zeromq`` module contains a server implementation that
uses ZeroMQ (zmq.REP) as transport.
"""
import threading

import zmq

from spyne.auxproc import process_contexts
from spyne._base import MethodContext
from spyne.server import ServerBase

class ZmqMethodContext(MethodContext):
    def __init__(self, app):
        super(ZmqMethodContext, self).__init__(app, MethodContext.SERVER)
        self.transport.type = 'zmq'

class ZeroMQServer(ServerBase):
    """The ZeroMQ server transport."""
    transport = 'http://rfc.zeromq.org/'

    def __init__(self, app, app_url, wsdl_url=None, ctx=None, socket=None):
        if ctx and socket and ctx is not socket.context:
            raise ValueError("ctx should be the same as socket.context")
        super(ZeroMQServer, self).__init__(app)

        self.app_url = app_url
        self.wsdl_url = wsdl_url

        if ctx:
            self.ctx = ctx
        elif socket:
            self.ctx = socket.context
        else:
            self.ctx = zmq.Context()

        if socket:
            self.zmq_socket = socket
        else:
            self.zmq_socket = self.ctx.socket(zmq.REP)
            self.zmq_socket.bind(app_url)

    def __handle_wsdl_request(self):
        return self.app.get_interface_document(self.url)

    def serve_forever(self):
        """Runs the ZeroMQ server."""

        while True:
            error = None

            initial_ctx = ZmqMethodContext(self)
            initial_ctx.in_string = [self.zmq_socket.recv()]

            contexts = self.generate_contexts(initial_ctx)
            p_ctx, others = contexts[0], contexts[1:]
            if p_ctx.in_error:
                p_ctx.out_object = p_ctx.in_error
                error = p_ctx.in_error

            else:
                self.get_in_object(p_ctx)

                if p_ctx.in_error:
                    p_ctx.out_object = p_ctx.in_error
                    error = p_ctx.in_error
                else:
                    self.get_out_object(p_ctx)
                    if p_ctx.out_error:
                        p_ctx.out_object = p_ctx.out_error
                        error = p_ctx.out_error

            self.get_out_string(p_ctx)

            process_contexts(self, others, error)

            self.zmq_socket.send(b''.join(p_ctx.out_string))

            p_ctx.close()

class ZeroMQThreadPoolServer(object):
    """Create a ZeroMQ server transport with several background workers,
    allowing asynchronous calls.

    More details on the pattern http://zguide.zeromq.org/page:all#Shared-Queue-DEALER-and-ROUTER-sockets"""

    def __init__(self, app, app_url, pool_size, wsdl_url=None, ctx=None, socket=None):
        if ctx and socket and ctx is not socket.context:
            raise ValueError("ctx should be the same as socket.context")

        self.app = app

        if ctx:
            self.ctx = ctx
        elif socket:
            self.ctx = socket.context
        else:
            self.ctx = zmq.Context()

        if socket:
            self.frontend = socket
        else:
            self.frontend = self.ctx.socket(zmq.ROUTER)
            self.frontend.bind(app_url)

        be_url = 'inproc://{tns}.{name}'.format(tns=self.app.tns, name=self.app.name)
        self.pool = []
        self.background_jobs = []
        for i in range(pool_size):
            worker, job = self.create_worker(i, be_url)
            self.pool.append(worker)
            self.background_jobs.append(job)

        self.backend = self.ctx.socket(zmq.DEALER)
        self.backend.bind(be_url)

    def create_worker(self, i, be_url):
        socket = self.ctx.socket(zmq.REP)
        socket.connect(be_url)
        worker = ZeroMQServer(self.app, be_url, socket=socket)
        job = threading.Thread(target=worker.serve_forever)
        job.daemon = True
        return worker, job

    def serve_forever(self):
        """Runs the ZeroMQ server."""

        for job in self.background_jobs:
            job.start()

        zmq.device(zmq.QUEUE, self.frontend, self.backend)

        # We never get here...
        self.frontend.close()
        self.backend.close()


text:
import React from 'react';
import { registerComponent, Components } from '../../lib/vulcan-lib';
import { Link } from '../../lib/reactRouterWrapper';
import { useHover } from '../common/withHover';
import { AnalyticsContext } from "../../lib/analyticsEvents";
import { DatabasePublicSetting } from '../../lib/publicSettings';
import classNames from 'classnames';

const useExperimentalTagStyleSetting = new DatabasePublicSetting<boolean>('useExperimentalTagStyle', false)

export const tagStyle = (theme: ThemeType): JssStyles => ({
  marginRight: 3,
  padding: 5,
  paddingLeft: 6,
  paddingRight: 6,
  marginBottom: 8,
  backgroundColor: theme.palette.grey[200],
  border: `solid 1px ${theme.palette.grey[200]}`,
  color: 'rgba(0,0,0,.9)',
  borderRadius: 3,
  ...theme.typography.commentStyle,
  cursor: "pointer"
})

const newTagStyle = (theme: ThemeType): JssStyles => ({
  marginRight: 4,
  padding: 5,
  paddingLeft: 8,
  paddingRight: 7,
  marginBottom: 8,
  borderRadius: 4,
  boxShadow: '1px 2px 5px rgba(0,0,0,.2)',
  color: theme.palette.primary.main,
  fontSize: 15
})

export const smallTagTextStyle = (theme: ThemeType): JssStyles => ({
  fontSize: 12,
  paddingTop: 1,
  paddingBottom: 2,
  marginBottom: 0
});

const styles = (theme: ThemeType): JssStyles => ({
  root: {
    display: "inline-block",
    cursor: "pointer",
    ...theme.typography.commentStyle,
    "&:hover": {
      opacity: 1
    },
    ...(useExperimentalTagStyleSetting.get()
      ? newTagStyle(theme)
      : tagStyle(theme)
    )
  },
  core: {
    backgroundColor: "white",
    border: "solid 1px rgba(0,0,0,.12)",
    color: theme.palette.grey[600]
  },
  score:  {
    paddingLeft: 5,
    color: 'rgba(0,0,0,0.7)',
  },
  name: {
    display: 'inline-block',
  },
  hovercard: {
  },
  smallText: {
    ...smallTagTextStyle(theme),
  }
});

const FooterTag = ({tagRel, tag, hideScore=false, classes, smallText}: {
  tagRel?: TagRelMinimumFragment,
  tag: TagBasicInfo,
  hideScore?: boolean,
  smallText?: boolean,
  classes: ClassesType,
}) => {
  const { hover, anchorEl, eventHandlers } = useHover({
    pageElementContext: "tagItem",
    tagId: tag._id,
    tagName: tag.name,
    tagSlug: tag.slug
  });
  const { PopperCard, TagRelCard } = Components

  if (tag.adminOnly) { return null }

  return (<AnalyticsContext tagName={tag.name} tagId={tag._id} tagSlug={tag.slug} pageElementContext="tagItem">

      <Link to={`/tag/${tag.slug}`}>
        {tag.name}
        {!hideScore && tagRel && {tagRel.baseScore}}
      </Link>
      {tagRel && <PopperCard open={hover} anchorEl={anchorEl} modifiers={{flip:{enabled:false}}}>

          <TagRelCard tagRel={tagRel} />

      </PopperCard>}

  </AnalyticsContext>);
}

const FooterTagComponent = registerComponent("FooterTag", FooterTag, {styles});

declare global {
  interface ComponentTypes {
    FooterTag: typeof FooterTagComponent
  }
}


text:
/************************************************************************************//**
// Copyright (c) 2006-2015 Advanced Micro Devices, Inc. All rights reserved.
/// \author AMD Developer Tools Team
/// \file
****************************************************************************************/

//=================================================================================================================================
//
//          Includes / defines / typedefs / static member variable initialization block
//
//=================================================================================================================================

// ignore VC++ warnings about fopen, fscanf, etc being deprecated
#if defined( _MSC_VER )
    #if _MSC_VER >= 1400
        #define _CRT_SECURE_NO_DEPRECATE
    #endif
#endif

#include "ObjLoader.h"
#include <assert.h>
#include <cstdio>
#include <cstring>
#include <map>

//=================================================================================================================================
//
//          Constructor(s) / Destructor(s) Block
//
//=================================================================================================================================

//=================================================================================================================================
//
//          Public methods block
//
//=================================================================================================================================

//=================================================================================================================================
/// Loads a mesh from an OBJ file
/// \param strFileName   The file name to load from
/// \param rVerticesOut  A set of vertices that is created from the OBJ
/// \param rFacesOut     A set of faces that is created from the OBJ
//=================================================================================================================================
bool ObjLoader::LoadGeometry(const char* strFileName, std::vector<ObjVertexFinal>& rVerticesOut, std::vector<ObjFace>& rFacesOut)
{
    //----------------------------------------------------------------------
    // Data
    //----------------------------------------------------------------------
    std::vector<ObjVertex3D> vertices;
    std::vector<ObjVertex3D> normals;
    std::vector<ObjVertex2D> texCoords;

    bool bHasTexCoords = false;
    bool bHasNormals   = false;

    char cLine[256];    //A line of the obj file

    //----------------------------------------------------------------------
    // Read OBJ file
    //----------------------------------------------------------------------
    FILE* pFile = fopen(strFileName, "rt");

    // Check if the file was opened
    if (NULL == pFile)
    {
        // Open failed
        return (false);

    } // end if ( NULL == pFile )

    //Read until we hit the end of the file
    while (!feof(pFile))
    {
        //Check the first char in the line
        int iStart = fgetc(pFile);

        // skip blank lines
        while ((iStart == 10) && (!feof(pFile))) { iStart = fgetc(pFile); }

        if (feof(pFile))
        {
            break;
        }

        //If the first letter is v, it is either a vertex, a text coord, or a vertex normal
        if (iStart == 'v')
        {
            //get the second char
            int iNext = fgetc(pFile);

            //if its a space, its a vertex coordinate
            if (iNext == ' ' || iNext == '\t')
            {
                ObjVertex3D vertex;

                //get the line
                fgets(cLine, 256, pFile);

                //get the vertex coords
                sscanf(cLine, " %f %f %f", &vertex.x, &vertex.y, &vertex.z);

                //add to the vertex array
                vertices.push_back(vertex);
            } // End if

            //if its a t, its a texture coord
            else if (iNext == 't')
            {
                ObjVertex2D texCoord;

                //get the line
                fgets(cLine, 256, pFile);

                //get the vertex coords
                sscanf(cLine, " %f %f", &texCoord.x, &texCoord.y);

                //add to the vertex array
                texCoords.push_back(texCoord);

                bHasTexCoords = true;
            } // End else if

            //if its an n its a normal
            else if (iNext == 'n')
            {
                ObjVertex3D normal;

                //get the line
                fgets(cLine, 256, pFile);

                //get the vertex coords
                sscanf(cLine, " %f %f %f", &normal.x, &normal.y, &normal.z);

                //add to the vertex array
                normals.push_back(normal);

                bHasNormals = true;
            } // End else if

            //else its something we don't support
            else
            {
                //scan the line and discard it
                fgets(cLine, 256, pFile);
            } // End else
        } // End if

        //if the first letter is f, its a face
        else if (iStart == 'f')
        {
            //read in the line
            fgets(cLine, 256, pFile);

            int numVerts = GetNumberOfVerticesInLine(cLine);

            int vertexIndices[256];
            int texCoordIndices[256];
            int normalIndices[256];

            assert(numVerts < 256);
            assert(numVerts > 0);

            ReadVertexIndices(cLine, numVerts, bHasTexCoords, bHasNormals,
                              vertexIndices, texCoordIndices, normalIndices);

            int fCount; // face count

            // Create triangles.
            //
            // Make a triangle fan if more than 3 vertices are specified
            //
            // If there are 3 vertices, 1 triangle
            // If there are 4 vertices, 2 triangles
            // If there are 5 vertices, 3 triangles
            // :
            for (fCount = 0; fCount < numVerts - 2; fCount++)
            {
                ObjFace face;
                face.vertexIndices[0] = vertexIndices[0];
                face.vertexIndices[1] = vertexIndices[fCount + 1];
                face.vertexIndices[2] = vertexIndices[fCount + 2];

                face.texCoordIndices[0] = texCoordIndices[0];
                face.texCoordIndices[1] = texCoordIndices[fCount + 1];
                face.texCoordIndices[2] = texCoordIndices[fCount + 2];

                face.normalIndices[0] = normalIndices[0];
                face.normalIndices[1] = normalIndices[fCount + 1];
                face.normalIndices[2] = normalIndices[fCount + 2];

                rFacesOut.push_back(face);
            } // End for
        } // End else if

        //if it isn't any of those, we don't care about it
        else
        {
            //read the whole line to advance
            fgets(cLine, 256, pFile);
        } // End else
    } // End while

    fclose(pFile);

    BuildFinalVertices(vertices, normals, texCoords, rFacesOut, rVerticesOut);

    return true;
} // End of LoadGeometry for CRmObjLoaderPlugIn

//=================================================================================================================================
//
//          Private methods block
//
//=================================================================================================================================

//=================================================================================================================================
/// Returns how many vertices are specified in one line read from OBJ
/// \param szLine  The line of text to count vertices in
//=================================================================================================================================

int ObjLoader::GetNumberOfVerticesInLine(const char* szLine)
{
    int pos = 0;
    int vertCount = 0;
    bool bInsideVertex = false;

    while (szLine[pos] != 0)
    {
        if (((szLine[pos] >= '0') && (szLine[pos] <= '9')) ||
            (szLine[pos] == '/'))
        {
            if (bInsideVertex == false)
            {
                vertCount++;
                bInsideVertex = true;
            } // End if
        } // End if
        else if (szLine[pos] == ' ')
        {
            if (bInsideVertex)
            {
                bInsideVertex = false;
            } // End if
        } // End else

        pos++;
    } // End while

    return vertCount;
} // End of GetNumberOfVerticesInLine for CRmObjLoaderPlugIn

//=================================================================================================================================
/// Parses a face line
//=============================================================================================================================
void ObjLoader::ReadVertexIndices(const char* szLine, int numVertsInLine,
                                  bool bHasTexCoords, bool bHasNormals,
                                  int* pVertIndices, int* pTexCoords, int* pNormals)
{
    const char* szNext = szLine;

    while (((*szNext) < '0') || ((*szNext) > '9'))
    {
        // Skip any character that's not a number
        assert(*szNext != '\0');
        szNext++;
    } // End while

    int i;

    for (i = 0; i < numVertsInLine; i++)
    {
        pVertIndices[i] = 0;
        pTexCoords[i] = 0;
        pNormals[i] = 0;

        int numRead;

        if (bHasTexCoords && bHasNormals)
        {
            numRead = sscanf(szNext, "%i/%i/%i", &pVertIndices[i], &pTexCoords[i], &pNormals[i]);

            if (numRead != 3)
            {
                sscanf(szNext, "%i//%i//%i", &pVertIndices[i], &pTexCoords[i], &pNormals[i]);
            }
        } // End if

        else if (!bHasTexCoords && bHasNormals)
        {
            numRead = sscanf(szNext, "%i/%i", &pVertIndices[i], &pNormals[i]);

            if (numRead != 2)
            {
                sscanf(szNext, "%i//%i", &pVertIndices[i], &pNormals[i]);
            }
        } // End if

        else if (bHasTexCoords && !bHasNormals)
        {
            numRead = sscanf(szNext, "%i/%i", &pVertIndices[i], &pTexCoords[i]);

            if (numRead != 2)
            {
                sscanf(szNext, "%i//%i", &pVertIndices[i], &pTexCoords[i]);
            }
        } // End if

        else
        {
            numRead = sscanf(szNext, "%i", &pVertIndices[i]);
        } // End else

        szNext = strchr(szNext, ' ');

        if (i < numVertsInLine - 1)
        {
            // If this is not the last one
            assert(szNext != NULL);
            szNext++;
        } // End if
    } // End for
} // End of ReadVertexIndices for CRmObjLoaderPlugIn

//=================================================================================================================================
/// Buildup vertex hash map and update each face's final vertex index
/// Build final vertex array
//=================================================================================================================================
void ObjLoader::BuildFinalVertices(const std::vector<ObjVertex3D>& vertices,
                                   const std::vector<ObjVertex3D>& normals,
                                   const std::vector<ObjVertex2D>& texCoords,
                                   std::vector<ObjFace>&     faces,
                                   std::vector<ObjVertexFinal>& finalVertices)
{
    std::map<VertexHashData, VertexHashData, vertex_less> vertexHashMap;

    int count = 0;
    unsigned int i;

    for (i = 0; i < faces.size(); i++)
    {
        ObjFace& face = faces[i];

        // OBj's index is 1 based, so subtract 1 to make it zero based indices
        int j;

        for (j = 0; j < 3; j++)
        {
            VertexHashData vHash;
            vHash.finalIndex    = count;
            vHash.vertexIndex   = face.vertexIndices[j];
            vHash.texCoordIndex = face.texCoordIndices[j];
            vHash.normalIndex   = face.normalIndices[j];

            std::map<VertexHashData, VertexHashData, vertex_less>::iterator itr = vertexHashMap.find(vHash);

            if (itr == vertexHashMap.end())
            {
                // If this combination of vertexIndex,texCoordIndex and normalIndex is nout found in map
                vertexHashMap.insert(std::map<VertexHashData, VertexHashData, vertex_less>::value_type(vHash, vHash));
                face.finalVertexIndices[j] = vHash.finalIndex;
                count++;

                ObjVertexFinal finalVertex;

                // OBJ's indices are 1 base, so subtract 1
                if (vHash.vertexIndex > 0)
                {
                    finalVertex.pos = vertices[vHash.vertexIndex - 1];
                }

                if (vHash.texCoordIndex > 0)
                {
                    finalVertex.texCoord = texCoords[vHash.texCoordIndex - 1];
                }

                if (vHash.normalIndex > 0)
                {
                    finalVertex.normal = normals[vHash.normalIndex - 1];
                }

                finalVertex.nNormalIndex = vHash.normalIndex;
                finalVertex.nTexcoordIndex = vHash.texCoordIndex;
                finalVertex.nVertexIndex = vHash.vertexIndex;
                finalVertices.push_back(finalVertex);
            } // End if
            else
            {
                VertexHashData& vHashFound = (*itr).second;
                face.finalVertexIndices[j] = vHashFound.finalIndex;
            } // End else
        } // End for
    } // End for
} // End of BuildFinalVertices for CRmObjLoaderPlugIn


text:
// @generated
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: src/com/facebook/buck/javacd/resources/proto/javacd.proto

package com.facebook.buck.javacd.model;

@javax.annotation.Generated(value="protoc", comments="annotations:PipeliningCommandOrBuilder.java.pb.meta")
public interface PipeliningCommandOrBuilder extends
    // @@protoc_insertion_point(interface_extends:javacd.api.v1.PipeliningCommand)
    com.google.protobuf.MessageOrBuilder {

  /**
   * .javacd.api.v1.BaseCommandParams baseCommandParams = 1;
   */
  boolean hasBaseCommandParams();
  /**
   * .javacd.api.v1.BaseCommandParams baseCommandParams = 1;
   */
  com.facebook.buck.javacd.model.BaseCommandParams getBaseCommandParams();
  /**
   * .javacd.api.v1.BaseCommandParams baseCommandParams = 1;
   */
  com.facebook.buck.javacd.model.BaseCommandParamsOrBuilder getBaseCommandParamsOrBuilder();

  /**
   * .javacd.api.v1.PipelineState pipeliningState = 2;
   */
  boolean hasPipeliningState();
  /**
   * .javacd.api.v1.PipelineState pipeliningState = 2;
   */
  com.facebook.buck.javacd.model.PipelineState getPipeliningState();
  /**
   * .javacd.api.v1.PipelineState pipeliningState = 2;
   */
  com.facebook.buck.javacd.model.PipelineStateOrBuilder getPipeliningStateOrBuilder();

  /**
   * .javacd.api.v1.BasePipeliningCommand abiCommand = 3;
   */
  boolean hasAbiCommand();
  /**
   * .javacd.api.v1.BasePipeliningCommand abiCommand = 3;
   */
  com.facebook.buck.javacd.model.BasePipeliningCommand getAbiCommand();
  /**
   * .javacd.api.v1.BasePipeliningCommand abiCommand = 3;
   */
  com.facebook.buck.javacd.model.BasePipeliningCommandOrBuilder getAbiCommandOrBuilder();

  /**
   * .javacd.api.v1.LibraryPipeliningCommand libraryCommand = 4;
   */
  boolean hasLibraryCommand();
  /**
   * .javacd.api.v1.LibraryPipeliningCommand libraryCommand = 4;
   */
  com.facebook.buck.javacd.model.LibraryPipeliningCommand getLibraryCommand();
  /**
   * .javacd.api.v1.LibraryPipeliningCommand libraryCommand = 4;
   */
  com.facebook.buck.javacd.model.LibraryPipeliningCommandOrBuilder getLibraryCommandOrBuilder();
}


text:
import urls
import urllib2
import json
import time
import csv

with open('fc.csv', 'wb') as csvfile:
    writer = csv.writer(csvfile)

    writer.writerow([
        'Key',
        'Name',
        'Year',
        'Rank By',
        'Rank',
        'Assets',
        'Assets %',
        'Giving',
        'Giving %',
        'Gifts Received',
        'Gifts Received %',
        'State',
        'Type'])

    for url in urls.generator():
        print "Processing: %s" % url

        try:
            response = urllib2.urlopen(url)
        except urllib2.URLError, e:
            print "URLError: " + url + " " + e.reason
            time.sleep(1)
        except urllib2.HTTPError, e:
            print "HTTPError: " + url + " " + e.code
            time.sleep(1)

        raw = response.read()
        data = json.loads(raw)

        for record in data['response']['rankings']:
            writer.writerow([
                record['foundation']['gm_key'],
                record['foundation']['name'],
                data['meta']['params']['year'],
                data['meta']['params']['rank_by'],
                record['rank'],
                record['assets']['amount'],
                record['assets']['pct'],
                record['giving']['amount'],
                record['giving']['pct'],
                record['gifts_received']['amount'],
                record['gifts_received']['pct'],
                record['state']['name'],
                record['type']['name']])


text:
"""Receives documents from the oplog worker threads and indexes them
    into the backend.

    This file is a document manager for MongoDB, but the intent
    is that this file can be used as an example to add on different backends.
    To extend this to other systems, simply implement the exact same class and
    replace the method definitions with API calls for the desired backend.
    """

import logging
import pymongo

from gridfs import GridFS
from mongo_connector import errors
from mongo_connector.util import exception_wrapper
from mongo_connector.doc_managers.doc_manager_base import DocManagerBase

wrap_exceptions = exception_wrapper({
    pymongo.errors.ConnectionFailure: errors.ConnectionFailed,
    pymongo.errors.OperationFailure: errors.OperationFailed})

LOG = logging.getLogger(__name__)

class DocManager(DocManagerBase):
    """The DocManager class creates a connection to the backend engine and
        adds/removes documents, and in the case of rollback, searches for them.

        The reason for storing id/doc pairs as opposed to doc's is so that
        multiple updates to the same doc reflect the most up to date version as
        opposed to multiple, slightly different versions of a doc.

        We are using MongoDB native fields for _id and ns, but we also store
        them as fields in the document, due to compatibility issues.
        """

    def __init__(self, url, **kwargs):
        """ Verify URL and establish a connection.
        """
        try:
            self.mongo = pymongo.MongoClient(url)
        except pymongo.errors.InvalidURI:
            raise errors.ConnectionFailed("Invalid URI for MongoDB")
        except pymongo.errors.ConnectionFailure:
            raise errors.ConnectionFailed("Failed to connect to MongoDB")
        self.namespace_set = kwargs.get("namespace_set")

    def _db_and_collection(self, namespace):
        return namespace.split('.', 1)

    @wrap_exceptions
    def _namespaces(self):
        """Provides the list of namespaces being replicated to MongoDB
        """
        if self.namespace_set:
            return self.namespace_set

        user_namespaces = []
        db_list = self.mongo.database_names()
        for database in db_list:
            if database == "config" or database == "local":
                continue
            coll_list = self.mongo[database].collection_names()
            for coll in coll_list:
                if coll.startswith("system"):
                    continue
                namespace = "%s.%s" % (database, coll)
                user_namespaces.append(namespace)
        return user_namespaces

    def stop(self):
        """Stops any running threads
        """
        LOG.info(
            "Mongo DocManager Stopped: If you will not target this system "
            "again with mongo-connector then you may drop the database "
            "__mongo_connector, which holds metadata for Mongo Connector."
        )

    @wrap_exceptions
    def handle_command(self, doc, namespace, timestamp):
        db, _ = self._db_and_collection(namespace)
        if doc.get('dropDatabase'):
            for new_db in self.command_helper.map_db(db):
                self.mongo.drop_database(db)

        if doc.get('renameCollection'):
            a = self.command_helper.map_namespace(doc['renameCollection'])
            b = self.command_helper.map_namespace(doc['to'])
            if a and b:
                self.mongo.admin.command(
                    "renameCollection", a, to=b)

        if doc.get('create'):
            new_db, coll = self.command_helper.map_collection(
                db, doc['create'])
            if new_db:
                self.mongo[new_db].create_collection(coll)

        if doc.get('drop'):
            new_db, coll = self.command_helper.map_collection(
                db, doc['drop'])
            if new_db:
                self.mongo[new_db].drop_collection(coll)

    @wrap_exceptions
    def update(self, document_id, update_spec, namespace, timestamp):
        """Apply updates given in update_spec to the document whose id
        matches that of doc.

        """
        db, coll = self._db_and_collection(namespace)
        updated = self.mongo[db][coll].find_and_modify(
            {'_id': document_id},
            update_spec,
            new=True
        )
        return updated

    @wrap_exceptions
    def upsert(self, doc, namespace, timestamp):
        """Update or insert a document into Mongo
        """
        database, coll = self._db_and_collection(namespace)

        self.mongo["__mongo_connector"][namespace].save({
            '_id': doc['_id'],
            "_ts": timestamp,
            "ns": namespace
        })
        self.mongo[database][coll].save(doc)

    @wrap_exceptions
    def remove(self, document_id, namespace, timestamp):
        """Removes document from Mongo

        The input is a python dictionary that represents a mongo document.
        The documents has ns and _ts fields.
        """
        database, coll = self._db_and_collection(namespace)

        doc2 = self.mongo['__mongo_connector'][namespace].find_and_modify(
            {'_id': document_id}, remove=True)
        if (doc2 and doc2.get('gridfs_id')):
            GridFS(self.mongo[database], coll).delete(doc2['gridfs_id'])
        else:
            self.mongo[database][coll].remove({'_id': document_id})

    @wrap_exceptions
    def insert_file(self, f, namespace, timestamp):
        database, coll = self._db_and_collection(namespace)

        id = GridFS(self.mongo[database], coll).put(f, filename=f.filename)
        self.mongo["__mongo_connector"][namespace].save({
            '_id': f._id,
            '_ts': timestamp,
            'ns': namespace,
            'gridfs_id': id
        })

    @wrap_exceptions
    def search(self, start_ts, end_ts):
        """Called to query Mongo for documents in a time range.
        """
        for namespace in self._namespaces():
            database, coll = self._db_and_collection(namespace)
            for ts_ns_doc in self.mongo["__mongo_connector"][namespace].find(
                {'_ts': {'$lte': end_ts,
                         '$gte': start_ts}}
            ):
                yield ts_ns_doc

    def commit(self):
        """ Performs a commit
        """
        return

    @wrap_exceptions
    def get_last_doc(self):
        """Returns the last document stored in Mongo.
        """
        def docs_by_ts():
            for namespace in self._namespaces():
                database, coll = self._db_and_collection(namespace)
                mc_coll = self.mongo["__mongo_connector"][namespace]
                for ts_ns_doc in mc_coll.find(limit=1).sort('_ts', -1):
                    yield ts_ns_doc

        return max(docs_by_ts(), key=lambda x: x["_ts"])


text:
'''
    This tries to demonstrate tracking an object shown on your webcam. It
    works with some types of objects in particular lighting conditions.

    Usage:

        Click twice on the webcam image, and that will define a rectangular
        area to be tracked. The area as tracked will be displayed on the
        screen when detected.

    Currently not optimized at all. Derived from the find_obj.py sample
    demo included with OpenCV
'''

#
# Derived from find_obj.py sample demo
#

import cv2
import numpy as np

# flann enum params are missing
FLANN_INDEX_KDTREE = 1  # bug: flann enums are missing
FLANN_INDEX_KMEANS = 2
FLANN_INDEX_COMPOSITE = 3
FLANN_INDEX_KDTREE_SINGLE = 4
FLANN_INDEX_HIERARCHICAL = 5
FLANN_INDEX_LSH    = 6
FLANN_INDEX_AUTOTUNED = 255

class DemoGoalie(object):

    def __init__(self, vc):
        self.vc = vc

        self.reset()

        # TODO: various types of detectors are available
        #self.detector = cv2.SIFT()
        self.detector = cv2.SURF(800)

        # TODO: various types of matchers available..
        #flann_args = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)
        #flann_args = dict(algorithm=FLANN_INDEX_LSH,
        #                  table_number=6,
        #                  key_size=12,
        #                  multi_probe_level=1)

        #flann_args = dict(algorithm=FLANN_INDEX_AUTOTUNED)
        #self.matcher = cv2.FlannBasedMatcher(flann_args, {})

        #self.matcher = cv2.BFMatcher(cv2.NORM_HAMMING)

        self.matcher = cv2.BFMatcher(cv2.NORM_L2)

    def reset(self):
        self.click1 = None
        self.click2 = None
        self.drag = None
        self.keypoints = None

    # do something with the matches. why?

    def define_interesting_features(self, img, coordinates):

        (x1, y1), (x2, y2) = coordinates
        self.feature_shape = [y2-y1, x2-x1]
        self.feature_offset = (x1, y1)

        # this is broken, support malformed rectangles
        mask = np.zeros(shape=(img.shape[0], img.shape[1]), dtype=np.uint8)
        mask[y1:y2, x1:x2] = 255

        self.keypoints, self.descriptors = self.detector.detectAndCompute(img, mask)

        if self.descriptors is None or len(self.descriptors) == 0:
            self.reset()
            return

        new_image = cv2.drawKeypoints(img, self.keypoints)
        cv2.imshow("Interest", new_image[y1:y2, x1:x2, :])

        print "%s keypoints found" % (len(self.keypoints))

    def filter_matches(self, kp1, kp2, matches, ratio = 0.75):
        '''From find_obj.py'''
        mkp1, mkp2 = [], []
        for m in matches:
            if len(m) == 2 and m[0].distance < m[1].distance * ratio:
                m = m[0]
                mkp1.append( kp1[m.queryIdx] )
                mkp2.append( kp2[m.trainIdx] )
        p1 = np.float32([kp.pt for kp in mkp1])
        p2 = np.float32([kp.pt for kp in mkp2])
        kp_pairs = zip(mkp1, mkp2)
        return p1, p2, kp_pairs

    def match(self, img):
        '''From find_obj.py'''

        kps, desc = self.detector.detectAndCompute(img, None)

        # don't try to match when there's nothing to match against
        if desc is None or len(desc) == 0:
            return

        # errors happen here depending on the algorithm parameters for flann. Not sure why.
        try:
            raw_matches = self.matcher.knnMatch(self.descriptors, desc, k=2)
        except cv2.error:
            return

        p1, p2, kp_pairs = self.filter_matches(self.keypoints, kps, raw_matches)

        # this allows us to transform the matched item if it has moved in 3d space
        if len(p1) >= 4:
            H, status = cv2.findHomography(p1, p2, cv2.RANSAC, 5.0)
        else:
            H, status = None, None

        self.draw_matches(img, kp_pairs, status, H)

    def draw_matches(self, img, kp_pairs, status, H):
        '''Derived from find_obj.py'''

        vis = img

        h, w = self.feature_shape[:2]

        if H is not None:
            corners = np.float32([[0, 0], [w, 0], [w, h], [0, h]]) + self.feature_offset
            corners = np.int32( cv2.perspectiveTransform(corners.reshape(1, -1, 2), H).reshape(-1, 2))
            cv2.polylines(vis, [corners], True, (255, 255, 255))

        if status is None:
            status = np.ones(len(kp_pairs), np.bool_)

        p2 = np.int32([kpp[1].pt for kpp in kp_pairs])

        green = (0, 255, 0)
        red = (0, 0, 255)

        for (x2, y2), inlier in zip(p2, status):
            if inlier:
                col = green
                cv2.circle(vis, (x2, y2), 2, col, -1)
            else:
                col = red
                r = 2
                thickness = 3
                cv2.line(vis, (x2-r, y2-r), (x2+r, y2+r), col, thickness)
                cv2.line(vis, (x2-r, y2+r), (x2+r, y2-r), col, thickness)

    def onmouse(self, event, x, y, flags, param):

        self.drag = (x, y)

        if flags & cv2.EVENT_FLAG_LBUTTON:
            if self.click1 is None:
                self.click1 = (x, y)
            elif self.click2 is None:
                self.click2 = (x, y)

    def process_video(self):

        cv2.namedWindow('Webcam')
        cv2.setMouseCallback('Webcam', self.onmouse)

        while cv2.waitKey(30) <= 0:
            success, img = self.vc.read()
            if not success:
                break

            if self.keypoints is None:

                # wait for the user to define the keypoints

                if self.click1 is not None:
                    if self.click2 is not None:

                        # extract rectangle, start finding matches
                        self.define_interesting_features(img, (self.click1, self.click2))

                    elif self.drag is not None:
                        cv2.rectangle(img, self.click1, self.drag, (255, 0 ,0) )

                kp,desc = self.detector.detectAndCompute(img, None)
                img = cv2.drawKeypoints(img, kp)

            else:

                # do matching in realtime and display the results
                # - might need to do some buffering to make this work
                self.match(img)

            cv2.imshow("Webcam", img)

if __name__ == '__main__':

    vc = cv2.VideoCapture()

    if not vc.open(0):
        print "Could not connect to webcam"
        exit(1)

    demo = DemoGoalie(vc)
    demo.process_video()


text:
package eu.ydp.empiria.player.client.controller.workmode;

public interface WorkModeTestClient extends WorkModeClientType {
    void enableTestMode();

    void disableTestMode();
}


text:
import {
    Component, Type, Input, OnInit, ViewChild,
    AfterViewInit, SimpleChange, ViewContainerRef,
    ComponentFactoryResolver, ComponentRef
} from '@angular/core';
import { FormGroup } from '@angular/forms';
import { FieldBase } from '../../../commonshared/form/field-base';
// import { DropdownField } from './dropdown-field'

import { uimap } from '../../../commonshared/decorators/ui-component.decorator'

// <f-text - input * ngSwitchCase="'textinput'"[simple] = "false"[form] = "form"[field] = "field"[model] = "model" > </f-text-input>
// <f-dropdown - input * ngSwitchCase="'dropdowninput'"[simple] = "false"[form] = "form"[field] = "field"[model] = "model" > </f-dropdown-input>
// <df-field - group - hori * ngSwitchCase="'fieldgroup'"[form] = "form"[field] = "field"[model] = "model" > </df-field-group-hori>
// <f-datetime - pick * ngSwitchCase="'datetimepick'"[simple] = "false"[form] = "form"[field] = "field"[model] = "model" > </f-datetime-pick>
// <f-select2 * ngSwitchCase="'select2'"[simple] = "false"[form] = "form"[field] = "field"[model] = "model" > </f-select2>
// <f-checkbox - input * ngSwitchCase="'checkbox'"[simple] = "false"[form] = "form"[field] = "field"[model] = "model" > </f-checkbox-input>
// <f-textarea * ngSwitchCase="'textarea'"[simple] = "false"[form] = "form"[field] = "field"[model] = "model" > </f-textarea>
// <f-radio - group * ngSwitchCase="'radiogroup'"[simple] = "false"[form] = "form"[field] = "field"[model] = "model" > </f-radio-group>
// <f-file - upload * ngSwitchCase="'fileupload'"[simple] = "false"[form] = "form"[field] = "field"[model] = "model" > </f-file-upload>

@Component({
    selector: 'df-field-m',
    template: `
    <div class="formContainer" fxLayout='row' fxLayoutWrap fxLayoutGap="15px" fxLayoutAlign="start baseline" style="padding:10px;align-content:flex-start">
        <ng-template #wrapper>
        </ng-template>
    </div>
    `
})
export class DynamicfieldMComponent implements OnInit, AfterViewInit {
    @Input() fields: FieldBase<any>[];
    @Input() form: FormGroup;
    @Input() model: any;

    @ViewChild('wrapper', { read: ViewContainerRef }) wrapperRef: ViewContainerRef;

    _tipmsg: string = "必填项";

    constructor(private vcRef: ViewContainerRef,
        private componentFactoryResolver: ComponentFactoryResolver, ) {

    }

    ngOnInit() {

    }

    ngAfterViewInit() {

    }

    ngAfterViewChecked() {

    }

    ngOnChanges(changes: { [propertyName: string]: SimpleChange }) {
        // debugger
        if (changes['fields'] && changes['fields'].currentValue) {
            // debugger
            setTimeout(() => {
                // debugger
                this.fields.forEach((field) => {
                    // debugger
                    let comp: Type<any> = uimap.get(field.selector)
                    //没有找到对应的模板
                    if (!comp) {
                        comp = uimap.get("m-custom")
                    }
                    let myComponentFactory
                    try {
                        myComponentFactory
                            = this.componentFactoryResolver.resolveComponentFactory(comp)

                    } catch (error) {//业务模块的模板解析不出来
                        comp = uimap.get("m-custom")
                        myComponentFactory
                            = this.componentFactoryResolver.resolveComponentFactory(comp)
                        console.warn("create component error:" + comp)
                    }
                    let cmpRef: ComponentRef<any>

                    //直接插到最后面 外面排好序再进来
                    cmpRef = this.wrapperRef.createComponent(myComponentFactory)
                    // debugger
                    cmpRef.instance.simple = false
                    cmpRef.instance.form = this.form
                    cmpRef.instance.field = field
                })
                // let value = this.form.value
                // console.log("form object after fields attach",this.form.controls)
                // console.log("fields attach formvalue-->", value)
                // this.form.patchValue(value)
            });
        }
    }

    // getCustomTemplateFields(): FieldBase<any>[] {
    //     let cstmTpltfields: FieldBase<any>[] = new Array<FieldBase<any>>()
    //     this.fields.forEach((field) => {
    //         if (field.controlType == "customtemplate") {
    //             cstmTpltfields.push(field)
    //         }
    //     })
    //     return cstmTpltfields
    // }
}


text:
package ru.aveselov.models;

import java.sql.Timestamp;

/**
 * Class represent User.
 *
 * @author Veselov Alexey.
 * @version 1.00
 * @since 02.04.2017
 */
public class User {

    /**
     * User's name.
     */
    private String name;
    /**
     * User's login.
     */
    private String login;
    /**
     * User's email.
     */
    private String email;
    /**
     * User's create date.
     */
    private Timestamp createDate;

    /**
     * Constructor.
     * @param name - user's name.
     * @param login - user's login.
     * @param email - user's email.
     * @param createDate - user's create date.
     */
    public User(String name, String login, String email, Timestamp createDate) {
        this.name = name;
        this.login = login;
        this.email = email;
        this.createDate = createDate;
    }

    /**
     * Getter.
     * @return user's name.
     */
    public String getName() {
        return name;
    }

    /**
     * Setter.
     * @param name - new user's name.
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * Getter.
     * @return user's login.
     */
    public String getLogin() {
        return login;
    }

    /**
     * Setter.
     * @param login - new user's login.
     */
    public void setLogin(String login) {
        this.login = login;
    }

    /**
     * Getter.
     * @return user's email.
     */
    public String getEmail() {
        return email;
    }

    /**
     * Setter.
     * @param email - new user's email.
     */
    public void setEmail(String email) {
        this.email = email;
    }

    /**
     * Getter.
     * @return user's create date.
     */
    public Timestamp getCreateDate() {
        return createDate;
    }

    /**
     * Setter.
     * @param createDate - new user's createDate.
     */
    public void setCreateDate(Timestamp createDate) {
        this.createDate = createDate;
    }
}


text:
package killyd

import (
	"github.com/prism-river/killy/internal/lg"
)

type Logger lg.Logger

const (
	LOG_DEBUG = lg.DEBUG
	LOG_INFO  = lg.INFO
	LOG_WARN  = lg.WARN
	LOG_ERROR = lg.ERROR
	LOG_FATAL = lg.FATAL
)

func (n *KILLYD) logf(level lg.LogLevel, f string, args ...interface{}) {
	opts := n.getOpts()
	lg.Logf(opts.Logger, opts.logLevel, level, f, args...)
}


text:
using System;

using Mono.Addins;

using Hyena.Widgets;

namespace FSpot.Extensions
{
	[ExtensionNode ("ComplexMenuItem")]
	public class ComplexMenuItemNode : MenuNode
	{
		[NodeAttribute]
		protected string widget_type;

		[NodeAttribute]
		protected string command_type;

		ICommand cmd;

		public override Gtk.MenuItem GetMenuItem (object parent)
		{
			ComplexMenuItem item = System.Activator.CreateInstance (Type.GetType (widget_type), parent) as ComplexMenuItem;
			cmd = (ICommand) Addin.CreateInstance (command_type);

            if (item != null)
                item.Activated += OnActivated;
            return item;
        }

        private void OnActivated (object o, EventArgs e)
        {
            if (cmd != null)
                cmd.Run (o, e);
        }
	}

}


text:
/**
 * Created by llan on 2017/5/5.
 */

import Product from '../models/product';
import Company from '../models/company';
import Body from '../models/body';
import Category from '../models/category';
import Property from '../models/property';
import fs from 'fs';
import path from 'path';
const md5 = require('blueimp-md5');
const salt = 'yourPassword';
const fontKey = 'myPassword';
const countPerPage = 10;
const currentPage = 1;
const paging = {
    'limit': countPerPage,                      // 每页多少条
    'offset': countPerPage * (currentPage - 1)  // 跳过多少条
};
const getSidebar = async()=> {
    try {
        let faddishResult = await Product.findAll({
            where: {
                isShow: true,
                property_id: '1'
            },
            raw: true
        });
        let freshResult = await Product.findAll({
            where: {
                isShow: true,
                property_id: '2'
            },
            raw: true
        });
        let mainResult = await Product.findAll({
            where: {
                isShow: true,
                property_id: '3'
            },
            raw: true
        });
        return {
            faddish: faddishResult,
            fresh: freshResult,
            main: mainResult
        }
    } catch (err) {
        console.log('Error with getSidebar', err);
    }
};
const getCompany = async()=> {
    try {
        let companyResult = await Company.findAll({
            raw: true
        });
        return {
            company: companyResult[0]
        }
    } catch (err) {
        console.log('Error with getCompany', err);
    }
};
const getBody = async()=> {
    try {
        let bodyResult = await Body.findAll({
            raw: true
        });
        return {
            body: bodyResult[0]
        }
    } catch (err) {
        console.log('Error with getBody', err);
    }
};
const getProperty = async()=> {
    try {
        let propertyResult = await Property.findAll({
            raw: true
        });
        return {
            properties: propertyResult
        }
    } catch (err) {
        console.log('Error with getProperty', err);
    }
};

const getBaseInfo = async()=> {
    let sideBarResult = await getSidebar();
    let company = await getCompany();
    let body = await getBody();
    let properties = await getProperty();
    return {
        ...sideBarResult,
        ...company,
        ...body,
        ...properties
    }
};
const getCategory = async()=> {
    try {
        let categories = await Category.findAll({
            raw: true
        });
        return {
            categories: categories
        }
    } catch (err) {
        console.log('Error with getCategory', err);
    }
};
const getProduct = async(id)=> {
    try {
        return {
            product: await Product.findById(id, {
                raw: true
            })
        };
    } catch (err) {
        console.log('Error with getProduct', err);
    }
};
const getAllProduct = async(currentPage)=> {
    try {
        return await Product.findAndCountAll({
            raw: true,
            limit: countPerPage,                      // 每页多少条
            offset: countPerPage * (currentPage - 1),  // 跳过多少条
            include: [Property, Category]
        });
    } catch (err) {
        console.log('Error with getProduct', err);
    }
};
const getProductByOption = async(name, property_id, category_id, currentPage)=> {
    try {
        let option = {};
        if (name) {
            option = {...option, name: {'$like': `%${name}%`}};
        }
        if (property_id != 0) {
            option = {...option, property_id: property_id};
        }
        if (category_id != 0) {
            option = {...option, category_id: category_id};
        }
        return await Product.findAndCountAll({
            raw: true,
            where: option,
            limit: countPerPage,                      // 每页多少条
            offset: countPerPage * (currentPage - 1),  // 跳过多少条
            include: [Property, Category]
        });
    } catch (err) {
        console.log('Error with getProductByOption', err);
    }
};
const getMoreCategory = async(id)=> {
    try {
        return await Product.findAll({
            where: {
                category_id: id
            },
            include: Property,
            raw: true,
            ...paging
        });
    } catch (err) {
        console.log('Error with getMoreCategory', err);
    }
};
const getMore = async(type)=> {
    try {
        return await Product.findAll({
            where: {
                property_id: type
            },
            raw: true,
            include: Property,
            ...paging
        });
    } catch (err) {
        console.log('Error with getMore', err);
    }
};

const editProduct = async(id, body)=> {
    try {
        return await Product.update(body, {
            where: {
                id: id
            }
        });
    } catch (err) {
        console.log('Error with editProduct', err);
    }
};
const createProduct = async(body)=> {
    try {
        return await Product.create(body);
    } catch (err) {
        console.log('Error with createProduct', err);
    }
};
const fileOperation = async(files)=> {
    let info = {};
    for (let key in files) {
        let imgInfo = {};
        const file = files[key][0],
            originalname = file.originalname,
            fieldname = file.fieldname,
            tmp_path = file.path,
            target_path = path.join(__dirname, '../assets/images/', originalname),
            src = fs.createReadStream(tmp_path),
            dest = fs.createWriteStream(target_path);
        await src.pipe(dest);
        await fs.unlink(tmp_path);
        imgInfo[`${fieldname}`] = `/images/${originalname}`;
        info = {
            ...info,
            ...imgInfo
        }
    }
    return info;
};

const changePassword = (password)=> {
    return md5(md5(password, fontKey, true), salt);
};
const deleteImgs = async(deleteArr)=> {
    for (let i = 0; i < deleteArr.length; i++) {
        let imgPath = path.join(__dirname, '../assets', deleteArr[i]);
        if (fs.existsSync(imgPath)) {
            await fs.unlink(imgPath);
        }
    }
};
const deleteProduct = async(id)=> {
    try {
        let product = await Product.findById(id, {
            raw: true
        });
        let {imgMainSrc, imgFirstSrc, imgSecondSrc, imgThirdSrc, imgFourthSrc} = product;
        let deleteArr = [];
        if (imgMainSrc) {
            deleteArr.push(imgMainSrc);
        }
        if (imgFirstSrc) {
            deleteArr.push(imgFirstSrc);
        }
        if (imgSecondSrc) {
            deleteArr.push(imgSecondSrc);
        }
        if (imgThirdSrc) {
            deleteArr.push(imgThirdSrc);
        }
        if (imgFourthSrc) {
            deleteArr.push(imgFourthSrc);
        }
        await deleteImgs(deleteArr);
        await Product.destroy({
            where: {
                id: id
            }
        });
    } catch (err) {
        console.log('Error with deleteProduct', err);
    }
};

export {
    getBaseInfo, getCategory, getMore,
    getMoreCategory, getCompany, getProperty,
    getProduct, editProduct, getAllProduct,
    getProductByOption, createProduct, fileOperation,
    changePassword, getBody, deleteProduct, deleteImgs,
    countPerPage
};


text:
elation.require(['engine.things.generic', 'engine.things.maskgenerator'], function() {

elation.component.add('engine.things.remoteplayer', function() {
  this.postinit = function() {
    this.defineProperties({startposition: {type: 'vector3', default: new THREE.Vector3()}})
  };

  this.createObject3D = function() {
    var geo = new THREE.CylinderGeometry(1, 1, 4, 8),
        mat = new THREE.MeshPhongMaterial({ color: 0x000000, transparent: true, opacity: 0.7 }),
        mesh = new THREE.Mesh(geo, mat);
    return mesh;
  };

  this.createChildren = function() {
    this.mask = this.spawn('maskgenerator', this.properties.player_id + '_mask', {
      'seed': this.properties.player_id.toString(),
      'tilesize': 0.25,
      'position': [0, 0, -1],
      'player_id': this.properties.player_id
    });
  };
}, elation.engine.things.generic);

});


text:
package org.apache.ignite.marshaller.jdk;

import org.apache.ignite.*;
import org.apache.ignite.internal.util.typedef.internal.*;
import org.apache.ignite.marshaller.*;
import org.jetbrains.annotations.*;

import java.io.*;

/**
 * Implementation of {@link org.apache.ignite.marshaller.Marshaller} based on JDK serialization mechanism.
 *

 *
Configuration

 *
Mandatory

 * This marshaller has no mandatory configuration parameters.
 *
Java Example

 * {@code JdkMarshaller} needs to be explicitly configured to override default {@link org.apache.ignite.marshaller.optimized.OptimizedMarshaller}.
 *

 * JdkMarshaller marshaller = new JdkMarshaller();
 *
 * IgniteConfiguration cfg = new IgniteConfiguration();
 *
 * // Override default marshaller.
 * cfg.setMarshaller(marshaller);
 *
 * // Starts grid.
 * G.start(cfg);
 *

 *
Spring Example

 * JdkMarshaller can be configured from Spring XML configuration file:
 *

 * <bean id="grid.custom.cfg" class="org.apache.ignite.configuration.IgniteConfiguration" singleton="true">
 *     ...
 *     <property name="marshaller">
 *         <bean class="org.apache.ignite.marshaller.jdk.JdkMarshaller"/>
 *     </property>
 *     ...
 * </bean>
 *

 *

 *
 *

 * For information about Spring framework visit www.springframework.org
 */
public class JdkMarshaller extends AbstractMarshaller {
    /** {@inheritDoc} */
    @Override public void marshal(@Nullable Object obj, OutputStream out) throws IgniteCheckedException {
        assert out != null;

        ObjectOutputStream objOut = null;

        try {
            objOut = new JdkMarshallerObjectOutputStream(new JdkMarshallerOutputStreamWrapper(out));

            // Make sure that we serialize only task, without class loader.
            objOut.writeObject(obj);

            objOut.flush();
        }
        catch (IOException e) {
            throw new IgniteCheckedException("Failed to serialize object: " + obj, e);
        }
        finally{
            U.closeQuiet(objOut);
        }
    }

    /** {@inheritDoc} */
    @SuppressWarnings({"unchecked"})
    @Override public <T> T unmarshal(InputStream in, @Nullable ClassLoader clsLdr) throws IgniteCheckedException {
        assert in != null;

        if (clsLdr == null)
            clsLdr = getClass().getClassLoader();

        ObjectInputStream objIn = null;

        try {
            objIn = new JdkMarshallerObjectInputStream(new JdkMarshallerInputStreamWrapper(in), clsLdr);

            return (T)objIn.readObject();
        }
        catch (IOException e) {
            throw new IgniteCheckedException("Failed to deserialize object with given class loader: " + clsLdr, e);
        }
        catch (ClassNotFoundException e) {
            throw new IgniteCheckedException("Failed to find class with given class loader for unmarshalling " +
                "(make sure same versions of all classes are available on all nodes or enable peer-class-loading): " +
                clsLdr, e);
        }
        finally{
            U.closeQuiet(objIn);
        }
    }

    /** {@inheritDoc} */
    @Override public String toString() {
        return S.toString(JdkMarshaller.class, this);
    }
}


text:
package org.lirazs.robolayout.core.resource.drawable;

import org.robovm.apple.coregraphics.CGSize;
import org.robovm.apple.uikit.UIEdgeInsets;

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

/**
 * Created on 7/30/2015.
 */
public class DrawableContainerConstantState extends DrawableConstantState {

    private DrawableContainer owner;

    // Drawables
    private List<Drawable> drawables;

    // Dimension
    private CGSize constantIntrinsicSize;
    private CGSize constantMinimumSize;
    private boolean constantSizeComputed;
    private boolean constantSize;

    // Statful
    private boolean haveStateful;
    private boolean stateful;

    // Padding
    private boolean paddingComputed;
    private UIEdgeInsets padding;
    private boolean hasPadding;

    public DrawableContainerConstantState(DrawableContainer owner) {
        this(null, owner);
    }

    public DrawableContainerConstantState(DrawableContainerConstantState state, DrawableContainer owner) {
        this.owner = owner;

        if(state != null) {
            List<Drawable> drawables = new ArrayList<>();

            for (Drawable drawable : state.getDrawables()) {
                Drawable copyDrawable = drawable.copy();
                copyDrawable.setDelegate(owner);

                drawables.add(copyDrawable);
            }

            this.drawables = drawables;
            this.constantIntrinsicSize = state.constantIntrinsicSize;
            this.constantMinimumSize = state.constantMinimumSize;
            this.constantSizeComputed = state.constantSizeComputed;
            this.haveStateful = state.haveStateful;
            this.stateful = state.stateful;
            this.paddingComputed = state.paddingComputed;
            this.padding = state.padding;
            this.hasPadding = state.hasPadding;
        } else {
            this.drawables = new ArrayList<>();
        }
    }

    public void addChildDrawable(Drawable drawable) {
        drawables.add(drawable);
        drawable.setDelegate(this.owner);

        this.haveStateful = false;
        this.constantSizeComputed = false;
        this.paddingComputed = false;
    }

    public void computeConstantSize() {
        CGSize minSize = CGSize.Zero();
        CGSize intrinsicSize = CGSize.Zero();

        for (Drawable drawable : drawables) {
            CGSize min = drawable.getMinimumSize();
            CGSize intrinsic = drawable.getIntrinsicSize();

            if(min.getWidth() > minSize.getWidth()) minSize.setWidth(min.getWidth());
            if(min.getHeight() > minSize.getHeight()) minSize.setHeight(min.getHeight());

            if(intrinsic.getWidth() > intrinsicSize.getWidth()) intrinsicSize.setWidth(intrinsic.getWidth());
            if(intrinsic.getHeight() > intrinsicSize.getHeight()) intrinsicSize.setHeight(intrinsic.getHeight());
        }

        this.constantIntrinsicSize = intrinsicSize;
        this.constantMinimumSize = minSize;
        this.constantSizeComputed = true;
    }

    public CGSize getConstantIntrinsicSize() {
        if(!isConstantSizeComputed()) {
            computeConstantSize();
        }
        return constantIntrinsicSize;
    }

    public CGSize getConstantMinimumSize() {
        if(!isConstantSizeComputed()) {
            computeConstantSize();
        }
        return constantMinimumSize;
    }

    public boolean isStateful() {
        if(haveStateful) {
            return stateful;
        }
        boolean stateful = false;
        for (Drawable drawable : drawables) {
            if(drawable.isStateful()) {
                stateful = true;
                break;
            }
        }
        this.stateful = stateful;
        haveStateful = true;

        return stateful;
    }

    public void computePadding() {
        UIEdgeInsets padding = UIEdgeInsets.Zero();
        boolean hasPadding = false;

        for (Drawable drawable : drawables) {
            if(drawable.hasPadding()) {
                hasPadding = true;

                UIEdgeInsets childPadding = drawable.getPadding();
                padding.setLeft(Math.max(padding.getLeft(), childPadding.getLeft()));
                padding.setRight(Math.max(padding.getRight(), childPadding.getRight()));
                padding.setTop(Math.max(padding.getTop(), childPadding.getTop()));
                padding.setBottom(Math.max(padding.getBottom(), childPadding.getBottom()));
            }
        }

        this.padding = padding;
        this.hasPadding = hasPadding;
        this.paddingComputed = true;
    }

    public boolean hasPadding() {
        if(!isPaddingComputed()) {
            computePadding();
        }
        return hasPadding;
    }

    public UIEdgeInsets getPadding() {
        return padding;
    }

    public boolean isConstantSizeComputed() {
        return constantSizeComputed;
    }

    public boolean isConstantSize() {
        return constantSize;
    }

    public boolean isPaddingComputed() {
        return paddingComputed;
    }

    public List<Drawable> getDrawables() {
        return drawables;
    }

    public void setConstantSize(boolean constantSize) {
        this.constantSize = constantSize;
    }
}