text:
// ========================================================================
// Copyright 199-2004 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ========================================================================

package org.mortbay.jetty.servlet;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.UnavailableException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.mortbay.io.Buffer;
import org.mortbay.io.ByteArrayBuffer;
import org.mortbay.io.WriterOutputStream;
import org.mortbay.io.nio.DirectNIOBuffer;
import org.mortbay.io.nio.IndirectNIOBuffer;
import org.mortbay.io.nio.NIOBuffer;
import org.mortbay.jetty.Connector;
import org.mortbay.jetty.HttpConnection;
import org.mortbay.jetty.HttpContent;
import org.mortbay.jetty.HttpFields;
import org.mortbay.jetty.HttpHeaderValues;
import org.mortbay.jetty.HttpHeaders;
import org.mortbay.jetty.HttpMethods;
import org.mortbay.jetty.InclusiveByteRange;
import org.mortbay.jetty.MimeTypes;
import org.mortbay.jetty.ResourceCache;
import org.mortbay.jetty.Response;
import org.mortbay.jetty.handler.ContextHandler;
import org.mortbay.jetty.nio.NIOConnector;
import org.mortbay.log.Log;
import org.mortbay.resource.FileResource;
import org.mortbay.resource.Resource;
import org.mortbay.resource.ResourceFactory;
import org.mortbay.util.IO;
import org.mortbay.util.MultiPartOutputStream;
import org.mortbay.util.TypeUtil;
import org.mortbay.util.URIUtil;

/* ------------------------------------------------------------ */
/** The default servlet.
 * This servlet, normally mapped to /, provides the handling for static
 * content, OPTION and TRACE methods for the context.
 * The following initParameters are supported, these can be set either
 * on the servlet itself or as ServletContext initParameters with a prefix
 * of org.mortbay.jetty.servlet.Default. :
 * <PRE>
 *   acceptRanges     If true, range requests and responses are
 *                    supported
 *
 *   dirAllowed       If true, directory listings are returned if no
 *                    welcome file is found. Else 403 Forbidden.
 *
 *   welcomeServlets  If true, attempt to dispatch to welcome files
 *                    that are servlets, but only after no matching static
 *                    resources could be found.
 *
 *                    This must be false if you want directory listings,
 *                    but have index.jsp in your welcome file list.
 *
 *   redirectWelcome  If true, welcome files are redirected rather than
 *                    forwarded to.
 *
 *   gzip             If set to true, then static content will be served as
 *                    gzip content encoded if a matching resource is
 *                    found ending with ".gz"
 *
 *  resourceBase      Set to replace the context resource base
 *
 *  relativeResourceBase
 *                    Set with a pathname relative to the base of the
 *                    servlet context root. Useful for only serving static content out
 *                    of only specific subdirectories.
 *
 *  aliases           If True, aliases of resources are allowed (eg. symbolic
 *                    links and caps variations). May bypass security constraints.
 *
 *  maxCacheSize      The maximum total size of the cache or 0 for no cache.
 *  maxCachedFileSize The maximum size of a file to cache
 *  maxCachedFiles    The maximum number of files to cache
 *  cacheType         Set to "bio", "nio" or "both" to determine the type resource cache.
 *                    A bio cached buffer may be used by nio but is not as efficient as an
 *                    nio buffer.  An nio cached buffer may not be used by bio.
 *
 *  useFileMappedBuffer
 *                    If set to true, it will use mapped file buffer to serve static content
 *                    when using NIO connector. Setting this value to false means that
 *                    a direct buffer will be used instead of a mapped file buffer.
 *                    By default, this is set to true.
 *
 *  cacheControl      If set, all static content will have this value set as the cache-control
 *                    header.
 *
 *
 * </PRE>
 *
 *
 * @author Greg Wilkins (gregw)
 * @author Nigel Canonizado
 */
public class DefaultServlet extends HttpServlet implements ResourceFactory
{
    private ContextHandler.SContext _context;

    private boolean _acceptRanges=true;
    private boolean _dirAllowed=true;
    private boolean _welcomeServlets=false;
    private boolean _redirectWelcome=false;
    private boolean _gzip=true;

    private Resource _resourceBase;
    private NIOResourceCache _nioCache;
    private ResourceCache _bioCache;

    private MimeTypes _mimeTypes;
    private String[] _welcomes;
    private boolean _aliases=false;
    private boolean _useFileMappedBuffer=false;
    ByteArrayBuffer _cacheControl;
    private ServletHandler _servletHandler;
    private ServletHolder _defaultHolder;

    /* ------------------------------------------------------------ */
    public void init()
        throws UnavailableException
    {
        ServletContext config=getServletContext();
        _context = (ContextHandler.SContext)config;
        _mimeTypes = _context.getContextHandler().getMimeTypes();

        _welcomes = _context.getContextHandler().getWelcomeFiles();
        if (_welcomes==null)
            _welcomes=new String[] {"index.jsp","index.html"};

        _acceptRanges=getInitBoolean("acceptRanges",_acceptRanges);
        _dirAllowed=getInitBoolean("dirAllowed",_dirAllowed);
        _welcomeServlets=getInitBoolean("welcomeServlets", _welcomeServlets);
        _redirectWelcome=getInitBoolean("redirectWelcome",_redirectWelcome);
        _gzip=getInitBoolean("gzip",_gzip);

        _aliases=getInitBoolean("aliases",_aliases);

        if (!_aliases && !FileResource.getCheckAliases())
            throw new IllegalStateException("Alias checking disabled");
        if (_aliases)
            config.log("Aliases are enabled");

        _useFileMappedBuffer=getInitBoolean("useFileMappedBuffer",_useFileMappedBuffer);

        String rrb = getInitParameter("relativeResourceBase");
        if (rrb!=null)
        {
            try
            {
                _resourceBase = _context.getContextHandler().getResource(URIUtil.SLASH).addPath(rrb);
            }
            catch (Exception e)
            {
                Log.warn(Log.EXCEPTION,e);
                throw new UnavailableException(e.toString());
            }
        }

        String rb=getInitParameter("resourceBase");
        if (rrb != null && rb != null)
            throw new  UnavailableException("resourceBase & relativeResourceBase");

        if (rb!=null)
        {
            try{_resourceBase=Resource.newResource(rb);}
            catch (Exception e)
            {
                Log.warn(Log.EXCEPTION,e);
                throw new UnavailableException(e.toString());
            }
        }

        String t=getInitParameter("cacheControl");
        if (t!=null)
            _cacheControl=new ByteArrayBuffer(t);

        try
        {
            if (_resourceBase==null)
                _resourceBase = _context.getContextHandler().getResource(URIUtil.SLASH);

            String cache_type =getInitParameter("cacheType");
            int max_cache_size=getInitInt("maxCacheSize", -2);
            int max_cached_file_size=getInitInt("maxCachedFileSize", -2);
            int max_cached_files=getInitInt("maxCachedFiles", -2);

            if (cache_type==null || "nio".equals(cache_type)|| "both".equals(cache_type))
            {
                if (max_cache_size==-2 || max_cache_size>0)
                {
                    _nioCache=new NIOResourceCache(_mimeTypes);
                    if (max_cache_size>0)
                        _nioCache.setMaxCacheSize(max_cache_size);
                    if (max_cached_file_size>=-1)
                        _nioCache.setMaxCachedFileSize(max_cached_file_size);
                    if (max_cached_files>=-1)
                        _nioCache.setMaxCachedFiles(max_cached_files);
                    _nioCache.start();
                }
            }
            if ("bio".equals(cache_type)|| "both".equals(cache_type))
            {
                if (max_cache_size==-2 || max_cache_size>0)
                {
                    _bioCache=new ResourceCache(_mimeTypes);
                    if (max_cache_size>0)
                        _bioCache.setMaxCacheSize(max_cache_size);
                    if (max_cached_file_size>=-1)
                        _bioCache.setMaxCachedFileSize(max_cached_file_size);
                    if (max_cached_files>=-1)
                        _bioCache.setMaxCachedFiles(max_cached_files);
                    _bioCache.start();
                }
            }
            if (_nioCache==null)
                _bioCache=null;
        }
        catch (Exception e)
        {
            Log.warn(Log.EXCEPTION,e);
            throw new UnavailableException(e.toString());
        }

        _servletHandler= (ServletHandler) _context.getContextHandler().getChildHandlerByClass(ServletHandler.class);
        ServletHolder[] holders = _servletHandler.getServlets();
        for (int i=holders.length;i-->0;)
            if (holders[i].getServletInstance()==this)
                _defaultHolder=holders[i];

        if (Log.isDebugEnabled()) Log.debug("resource base = "+_resourceBase);
    }

    /* ------------------------------------------------------------ */
    public String getInitParameter(String name)
    {
        String value=getServletContext().getInitParameter("org.mortbay.jetty.servlet.Default."+name);
	if (value==null)
	    value=super.getInitParameter(name);
	return value;
    }

    /* ------------------------------------------------------------ */
    private boolean getInitBoolean(String name, boolean dft)
    {
        String value=getInitParameter(name);
        if (value==null || value.length()==0)
            return dft;
        return (value.startsWith("t")||
                value.startsWith("T")||
                value.startsWith("y")||
                value.startsWith("Y")||
                value.startsWith("1"));
    }

    /* ------------------------------------------------------------ */
    private int getInitInt(String name, int dft)
    {
        String value=getInitParameter(name);
	if (value==null)
            value=getInitParameter(name);
        if (value!=null && value.length()>0)
            return Integer.parseInt(value);
        return dft;
    }

    /* ------------------------------------------------------------ */
    /** get Resource to serve.
     * Map a path to a resource. The default implementation calls
     * HttpContext.getResource but derived servlets may provide
     * their own mapping.
     * @param pathInContext The path to find a resource for.
     * @return The resource to serve.
     */
    public Resource getResource(String pathInContext)
    {
        if (_resourceBase==null)
            return null;
        Resource r=null;
        try
        {
            r = _resourceBase.addPath(pathInContext);
            if (!_aliases && r.getAlias()!=null)
            {
                if (r.exists())
                    Log.warn("Aliased resource: "+r+"=="+r.getAlias());
                return null;
            }
            if (Log.isDebugEnabled()) Log.debug("RESOURCE="+r);
        }
        catch (IOException e)
        {
            Log.ignore(e);
        }
        return r;
    }

    /* ------------------------------------------------------------ */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    	throws ServletException, IOException
    {
        String servletPath=null;
        String pathInfo=null;
        Enumeration reqRanges = null;
        Boolean included =(Boolean)request.getAttribute(Dispatcher.__INCLUDE_JETTY);
        if (included!=null && included.booleanValue())
        {
            servletPath=(String)request.getAttribute(Dispatcher.__INCLUDE_SERVLET_PATH);
            pathInfo=(String)request.getAttribute(Dispatcher.__INCLUDE_PATH_INFO);
            if (servletPath==null)
            {
                servletPath=request.getServletPath();
                pathInfo=request.getPathInfo();
            }
        }
        else
        {
            included=Boolean.FALSE;
            servletPath=request.getServletPath();
            pathInfo=request.getPathInfo();

            // Is this a range request?
            reqRanges = request.getHeaders(HttpHeaders.RANGE);
            if (reqRanges!=null && !reqRanges.hasMoreElements())
                reqRanges=null;
        }

        String pathInContext=URIUtil.addPaths(servletPath,pathInfo);
        boolean endsWithSlash=pathInContext.endsWith(URIUtil.SLASH);

        // Can we gzip this request?
        String pathInContextGz=null;
        boolean gzip=false;
        if (!included.booleanValue() && _gzip && reqRanges==null && !endsWithSlash )
        {
            String accept=request.getHeader(HttpHeaders.ACCEPT_ENCODING);
            if (accept!=null && accept.indexOf("gzip")>=0)
                gzip=true;
        }

        // Find the resource and content
        Resource resource=null;
        HttpContent content=null;

        Connector connector = HttpConnection.getCurrentConnection().getConnector();
        ResourceCache cache=(connector instanceof NIOConnector) ?_nioCache:_bioCache;
        try
        {
            // Try gzipped content first
            if (gzip)
            {
                pathInContextGz=pathInContext+".gz";
                resource=getResource(pathInContextGz);

                if (resource==null || !resource.exists()|| resource.isDirectory())
                {
                    gzip=false;
                    pathInContextGz=null;
                }
                else if (cache!=null)
                {
                    content=cache.lookup(pathInContextGz,resource);
                    if (content!=null)
                        resource=content.getResource();
                }

                if (resource==null || !resource.exists()|| resource.isDirectory())
                {
                    gzip=false;
                    pathInContextGz=null;
                }
            }

            // find resource
            if (!gzip)
            {
                if (cache==null)
                    resource=getResource(pathInContext);
                else
                {
                    content=cache.lookup(pathInContext,this);

                    if (content!=null)
                        resource=content.getResource();
                    else
                        resource=getResource(pathInContext);
                }
            }

            if (Log.isDebugEnabled())
                Log.debug("resource="+resource+(content!=null?" content":""));

            // Handle resource
            if (resource==null || !resource.exists())
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
            else if (!resource.isDirectory())
            {
                if (endsWithSlash && _aliases && pathInContext.length()>1)
                {
                    String q=request.getQueryString();
                    pathInContext=pathInContext.substring(0,pathInContext.length()-1);
                    if (q!=null&&q.length()!=0)
                        pathInContext+="?"+q;
                    response.sendRedirect(response.encodeRedirectURL(URIUtil.addPaths( _context.getContextPath(),pathInContext)));
                }
                else
                {
                    // ensure we have content
                    if (content==null)
                        content=new UnCachedContent(resource);

                    if (included.booleanValue() || passConditionalHeaders(request,response, resource,content))
                    {
                        if (gzip)
                        {
                            response.setHeader(HttpHeaders.CONTENT_ENCODING,"gzip");
                            String mt=_context.getMimeType(pathInContext);
                            if (mt!=null)
                                response.setContentType(mt);
                        }
                        sendData(request,response,included.booleanValue(),resource,content,reqRanges);
                    }
                }
            }
            else
            {
                String welcome=null;

                if (!endsWithSlash || (pathInContext.length()==1 && request.getAttribute("org.mortbay.jetty.nullPathInfo")!=null))
                {
                    StringBuffer buf=request.getRequestURL();
                    int param=buf.lastIndexOf(";");
                    if (param<0)
                        buf.append('/');
                    else
                        buf.insert(param,'/');
                    String q=request.getQueryString();
                    if (q!=null&&q.length()!=0)
                    {
                        buf.append('?');
                        buf.append(q);
                    }
                    response.setContentLength(0);
                    response.sendRedirect(response.encodeRedirectURL(buf.toString()));
                }
                // else look for a welcome file
                else if (null!=(welcome=getWelcomeFile(pathInContext)))
                {
                    if (_redirectWelcome)
                    {
                        // Redirect to the index
                        response.setContentLength(0);
                        String q=request.getQueryString();
                        if (q!=null&&q.length()!=0)
                            response.sendRedirect(response.encodeRedirectURL(URIUtil.addPaths( _context.getContextPath(),welcome)+"?"+q));
                        else
                            response.sendRedirect(response.encodeRedirectURL(URIUtil.addPaths( _context.getContextPath(),welcome)));
                    }
                    else
                    {
                        // Forward to the index
                        RequestDispatcher dispatcher=request.getRequestDispatcher(welcome);
                        if (dispatcher!=null)
                        {
                            if (included.booleanValue())
                                dispatcher.include(request,response);
                            else
                            {
                                request.setAttribute("org.mortbay.jetty.welcome",welcome);
                                dispatcher.forward(request,response);
                            }
                        }
                    }
                }
                else
                {
                    content=new UnCachedContent(resource);
                    if (included.booleanValue() || passConditionalHeaders(request,response, resource,content))
                        sendDirectory(request,response,resource,pathInContext.length()>1);
                }
            }
        }
        catch(IllegalArgumentException e)
        {
            Log.warn(Log.EXCEPTION,e);
            if(!response.isCommitted())
                response.sendError(500, e.getMessage());
        }
        finally
        {
            if (content!=null)
                content.release();
            else if (resource!=null)
                resource.release();
        }

    }

    /* ------------------------------------------------------------ */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
    {
        doGet(request,response);
    }

    /* ------------------------------------------------------------ */
    /* (non-Javadoc)
     * @see javax.servlet.http.HttpServlet#doTrace(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    protected void doTrace(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    }

    /* ------------------------------------------------------------ */
    /**
     * Finds a matching welcome file for the supplied {@link Resource}. This will be the first entry in the list of
     * configured {@link #_welcomes welcome files} that existing within the directory referenced by the <code>Resource</code>.
     * If the resource is not a directory, or no matching file is found, then it may look for a valid servlet mapping.
     * If there is none, then <code>null</code> is returned.
     * The list of welcome files is read from the {@link ContextHandler} for this servlet, or
     * <code>"index.jsp" , "index.html"</code> if that is <code>null</code>.
     * @param pathInContext The path in Context in which we are looking for a welcome
     * @return The path of the matching welcome file in context
     * @throws IOException
     * @throws MalformedURLException
     */
    private String getWelcomeFile(String pathInContext) throws MalformedURLException, IOException
    {
        if (_welcomes==null)
            return null;

        String welcome_servlet=null;
        for (int i=0;i<_welcomes.length;i++)
        {
            String welcome_in_context=URIUtil.addPaths(pathInContext,_welcomes[i]);
            Resource welcome=getResource(welcome_in_context);
            if (welcome!=null && welcome.exists())
                return _welcomes[i];

            if (_welcomeServlets && welcome_servlet==null)
            {
                Map.Entry entry=_servletHandler.getHolderEntry(welcome_in_context);
                if (entry!=null && entry.getValue()!=_defaultHolder)
                    welcome_servlet=welcome_in_context;
            }
        }
        return welcome_servlet;

    }

    /* ------------------------------------------------------------ */
    /* Check modification date headers.
     */
    protected boolean passConditionalHeaders(HttpServletRequest request,HttpServletResponse response, Resource resource, HttpContent content)
    throws IOException
    {
        try
        {
            if (!request.getMethod().equals(HttpMethods.HEAD) )
            {
                String ifms=request.getHeader(HttpHeaders.IF_MODIFIED_SINCE);
                if (ifms!=null)
                {
                    if (content!=null)
                    {
                        Buffer mdlm=content.getLastModified();
                        if (mdlm!=null)
                        {
                            if (ifms.equals(mdlm.toString()))
                            {
                                response.reset();
                                response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                                response.flushBuffer();
                                return false;
                            }
                        }
                    }

                    long ifmsl=request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE);
                    if (ifmsl!=-1)
                    {
                        if (resource.lastModified()/1000 <= ifmsl/1000)
                        {
                            response.reset();
                            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                            response.flushBuffer();
                            return false;
                        }
                    }
                }

                // Parse the if[un]modified dates and compare to resource
                long date=request.getDateHeader(HttpHeaders.IF_UNMODIFIED_SINCE);

                if (date!=-1)
                {
                    if (resource.lastModified()/1000 > date/1000)
                    {
                        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
                        return false;
                    }
                }

            }
        }
        catch(IllegalArgumentException iae)
        {
            if(!response.isCommitted())
                response.sendError(400, iae.getMessage());
            throw iae;
        }
        return true;
    }

    /* ------------------------------------------------------------------- */
    protected void sendDirectory(HttpServletRequest request,
                                 HttpServletResponse response,
                                 Resource resource,
                                 boolean parent)
    throws IOException
    {
        if (!_dirAllowed)
        {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return;
        }

        byte[] data=null;
        String base = URIUtil.addPaths(request.getRequestURI(),URIUtil.SLASH);
        String dir = resource.getListHTML(base,parent);
        if (dir==null)
        {
            response.sendError(HttpServletResponse.SC_FORBIDDEN,
            "No directory");
            return;
        }

        data=dir.getBytes("UTF-8");
        response.setContentType("text/html; charset=UTF-8");
        response.setContentLength(data.length);
        response.getOutputStream().write(data);
    }

    /* ------------------------------------------------------------ */
    protected void sendData(HttpServletRequest request,
                            HttpServletResponse response,
                            boolean include,
                            Resource resource,
                            HttpContent content,
                            Enumeration reqRanges)
    throws IOException
    {
        long content_length=resource.length();

        // Get the output stream (or writer)
        OutputStream out =null;
        try{out = response.getOutputStream();}
        catch(IllegalStateException e) {out = new WriterOutputStream(response.getWriter());}

        if ( reqRanges == null || !reqRanges.hasMoreElements())
        {
            //  if there were no ranges, send entire entity
            if (include)
            {
                resource.writeTo(out,0,content_length);
            }
            else
            {
                // See if a direct methods can be used?
                if (out instanceof HttpConnection.Output)
                {
                    if (response instanceof Response)
                    {
                        writeOptionHeaders(((Response)response).getHttpFields());
                        ((HttpConnection.Output)out).sendContent(content);
                    }
                    else if (content.getBuffer()!=null)
                    {
                        writeHeaders(response,content,content_length);
                        ((HttpConnection.Output)out).sendContent(content.getBuffer());
                    }
                    else
                    {
                        writeHeaders(response,content,content_length);
                        resource.writeTo(out,0,content_length);
                    }
                }
                else
                {
                    // Write content normally
                    writeHeaders(response,content,content_length);
                    resource.writeTo(out,0,content_length);
                }
            }
        }
        else
        {
            // Parse the satisfiable ranges
            List ranges =InclusiveByteRange.satisfiableRanges(reqRanges,content_length);

            //  if there are no satisfiable ranges, send 416 response
            if (ranges==null || ranges.size()==0)
            {
                writeHeaders(response, content, content_length);
                response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                response.setHeader(HttpHeaders.CONTENT_RANGE,
                        InclusiveByteRange.to416HeaderRangeString(content_length));
                resource.writeTo(out,0,content_length);
                return;
            }

            //  if there is only a single valid range (must be satisfiable
            //  since were here now), send that range with a 216 response
            if ( ranges.size()== 1)
            {
                InclusiveByteRange singleSatisfiableRange =
                    (InclusiveByteRange)ranges.get(0);
                long singleLength = singleSatisfiableRange.getSize(content_length);
                writeHeaders(response,content,singleLength                     );
                response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
                response.setHeader(HttpHeaders.CONTENT_RANGE,
                        singleSatisfiableRange.toHeaderRangeString(content_length));
                resource.writeTo(out,singleSatisfiableRange.getFirst(content_length),singleLength);
                return;
            }

            //  multiple non-overlapping valid ranges cause a multipart
            //  216 response which does not require an overall
            //  content-length header
            //
            writeHeaders(response,content,-1);
            String mimetype=content.getContentType().toString();
            MultiPartOutputStream multi = new MultiPartOutputStream(out);
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);

            // If the request has a "Request-Range" header then we need to
            // send an old style multipart/x-byteranges Content-Type. This
            // keeps Netscape and acrobat happy. This is what Apache does.
            String ctp;
            if (request.getHeader(HttpHeaders.REQUEST_RANGE)!=null)
                ctp = "multipart/x-byteranges; boundary=";
            else
                ctp = "multipart/byteranges; boundary=";
            response.setContentType(ctp+multi.getBoundary());

            InputStream in=resource.getInputStream();
            long pos=0;

            // calculate the content-length
            int length=0;
            String[] header = new String[ranges.size()];
            for (int i=0;i<ranges.size();i++)
            {
                InclusiveByteRange ibr = (InclusiveByteRange) ranges.get(i);
                header[i]=ibr.toHeaderRangeString(content_length);
                length+=
                    ((i>0)?2:0)+
                    2+multi.getBoundary().length()+2+
                    HttpHeaders.CONTENT_TYPE.length()+2+mimetype.length()+2+
                    HttpHeaders.CONTENT_RANGE.length()+2+header[i].length()+2+
                    2+
                    (ibr.getLast(content_length)-ibr.getFirst(content_length))+1;
            }
            length+=2+2+multi.getBoundary().length()+2+2;
            response.setContentLength(length);

            for (int i=0;i<ranges.size();i++)
            {
                InclusiveByteRange ibr = (InclusiveByteRange) ranges.get(i);
                multi.startPart(mimetype,new String[]{HttpHeaders.CONTENT_RANGE+": "+header[i]});

                long start=ibr.getFirst(content_length);
                long size=ibr.getSize(content_length);
                if (in!=null)
                {
                    // Handle non cached resource
                    if (start<pos)
                    {
                        in.close();
                        in=resource.getInputStream();
                        pos=0;
                    }
                    if (pos<start)
                    {
                        in.skip(start-pos);
                        pos=start;
                    }
                    IO.copy(in,multi,size);
                    pos+=size;
                }
                else
                    // Handle cached resource
                    (resource).writeTo(multi,start,size);

            }
            if (in!=null)
                in.close();
            multi.close();
        }
        return;
    }

    /* ------------------------------------------------------------ */
    protected void writeHeaders(HttpServletResponse response,HttpContent content,long count)
        throws IOException
    {
        if (content.getContentType()!=null && response.getContentType()==null)
            response.setContentType(content.getContentType().toString());

        if (response instanceof Response)
        {
            Response r=(Response)response;
            HttpFields fields = r.getHttpFields();

            if (content.getLastModified()!=null)
                fields.put(HttpHeaders.LAST_MODIFIED_BUFFER,content.getLastModified(),content.getResource().lastModified());
            else if (content.getResource()!=null)
            {
                long lml=content.getResource().lastModified();
                if (lml!=-1)
                    fields.putDateField(HttpHeaders.LAST_MODIFIED_BUFFER,lml);
            }

            if (count != -1)
                r.setLongContentLength(count);

            writeOptionHeaders(fields);
        }
        else
        {
            long lml=content.getResource().lastModified();
            if (lml>=0)
                response.setDateHeader(HttpHeaders.LAST_MODIFIED,lml);

            if (count != -1)
            {
                if (count<Integer.MAX_VALUE)
                    response.setContentLength((int)count);
                else
                    response.setHeader(HttpHeaders.CONTENT_LENGTH,TypeUtil.toString(count));
            }

            writeOptionHeaders(response);
        }
    }

    /* ------------------------------------------------------------ */
    protected void writeOptionHeaders(HttpFields fields) throws IOException
    {
        if (_acceptRanges)
            fields.put(HttpHeaders.ACCEPT_RANGES_BUFFER,HttpHeaderValues.BYTES_BUFFER);

        if (_cacheControl!=null)
            fields.put(HttpHeaders.CACHE_CONTROL_BUFFER,_cacheControl);
    }

    /* ------------------------------------------------------------ */
    protected void writeOptionHeaders(HttpServletResponse response) throws IOException
    {
        if (_acceptRanges)
            response.setHeader(HttpHeaders.ACCEPT_RANGES,"bytes");

        if (_cacheControl!=null)
            response.setHeader(HttpHeaders.CACHE_CONTROL,_cacheControl.toString());
    }

    /* ------------------------------------------------------------ */
    /*
     * @see javax.servlet.Servlet#destroy()
     */
    public void destroy()
    {
        try
        {
            if (_nioCache!=null)
                _nioCache.stop();
            if (_bioCache!=null)
                _bioCache.stop();
        }
        catch(Exception e)
        {
            Log.warn(Log.EXCEPTION,e);
        }
        finally
        {
            super.destroy();
        }
    }

    /* ------------------------------------------------------------ */
    /* ------------------------------------------------------------ */
    /* ------------------------------------------------------------ */
    private class UnCachedContent implements HttpContent
    {
        Resource _resource;

        UnCachedContent(Resource resource)
        {
            _resource=resource;
        }

        /* ------------------------------------------------------------ */
        public Buffer getContentType()
        {
            return _mimeTypes.getMimeByExtension(_resource.toString());
        }

        /* ------------------------------------------------------------ */
        public Buffer getLastModified()
        {
            return null;
        }

        /* ------------------------------------------------------------ */
        public Buffer getBuffer()
        {
            return null;
        }

        /* ------------------------------------------------------------ */
        public long getContentLength()
        {
            return _resource.length();
        }

        /* ------------------------------------------------------------ */
        public InputStream getInputStream() throws IOException
        {
            return _resource.getInputStream();
        }

        /* ------------------------------------------------------------ */
        public Resource getResource()
        {
            return _resource;
        }

        /* ------------------------------------------------------------ */
        public void release()
        {
            _resource.release();
            _resource=null;
        }

    }

    /* ------------------------------------------------------------ */
    /* ------------------------------------------------------------ */
    class NIOResourceCache extends ResourceCache
    {
        /* ------------------------------------------------------------ */
        public NIOResourceCache(MimeTypes mimeTypes)
        {
            super(mimeTypes);
        }

        /* ------------------------------------------------------------ */
        protected void fill(Content content) throws IOException
        {
            Buffer buffer=null;
            Resource resource=content.getResource();
            long length=resource.length();

            if (_useFileMappedBuffer && resource.getFile()!=null)
            {
                buffer = new DirectNIOBuffer(resource.getFile());
            }
            else
            {
                InputStream is = resource.getInputStream();
                try
                {
                    Connector connector = HttpConnection.getCurrentConnection().getConnector();
                    buffer = ((NIOConnector)connector).getUseDirectBuffers()?
                            (NIOBuffer)new DirectNIOBuffer((int)length):
                            (NIOBuffer)new IndirectNIOBuffer((int)length);

                }
                catch(OutOfMemoryError e)
                {
                    Log.warn(e.toString());
                    Log.debug(e);
                    buffer = new IndirectNIOBuffer((int) length);
                }
                buffer.readFrom(is,(int)length);
                is.close();
            }
            content.setBuffer(buffer);
        }
    }
}


text:
.class public final Landroid/speech/srec/MicrophoneInputStream;
.super Ljava/io/InputStream;
.source "MicrophoneInputStream.java"

# static fields
.field private static final TAG:Ljava/lang/String; = "MicrophoneInputStream"

# instance fields
.field private mAudioRecord:I

.field private mOneByte:[B

# direct methods
.method static constructor <clinit>()V
    .locals 1

    .prologue
    .line 33
    const-string/jumbo v0, "srec_jni"

    invoke-static {v0}, Ljava/lang/System;->loadLibrary(Ljava/lang/String;)V

    .line 34
    return-void
.end method

.method public constructor <init>(II)V
    .locals 4
    .param p1, "sampleRate"    # I
    .param p2, "fifoDepth"    # I
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;
        }
    .end annotation

    .prologue
    .line 46
    invoke-direct {p0}, Ljava/io/InputStream;-><init>()V

    .line 37
    const/4 v1, 0x0

    iput v1, p0, Landroid/speech/srec/MicrophoneInputStream;->mAudioRecord:I

    .line 38
    const/4 v1, 0x1

    new-array v1, v1, [B

    iput-object v1, p0, Landroid/speech/srec/MicrophoneInputStream;->mOneByte:[B

    .line 47
    invoke-static {p1, p2}, Landroid/speech/srec/MicrophoneInputStream;->AudioRecordNew(II)I

    move-result v1

    iput v1, p0, Landroid/speech/srec/MicrophoneInputStream;->mAudioRecord:I

    .line 48
    iget v1, p0, Landroid/speech/srec/MicrophoneInputStream;->mAudioRecord:I

    if-nez v1, :cond_0

    new-instance v1, Ljava/io/IOException;

    const-string v2, "AudioRecord constructor failed - busy?"

    invoke-direct {v1, v2}, Ljava/io/IOException;-><init>(Ljava/lang/String;)V

    throw v1

    .line 49
    :cond_0
    iget v1, p0, Landroid/speech/srec/MicrophoneInputStream;->mAudioRecord:I

    invoke-static {v1}, Landroid/speech/srec/MicrophoneInputStream;->AudioRecordStart(I)I

    move-result v0

    .line 50
    .local v0, "status":I
    if-eqz v0, :cond_1

    .line 51
    invoke-virtual {p0}, Landroid/speech/srec/MicrophoneInputStream;->close()V

    .line 52
    new-instance v1, Ljava/io/IOException;

    new-instance v2, Ljava/lang/StringBuilder;

    invoke-direct {v2}, Ljava/lang/StringBuilder;-><init>()V

    const-string v3, "AudioRecord start failed: "

    invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v2

    invoke-virtual {v2, v0}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v2

    invoke-virtual {v2}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v2

    invoke-direct {v1, v2}, Ljava/io/IOException;-><init>(Ljava/lang/String;)V

    throw v1

    .line 54
    :cond_1
    return-void
.end method

.method private static native AudioRecordDelete(I)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;
        }
    .end annotation
.end method

.method private static native AudioRecordNew(II)I
.end method

.method private static native AudioRecordRead(I[BII)I
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;
        }
    .end annotation
.end method

.method private static native AudioRecordStart(I)I
.end method

.method private static native AudioRecordStop(I)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;
        }
    .end annotation
.end method

# virtual methods
.method public close()V
    .locals 3
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;
        }
    .end annotation

    .prologue
    const/4 v2, 0x0

    .line 81
    iget v0, p0, Landroid/speech/srec/MicrophoneInputStream;->mAudioRecord:I

    if-eqz v0, :cond_0

    .line 83
    :try_start_0
    iget v0, p0, Landroid/speech/srec/MicrophoneInputStream;->mAudioRecord:I

    invoke-static {v0}, Landroid/speech/srec/MicrophoneInputStream;->AudioRecordStop(I)V
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_1

    .line 86
    :try_start_1
    iget v0, p0, Landroid/speech/srec/MicrophoneInputStream;->mAudioRecord:I

    invoke-static {v0}, Landroid/speech/srec/MicrophoneInputStream;->AudioRecordDelete(I)V
    :try_end_1
    .catchall {:try_start_1 .. :try_end_1} :catchall_0

    .line 88
    iput v2, p0, Landroid/speech/srec/MicrophoneInputStream;->mAudioRecord:I

    .line 92
    :cond_0
    return-void

    .line 88
    :catchall_0
    move-exception v0

    iput v2, p0, Landroid/speech/srec/MicrophoneInputStream;->mAudioRecord:I

    throw v0

    .line 85
    :catchall_1
    move-exception v0

    .line 86
    :try_start_2
    iget v1, p0, Landroid/speech/srec/MicrophoneInputStream;->mAudioRecord:I

    invoke-static {v1}, Landroid/speech/srec/MicrophoneInputStream;->AudioRecordDelete(I)V
    :try_end_2
    .catchall {:try_start_2 .. :try_end_2} :catchall_2

    .line 88
    iput v2, p0, Landroid/speech/srec/MicrophoneInputStream;->mAudioRecord:I

    throw v0

    :catchall_2
    move-exception v0

    iput v2, p0, Landroid/speech/srec/MicrophoneInputStream;->mAudioRecord:I

    throw v0
.end method

.method protected finalize()V
    .locals 2
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/lang/Throwable;
        }
    .end annotation

    .prologue
    .line 96
    iget v0, p0, Landroid/speech/srec/MicrophoneInputStream;->mAudioRecord:I

    if-eqz v0, :cond_0

    .line 97
    invoke-virtual {p0}, Landroid/speech/srec/MicrophoneInputStream;->close()V

    .line 98
    new-instance v0, Ljava/io/IOException;

    const-string/jumbo v1, "someone forgot to close MicrophoneInputStream"

    invoke-direct {v0, v1}, Ljava/io/IOException;-><init>(Ljava/lang/String;)V

    throw v0

    .line 100
    :cond_0
    return-void
.end method

.method public read()I
    .locals 5
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;
        }
    .end annotation

    .prologue
    const/4 v4, 0x1

    const/4 v3, 0x0

    .line 58
    iget v1, p0, Landroid/speech/srec/MicrophoneInputStream;->mAudioRecord:I

    if-nez v1, :cond_0

    new-instance v1, Ljava/lang/IllegalStateException;

    const-string/jumbo v2, "not open"

    invoke-direct {v1, v2}, Ljava/lang/IllegalStateException;-><init>(Ljava/lang/String;)V

    throw v1

    .line 59
    :cond_0
    iget v1, p0, Landroid/speech/srec/MicrophoneInputStream;->mAudioRecord:I

    iget-object v2, p0, Landroid/speech/srec/MicrophoneInputStream;->mOneByte:[B

    invoke-static {v1, v2, v3, v4}, Landroid/speech/srec/MicrophoneInputStream;->AudioRecordRead(I[BII)I

    move-result v0

    .line 60
    .local v0, "rtn":I
    if-ne v0, v4, :cond_1

    iget-object v1, p0, Landroid/speech/srec/MicrophoneInputStream;->mOneByte:[B

    aget-byte v1, v1, v3

    and-int/lit16 v1, v1, 0xff

    :goto_0
    return v1

    :cond_1
    const/4 v1, -0x1

    goto :goto_0
.end method

.method public read([B)I
    .locals 3
    .param p1, "b"    # [B
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;
        }
    .end annotation

    .prologue
    .line 65
    iget v0, p0, Landroid/speech/srec/MicrophoneInputStream;->mAudioRecord:I

    if-nez v0, :cond_0

    new-instance v0, Ljava/lang/IllegalStateException;

    const-string/jumbo v1, "not open"

    invoke-direct {v0, v1}, Ljava/lang/IllegalStateException;-><init>(Ljava/lang/String;)V

    throw v0

    .line 66
    :cond_0
    iget v0, p0, Landroid/speech/srec/MicrophoneInputStream;->mAudioRecord:I

    const/4 v1, 0x0

    array-length v2, p1

    invoke-static {v0, p1, v1, v2}, Landroid/speech/srec/MicrophoneInputStream;->AudioRecordRead(I[BII)I

    move-result v0

    return v0
.end method

.method public read([BII)I
    .locals 2
    .param p1, "b"    # [B
    .param p2, "offset"    # I
    .param p3, "length"    # I
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;
        }
    .end annotation

    .prologue
    .line 71
    iget v0, p0, Landroid/speech/srec/MicrophoneInputStream;->mAudioRecord:I

    if-nez v0, :cond_0

    new-instance v0, Ljava/lang/IllegalStateException;

    const-string/jumbo v1, "not open"

    invoke-direct {v0, v1}, Ljava/lang/IllegalStateException;-><init>(Ljava/lang/String;)V

    throw v0

    .line 73
    :cond_0
    iget v0, p0, Landroid/speech/srec/MicrophoneInputStream;->mAudioRecord:I

    invoke-static {v0, p1, p2, p3}, Landroid/speech/srec/MicrophoneInputStream;->AudioRecordRead(I[BII)I

    move-result v0

    return v0
.end method

redpajama_set_name: RedPajamaGithub


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('attendance', '0002_auto_20151103_0757'),
    ]

    operations = [
        migrations.AddField(
            model_name='event',
            name='type',
            field=models.ForeignKey(related_name='events', default=None, verbose_name=b'Event type', to='attendance.EventType'),
            preserve_default=False,
        ),
    ]


text:
module Cryptoexchange::Exchanges
  module Upbit
    module Services
      class Pairs < Cryptoexchange::Services::Pairs
        PAIRS_URL = "#{Cryptoexchange::Exchanges::Upbit::Market::API_URL}/market/all"

        def fetch
          output = super
          adapt(output)
        end

        def adapt(output)
          market_pairs = []
          output.each do |pair|
            target, base = pair['market'].split('-')
            market_pairs << Cryptoexchange::Models::MarketPair.new(
                              base: base,
                              target: target,
                              market: Upbit::Market::NAME
                            )
          end
          market_pairs
        end
      end
    end
  end
end


text:
#include "Elevation/IslandElevation.h"

TArray<FTriangleIndex> UIslandElevation::FindCoastTriangles(UTriangleDualMesh* Mesh, const TArray<bool>& r_ocean) const
{
	TSet<FTriangleIndex> coasts_t;
	for (FSideIndex s = 0; s < Mesh->NumSides; s++)
	{
		// Get the points at the start and end of each side
		FPointIndex r0 = Mesh->s_begin_r(s);
		FPointIndex r1 = Mesh->s_end_r(s);
		// Something is a coast if it's an ocean on one side and not on the other
		if (r_ocean[r0] && !r_ocean[r1])
		{
			// It might seem that we also need to check !r_ocean[r0] && r_ocean[r1]
			// and it might seem that we have to add both t and its opposite but
			// each t vertex shows up in *four* directed sides, so we only have to test
			// one fourth of those conditions to get the vertex in the list once.
			coasts_t.Add(Mesh->s_inner_t(s));
		}
	}
	return coasts_t.Array();
}

bool UIslandElevation::IsTriangleOcean(FTriangleIndex t, UTriangleDualMesh* Mesh, const TArray<bool>& r_ocean) const
{
	TArray<FPointIndex> trianglePoints = Mesh->t_circulate_r(t);
	int count = 0;
	for (FPointIndex r : trianglePoints)
	{
		if (r_ocean[r])
		{
			count++;
		}
	}
	// True if 2 or more points of the triangle are ocean
	return count >= 2;
}

bool UIslandElevation::IsRegionLake(FPointIndex r, const TArray<bool>& r_water, const TArray<bool>& r_ocean) const
{
	return r_water[r] && !r_ocean[r];
}

bool UIslandElevation::IsSideLake(FSideIndex s, UTriangleDualMesh* Mesh, const TArray<bool>& r_water, const TArray<bool>& r_ocean) const
{
	return IsRegionLake(Mesh->s_begin_r(s), r_water, r_ocean) || IsRegionLake(Mesh->s_end_r(s), r_water, r_ocean);
}

void UIslandElevation::DistributeElevations(TArray<float> &t_elevation, UTriangleDualMesh* Mesh, const TArray<int32> &t_coastdistance, const TArray<bool>& r_ocean, int32 MinDistance, int32 MaxDistance) const
{
	// We initially base elevation on distance from a coast
	for (FTriangleIndex t = 0; t < t_coastdistance.Num(); t++)
	{
		float d = (float)t_coastdistance[t];
		// Ocean values scale linearly down, so they're "upside-down mountains"
		if (IsTriangleOcean(t, Mesh, r_ocean))
		{
			t_elevation[t] = -d / (float)MinDistance;
		}
		else
		{
			t_elevation[t] = d / (float)MaxDistance;
		}
	}
}

void UIslandElevation::UpdateCoastDistance(TArray<int32> &t_coastdistance, UTriangleDualMesh* Mesh, FTriangleIndex Triangle, int32 Distance) const
{
	// Update the coast distance array to make sure we're still pointing to the nearest coast
	t_coastdistance[Triangle] = Distance;
	TArray<FSideIndex> out_s = Mesh->t_circulate_s(Triangle);
	for (int i = 0; i < out_s.Num(); i++)
	{
		FSideIndex s = out_s[i];
		FTriangleIndex neighbor_t = Mesh->s_outer_t(s);
		if (t_coastdistance[neighbor_t] > Distance + 1)
		{
			UpdateCoastDistance(t_coastdistance, Mesh, neighbor_t, Distance + 1);
		}
	}
}

void UIslandElevation::AssignTriangleElevations_Implementation(TArray<float>& t_elevation, TArray<int32>& t_coastdistance, TArray<FSideIndex>& t_downslope_s, UTriangleDualMesh* Mesh, const TArray<bool>& r_ocean, const TArray<bool>& r_water, FRandomStream& DrainageRng) const
{
	// TODO: this messes up lakes, as they will no longer all be at the same elevation

	// Initialize all triangles to be -1 triangles away from the nearest coast
	t_coastdistance.Empty(Mesh->NumTriangles);
	t_coastdistance.SetNumZeroed(Mesh->NumTriangles);
	for (int i = 0; i < t_coastdistance.Num(); i++)
	{
		t_coastdistance[i] = -1;
	}
	// Initialize all downslopes to point to an invalid index
	t_downslope_s.Empty(Mesh->NumTriangles);
	t_downslope_s.SetNumZeroed(Mesh->NumTriangles);
	for (int i = 0; i < t_downslope_s.Num(); i++)
	{
		t_downslope_s[i] = FSideIndex();
	}

	// Reset the elevation arrays to 0
	t_elevation.Empty(Mesh->NumTriangles);
	t_elevation.SetNumZeroed(Mesh->NumTriangles);

	// Find all coasts and set them to be 0 distance away from the nearest coast
	TArray<FTriangleIndex> queue_t = FindCoastTriangles(Mesh, r_ocean);
	if (queue_t.Num() == 0)
	{
		UE_LOG(LogMapGen, Error, TEXT("No triangles were marked as coast!"));
		return;
	}

	for (int t = 0; t < queue_t.Num(); t++)
	{
		t_coastdistance[queue_t[t]] = 0;
	}

	// Distance underwater to nearest shore
	int32 minDistance = 1;
	// Distance overland to nearest shore
	int32 maxDistance = 1;
	while (queue_t.Num() > 0)
	{
		// Get the next triangle and pop it from the queue
		FTriangleIndex current_t = queue_t[0];
		queue_t.RemoveAt(0);
		// Find all sides of the current triangle
		TArray<FSideIndex> out_s = Mesh->t_circulate_s(current_t);

		// Iterate over each side of the triangle, starting from a random offset
		int32 iOffset = DrainageRng.RandRange(0, out_s.Num() - 1);
		for (int i = 0; i < out_s.Num(); i++)
		{
			// Get the index of the side we're working on
			FSideIndex s = out_s[(i + iOffset) % out_s.Num()];
			// Check to see if this side is a lake
			// If it is, keep the distance from the nearest coast the same (to ensure that lakes keep elevation)
			// If it isn't, increment the distance from the nearest coast
			bool lake = IsSideLake(s, Mesh, r_water, r_ocean);
			int32 newDistance = (lake ? 0 : 1) + t_coastdistance[current_t];

			// Get the next triangle down the line
			FTriangleIndex neighbor_t = Mesh->s_outer_t(s);
			// Check if this next triangle has not had its distance set yet
			// or if it's closer to a coast than it thought it was
			if (t_coastdistance[neighbor_t] == -1 || newDistance < t_coastdistance[neighbor_t])
			{
				// Point it "downhill" to the next side
				t_downslope_s[neighbor_t] = Mesh->s_opposite_s(s);

				UpdateCoastDistance(t_coastdistance, Mesh, neighbor_t, newDistance);

				// If this tile is ocean, see if we need to update how far away this underwater tile
				// is from a coast
				if (IsTriangleOcean(neighbor_t, Mesh, r_ocean) && newDistance > minDistance) { minDistance = newDistance; }
				// If this tile is land, see if we need to update how far away this land tile is from a coast
				else if (!IsTriangleOcean(neighbor_t, Mesh, r_ocean) && newDistance > maxDistance) { maxDistance = newDistance; }

				if (lake)
				{
					// If we're a lake, make sure we're processed next
					queue_t.Insert(neighbor_t, 0);
				}
				else
				{
					// Otherwise, add us to the end of the queue
					queue_t.Add(neighbor_t);
				}
			}
		}

		if (queue_t.Num() == 0)
		{
			for (FTriangleIndex t = 0; t < t_coastdistance.Num(); t++)
			{
				if (t_coastdistance[t] == -1)
				{
					UE_LOG(LogMapGen, Warning, TEXT("Found unitialized coast distance triangle: %d"), t);
				}
			}
		}
	}

	// Now to distribute the actual elevations
	DistributeElevations(t_elevation, Mesh, t_coastdistance, r_ocean, minDistance, maxDistance);
}

void UIslandElevation::RedistributeTriangleElevations_Implementation(TArray<float>& t_elevation, UTriangleDualMesh* Mesh, const TArray<bool>& r_ocean) const
{
	// SCALE_FACTOR increases the mountain area. At 1.0 the maximum
	// elevation barely shows up on the map, so we set it to 1.1.
	const float SCALE_FACTOR = 1.1f;

	TArray<FTriangleIndex> nonocean_t;
	for (FTriangleIndex t = 0; t < t_elevation.Num(); t++)
	{
		if (!IsTriangleOcean(t, Mesh, r_ocean))
		{
			nonocean_t.Add(t);
		}
	}

	nonocean_t.Sort([t_elevation](const FTriangleIndex& A, const FTriangleIndex& B)
	{
		return t_elevation[A] < t_elevation[B];
	});

	if (nonocean_t.Num() > 0)
	{
		UE_LOG(LogMapGen, Log, TEXT("Sorted non-ocean bottom value: %f. Sorted non-ocean top value: %f"), t_elevation[nonocean_t[0]], t_elevation[nonocean_t[nonocean_t.Num() - 1]]);
	}

	for (int i = 0; i < nonocean_t.Num(); i++)
	{
		// Let y(x) be the total area that we want at elevation <= x.
		// We want the higher elevations to occur less than lower
		// ones, and set the area to be y(x) = 1 - (1-x)^2.
		float y = i / (nonocean_t.Num() - 1.0f);
		// Now we have to solve for x, given the known y.
		//  *  y = 1 - (1-x)^2
		//  *  y = 1 - (1 - 2x + x^2)
		//  *  y = 2x - x^2
		//  *  x^2 - 2x + y = 0
		// From this we can use the quadratic equation to get:
		float x = FMath::Sqrt(SCALE_FACTOR) - FMath::Sqrt(SCALE_FACTOR*(1 - y));
		if (x > 1.0)
		{
			x = 1.0;
		}
		//UE_LOG(LogMapGen, Log, TEXT("Redistributing elevation for triangle %d for %f to %f."), nonocean_t[i], t_elevation[nonocean_t[i]], x);
		t_elevation[nonocean_t[i]] = x;
	}
}

void UIslandElevation::AssignRegionElevations_Implementation(TArray<float>& r_elevation, UTriangleDualMesh* Mesh, const TArray<float>& t_elevation, const TArray<bool>& r_ocean) const
{
	const float max_ocean_elevation = -0.01;

	r_elevation.Empty(Mesh->NumRegions);
	r_elevation.SetNumZeroed(Mesh->NumRegions);

	TArray<FTriangleIndex> out_t;
	for (FPointIndex r = 0; r < Mesh->NumRegions; r++)
	{
		out_t = Mesh->r_circulate_t(r);
		float elevation = 0.0f;
		for (FTriangleIndex t : out_t)
		{
			elevation += t_elevation[t];
		}

		r_elevation[r] = elevation / out_t.Num();
		if (r_ocean[r] && r_elevation[r] > max_ocean_elevation)
		{
			r_elevation[r] = max_ocean_elevation;
		}
	}
}

void UIslandElevation::assign_t_elevation(TArray<float>& t_elevation, TArray<int32>& t_coastdistance, TArray<FSideIndex>& t_downslope_s, UTriangleDualMesh* Mesh, const TArray<bool>& r_ocean, const TArray<bool>& r_water, FRandomStream& DrainageRng) const
{
	AssignTriangleElevations(t_elevation, t_coastdistance, t_downslope_s, Mesh, r_ocean, r_water, DrainageRng);
}

void UIslandElevation::redistribute_t_elevation(TArray<float>& t_elevation, UTriangleDualMesh* Mesh, const TArray<bool>& r_ocean) const
{
	RedistributeTriangleElevations(t_elevation, Mesh, r_ocean);
}

void UIslandElevation::assign_r_elevation(TArray<float>& r_elevation, UTriangleDualMesh* Mesh, const TArray<float>& t_elevation, const TArray<bool>& r_ocean) const
{
	AssignRegionElevations(r_elevation, Mesh, t_elevation, r_ocean);
}


text:
This repository is for a course taken at UNA given by:
### Erick Salas-Chaverri - ([ericksc](https://github.com/ericksc))

This course is possible thanks to:
### *Majid Bayani Abbasy*

Instructions about running Python:
### [Instructions](HOW-TO.md)


text:
package edu.uci.ics.asterix.runtime.evaluators.accessors;

import java.io.DataOutput;
import java.io.IOException;

import edu.uci.ics.asterix.dataflow.data.nontagged.serde.AIntervalSerializerDeserializer;
import edu.uci.ics.asterix.formats.nontagged.AqlSerializerDeserializerProvider;
import edu.uci.ics.asterix.om.base.ADate;
import edu.uci.ics.asterix.om.base.ADateTime;
import edu.uci.ics.asterix.om.base.AMutableDate;
import edu.uci.ics.asterix.om.base.AMutableDateTime;
import edu.uci.ics.asterix.om.base.AMutableTime;
import edu.uci.ics.asterix.om.base.ANull;
import edu.uci.ics.asterix.om.base.ATime;
import edu.uci.ics.asterix.om.functions.AsterixBuiltinFunctions;
import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory;
import edu.uci.ics.asterix.om.types.ATypeTag;
import edu.uci.ics.asterix.om.types.BuiltinType;
import edu.uci.ics.asterix.om.types.EnumDeserializer;
import edu.uci.ics.asterix.runtime.evaluators.base.AbstractScalarFunctionDynamicDescriptor;
import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException;
import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluator;
import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory;
import edu.uci.ics.hyracks.api.dataflow.value.ISerializerDeserializer;
import edu.uci.ics.hyracks.data.std.api.IDataOutputProvider;
import edu.uci.ics.hyracks.data.std.util.ArrayBackedValueStorage;
import edu.uci.ics.hyracks.dataflow.common.data.accessors.IFrameTupleReference;

public class TemporalIntervalEndAccessor extends AbstractScalarFunctionDynamicDescriptor {

    private static final long serialVersionUID = 1L;

    private static final FunctionIdentifier FID = AsterixBuiltinFunctions.ACCESSOR_TEMPORAL_INTERVAL_END;

    private static final byte SER_INTERVAL_TYPE_TAG = ATypeTag.INTERVAL.serialize();
    private static final byte SER_NULL_TYPE_TAG = ATypeTag.NULL.serialize();

    private static final byte SER_DATE_TYPE_TAG = ATypeTag.DATE.serialize();
    private static final byte SER_TIME_TYPE_TAG = ATypeTag.TIME.serialize();
    private static final byte SER_DATETIME_TYPE_TAG = ATypeTag.DATETIME.serialize();

    public static final IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {

        @Override
        public IFunctionDescriptor createFunctionDescriptor() {
            return new TemporalIntervalEndAccessor();
        }
    };

    public ICopyEvaluatorFactory createEvaluatorFactory(final ICopyEvaluatorFactory[] args) throws AlgebricksException {
        return new ICopyEvaluatorFactory() {

            private static final long serialVersionUID = 1L;

            @Override
            public ICopyEvaluator createEvaluator(final IDataOutputProvider output) throws AlgebricksException {
                return new ICopyEvaluator() {

                    private final DataOutput out = output.getDataOutput();

                    private final ArrayBackedValueStorage argOut = new ArrayBackedValueStorage();

                    private final ICopyEvaluator eval = args[0].createEvaluator(argOut);

                    // possible output
                    @SuppressWarnings("unchecked")
                    private final ISerializerDeserializer<ADate> dateSerde = AqlSerializerDeserializerProvider.INSTANCE
                            .getSerializerDeserializer(BuiltinType.ADATE);
                    private final AMutableDate aDate = new AMutableDate(0);
                    @SuppressWarnings("unchecked")
                    private final ISerializerDeserializer<ADateTime> datetimeSerde = AqlSerializerDeserializerProvider.INSTANCE
                            .getSerializerDeserializer(BuiltinType.ADATETIME);
                    private final AMutableDateTime aDateTime = new AMutableDateTime(0);
                    @SuppressWarnings("unchecked")
                    private final ISerializerDeserializer<ATime> timeSerde = AqlSerializerDeserializerProvider.INSTANCE
                            .getSerializerDeserializer(BuiltinType.ATIME);
                    private final AMutableTime aTime = new AMutableTime(0);
                    @SuppressWarnings("unchecked")
                    private final ISerializerDeserializer<ANull> nullSerde = AqlSerializerDeserializerProvider.INSTANCE
                            .getSerializerDeserializer(BuiltinType.ANULL);

                    @Override
                    public void evaluate(IFrameTupleReference tuple) throws AlgebricksException {
                        argOut.reset();
                        eval.evaluate(tuple);
                        byte[] bytes = argOut.getByteArray();

                        try {
                            if (bytes[0] == SER_NULL_TYPE_TAG) {
                                nullSerde.serialize(ANull.NULL, out);
                                return;
                            } else if (bytes[0] == SER_INTERVAL_TYPE_TAG) {
                                byte timeType = AIntervalSerializerDeserializer.getIntervalTimeType(bytes, 1);
                                long endTime = AIntervalSerializerDeserializer.getIntervalEnd(bytes, 1);
                                if (timeType == SER_DATE_TYPE_TAG) {
                                    aDate.setValue((int) (endTime));
                                    dateSerde.serialize(aDate, out);
                                } else if (timeType == SER_TIME_TYPE_TAG) {
                                    aTime.setValue((int) (endTime));
                                    timeSerde.serialize(aTime, out);
                                } else if (timeType == SER_DATETIME_TYPE_TAG) {
                                    aDateTime.setValue(endTime);
                                    datetimeSerde.serialize(aDateTime, out);
                                }
                            } else {
                                throw new AlgebricksException(FID.getName() + ": expects NULL/INTERVAL, but got "
                                        + EnumDeserializer.ATYPETAGDESERIALIZER.deserialize(bytes[0]));
                            }
                        } catch (IOException e) {
                            throw new AlgebricksException(e);
                        }
                    }
                };
            }
        };
    }

    /* (non-Javadoc)
     * @see edu.uci.ics.asterix.om.functions.AbstractFunctionDescriptor#getIdentifier()
     */
    @Override
    public FunctionIdentifier getIdentifier() {
        return FID;
    }

}


text:
import React, { Component, Fragment } from 'react'
import { getCurrentLanguage } from '../../lib/i18n'

// Components
import Button from '../button/Button'
import Overlay from '../overlay/Overlay'
import LanguageModal from './language-modal/LanguageModal'

class LanguageSelector extends Component {
  state = { isLanguageModalOpen: false }

  onLanguageEditOpen = () => this.setState({ isLanguageModalOpen: true })

  onLanguageEditClose = () => this.setState({ isLanguageModalOpen: false })

  render () {
    const { t } = this.props

    return (
      <Fragment>

            {getCurrentLanguage()}

          <Button className="tc" bg='bg-teal' minWidth={100} onClick={this.onLanguageEditOpen}>
            {t('app:actions.change')}
          </Button>

        <Overlay show={this.state.isLanguageModalOpen} onLeave={this.onLanguageEditClose} >
          <LanguageModal className='outline-0' onLeave={this.onLanguageEditClose} t={t} />
        </Overlay>
      </Fragment>
    )
  }
}

export default LanguageSelector


text:
package example.com.cv4j.example.controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import example.com.cv4j.example.model.EventData;

/**
 * Created by zhigang on 2018/1/2.
 */

public class DefaultController implements ActionListener {

    private EventHandler eventHandler;

    public DefaultController(EventHandler handler) {
        this.eventHandler = handler;
    }

    @Override
    public void actionPerformed(ActionEvent cmd) {
        EventData ed = new EventData();
        ed.putData(cmd.getActionCommand(), cmd.getActionCommand());
        eventHandler.handleEvent(ed);
    }
}


text:
exports.BattleScripts = {
	init: function() {
		for (var i in this.data.Pokedex) {
			var tier = '';
			var adjustment = 0;
			if (this.data.FormatsData[i]) tier = this.data.FormatsData[i].tier;
			switch (tier) {
			case 'OU':
				adjustment = 6;
				break;
			case 'BL':
				adjustment = 12;
				break;
			case 'UU':
				adjustment = 18;
				break;
			case 'BL2':
				adjustment = 24;
				break;
			case 'RU':
				adjustment = 30;
				break;
			case 'BL3':
				adjustment = 36;
				break;
			case 'NU':
				adjustment = 42;
				break;
			case 'NFE':
				adjustment = 48;
				break;
			case 'LC':
				adjustment = 54;
			}

			if (adjustment) {
				this.data.Pokedex[i].baseStats.hp += adjustment;
				this.data.Pokedex[i].baseStats.atk += adjustment;
				this.data.Pokedex[i].baseStats.def += adjustment;
				this.data.Pokedex[i].baseStats.spa += adjustment;
				this.data.Pokedex[i].baseStats.spd += adjustment;
				this.data.Pokedex[i].baseStats.spe += adjustment;
			}
		}
	}
};


text:
SameBoy is an open source Game Boy (DMG) and Game Boy Color (CGB) emulator, written in portable C. It has a native Cocoa frontend for macOS, an SDL frontend for other operating systems, and a libretro core. It also includes a text-based debugger with an expression evaluator. Visit [the website](https://sameboy.github.io/).

## Features
Features common to both Cocoa and SDL versions:
 * Supports Game Boy (DMG) and Game Boy Color (CGB) emulation
 * Lets you choose the model you want to emulate regardless of ROM
 * High quality 96KHz audio
 * Battery save support
 * Save states
 * Includes open source DMG and CGB boot ROMs:
   * Complete support for (and documentation of) *all* game-specific palettes in the CGB boot ROM, for accurate emulation of Game Boy games on a Game Boy Color
   * Supports manual palette selection with key combinations, with 4 additional new palettes (A + B + direction)
   * Supports palette selection in a CGB game, forcing it to run in 'paletted' DMG mode, if ROM allows doing so.
   * Support for games with a non-Nintendo logo in the header
   * No long animation in the DMG boot
 * Advanced text-based debugger with an expression evaluator, disassembler, conditional breakpoints, conditional watchpoints, backtracing and other features
 * Extremely high accuracy
 * Emulates [PCM_12 and PCM_34 registers](https://github.com/LIJI32/GBVisualizer)
 * T-cycle accurate emulation of LCD timing effects, supporting the Demotronic trick, Prehistorik Man, [GBVideoPlayer](https://github.com/LIJI32/GBVideoPlayer) and other tech demos
 * Real time clock emulation
 * Retina/High DPI display support, allowing a wider range of scaling factors without artifacts
 * Optional frame blending (Requires OpenGL 3.2 or later)
 * Several [scaling algorithms](https://sameboy.github.io/scaling/) (Including exclusive algorithms like OmniScale and Anti-aliased Scale2x; Requires OpenGL 3.2 or later or Metal)

Features currently supported only with the Cocoa version:
 * Native Cocoa interface, with support for all system-wide features, such as drag-and-drop and smart titlebars
 * Game Boy Camera support

[Read more](https://sameboy.github.io/features/).

## Compatibility
SameBoy passes all of [blargg's test ROMs](http://gbdev.gg8.se/wiki/articles/Test_ROMs#Blargg.27s_tests), all of [mooneye-gb's](https://github.com/Gekkio/mooneye-gb) tests (Some tests require the original boot ROMs), and all of [Wilbert Pol's tests](https://github.com/wilbertpol/mooneye-gb/tree/master/tests/acceptance). SameBoy should work with most games and demos, please [report](https://github.com/LIJI32/SameBoy/issues/new) any broken ROM. The latest results for SameBoy's automatic tester are available [here](https://sameboy.github.io/automation/).

## Contributing
SameBoy is an open-source project licensed under the MIT license, and you're welcome to contribute by creating issues, implementing new features, improving emulation accuracy and fixing existing open issues. You can read the [contribution guidelines](CONTRIBUTING.md) to make sure your contributions are as effective as possible.

## Compilation
SameBoy requires the following tools and libraries to build:
 * clang (Recommended; required for macOS) or GCC
 * make
 * macOS Cocoa port: macOS SDK and Xcode (For command line tools and ibtool)
 * SDL port: libsdl2
 * [rgbds](https://github.com/gbdev/rgbds/releases/), for boot ROM compilation

On Windows, SameBoy also requires:
 * Visual Studio (For headers, etc.)
 * [GnuWin](http://gnuwin32.sourceforge.net/)
 * Running vcvars32 before running make. Make sure all required tools and libraries are in %PATH% and %lib%, respectively. (see [Build FAQ](https://github.com/LIJI32/SameBoy/blob/master/build-faq.md) for more details on Windows compilation)

To compile, simply run `make`. The targets are `cocoa` (Default for macOS), `sdl` (Default for everything else), `libretro`, `bootroms` and `tester`. You may also specify `CONF=debug` (default), `CONF=release`, `CONF=native_release` or `CONF=fat_release`  to control optimization, symbols and multi-architectures. `native_release` is faster than `release`, but is optimized to the host's CPU and therefore is not portable. `fat_release` is exclusive to macOS and builds x86-64 and ARM64 fat binaries; this requires using a recent enough `clang` and macOS SDK using `xcode-select`, or setting them explicitly with `CC=` and `SYSROOT=`, respectively. All other configurations will build to your host architecture. You may set `BOOTROMS_DIR=...` to a directory containing precompiled boot ROM files, otherwise the build system will compile and use SameBoy's own boot ROMs.

The SDL port will look for resource files with a path relative to executable and inside the directory specified by the `DATA_DIR` variable. If you are packaging SameBoy, you may wish to override this by setting the `DATA_DIR` variable during compilation to the target path of the directory containing all files (apart from the executable, that's not necessary) from the `build/bin/SDL` directory in the source tree. Make sure the variable ends with a `/` character. On FreeDesktop environments, `DATA_DIR` will default to `/usr/local/share/sameboy/`. `PREFIX` and `DESTDIR` follow their standard usage and default to an empty string an `/usr/local`, respectively

Linux, BSD, and other FreeDesktop users can run `sudo make install` to install SameBoy as both a GUI app and a command line tool.

SameBoy is compiled and tested on macOS, Ubuntu and 64-bit Windows 10.


text:
package com.apurv.repository;

import java.util.List;

import com.apurv.entity.Average;
import com.apurv.entity.Comment;
import com.apurv.entity.Login;
//import com.apurv.entity.Employee;
import com.apurv.entity.Movie;
import com.apurv.entity.Rate;

public interface EmployeeRepository {
	public List<Movie> empAll();
	   public Movie getOne(String id);
	   public String addOne(Movie movie) throws Exception;
	   public String addLogin(Login login) throws Exception;
	   public String addRate(Rate rate) throws Exception;
	   public String addComment(Comment comment) throws Exception;
	   public List<Login> getLogin(String login) ;
	   public String updateMovie(String movieId,Movie movie) throws Exception;
	   public List<Average> getAverage(List<String> titles) ;
	   public String deleteMovie(String id) ;
	   public List<Comment> getAllComments(String title) ;

}


text:
#ifndef   _ZCDB_LAYOUT_MANAGER_REACTOR_H
#define   _ZCDB_LAYOUT_MANAGER_REACTOR_H

#include "zrxobject.h"
#include "zdbid.h"
#include "zAdAChar.h"
#pragma pack (push, 8)

class ZcDbLayoutManagerReactor : public ZcRxObject
{
public:
    ZCRX_DECLARE_MEMBERS(ZcDbLayoutManagerReactor);

    virtual void layoutCreated(const ZTCHAR * newLayoutName,
                               const ZcDbObjectId& layoutId);
    virtual void layoutToBeRemoved(const ZTCHAR * layoutName,
                                   const ZcDbObjectId& layoutId);
    virtual void layoutRemoved(const ZTCHAR * layoutName,
                               const ZcDbObjectId& layoutId);
    virtual void abortLayoutRemoved(const ZTCHAR * layoutName,
                                    const ZcDbObjectId& layoutId);
    virtual void layoutToBeCopied(const ZTCHAR * layoutName,
                                  const ZcDbObjectId& oldLayoutId);
    virtual void layoutCopied(const ZTCHAR * oldLayoutName,
                              const ZcDbObjectId& oldLayoutId,
                              const ZTCHAR * newLayoutname,
                              const ZcDbObjectId& newLayoutId);
    virtual void abortLayoutCopied(const ZTCHAR * layoutName,
                                   const ZcDbObjectId& layoutId);
    virtual void layoutToBeRenamed(const ZTCHAR * oldName,
                                   const ZTCHAR * newName,
                                   const ZcDbObjectId& layoutId);
    virtual void layoutRenamed(const ZTCHAR * oldName,
                               const ZTCHAR * newName,
                               const ZcDbObjectId& layoutId);
    virtual void abortLayoutRename(const ZTCHAR * oldName,
                                   const ZTCHAR * newName,
                                   const ZcDbObjectId& layoutId);
    virtual void layoutSwitched(const ZTCHAR * newLayoutname,
                                const ZcDbObjectId& newLayoutId);
    virtual void plotStyleTableChanged(const ZTCHAR * newTableName,
                                       const ZcDbObjectId& layoutId);
    virtual void layoutsReordered();

};

#pragma pack (pop)
#endif


text:
local pathToThisFile = ...
local folderContainingThisFile = pathToThisFile:match(".+/") or ""
require (folderContainingThisFile..'vec3')

BlockEvent = {

new = function(self, typein, xin, yin, zin, facein, entityIdin)

    if type(typein) == 'table' and xin == nil and yin == nil and zin == nil and facein ==nil and entityId == nil  then
        entityIdin = typein[6]
        facein = typein[5]
        zin = typein[4]
        yin = typein[3]
        xin = typein[2]
        typein = typein[1]
    elseif type(xin) == 'table' and yin == nil and zin == nil and facein ==nil and entityId == nil  then
        entityIdin = xin[5]
        facein = xin[4]
        zin = xin[3]
        yin = xin[2]
        xin = xin[1]
    end
    local posnIn = Vec3:new(xin, yin, zin)
    local obj = {type=typein, face=facein, entityId=entityIdin, posn=posnIn }
    setmetatable(obj, self)
    self.__index=self
    return obj
end,

toString = function(self)
    local sTypeHash = {[0] = "BlockEvent.HIT"}
    key = self.type
    local typeText = sTypeHash[key] or "???"
    output = "BlockEvent("..typeText..", "..self.posn.x..", "..self.posn.y..", "..self.posn.z..", "..self.face..", "..self.entityId..")"
    return output
end,

Hit = function(self, x, y, z, face, entityId)
    return BlockEvent:new(0, x, y, z, face, entityId)
end,

}


text:
namespace muduo
{

namespace net
{

class EventLoop;
class EventLoopThread;

class EventLoopThreadPool : boost::noncopyable
{
 public:
  typedef boost::function<void(EventLoop*)> ThreadInitCallback;

  EventLoopThreadPool(EventLoop* baseLoop, const string& nameArg);
  ~EventLoopThreadPool();
  void setThreadNum(int numThreads) { numThreads_ = numThreads; }
  void start(const ThreadInitCallback& cb = ThreadInitCallback());

  // valid after calling start()
  /// round-robin
  EventLoop* getNextLoop();

  /// with the same hash code, it will always return the same EventLoop
  EventLoop* getLoopForHash(size_t hashCode);

  std::vector<EventLoop*> getAllLoops();

  bool started() const
  { return started_; }

  const string& name() const
  { return name_; }

 private:

  EventLoop* baseLoop_;
  string name_;
  bool started_;
  int numThreads_;
  int next_;
  boost::ptr_vector<EventLoopThread> threads_;
  std::vector<EventLoop*> loops_;
};

}
}

#endif  // MUDUO_NET_EVENTLOOPTHREADPOOL_H


text:
<thymeleaf xmlns:th="http://www.thymeleaf.org"
           xmlns:sec="http://www.thymeleaf.org/extras/spring-security"
           th:remove="tag">

        <title th:replace="${title}">TITLE</title>
        <meta name="_csrf" th:content="${_csrf.token}"/>
        <meta name="_csrf_header" th:content="${_csrf.headerName}"/>
        <link rel="stylesheet" th:href="@{/components/dataTables/css/dataTables.bootstrap.min.css}"/>

</thymeleaf>


text:
var colorConverter = {};

colorConverter.hexToRGB = function(hexStr, divInt) {
	R = parseInt((colorConverter.trimHex(hexStr)).substring(0,2),16)
	G = parseInt((colorConverter.trimHex(hexStr)).substring(2,4),16);
	B = parseInt((colorConverter.trimHex(hexStr)).substring(4,6),16);

	if(!divInt) {
		divInt = 1;
	}
	return [R/divInt,G/divInt,B/divInt];
}

colorConverter.trimHex = function(h) {
	return (h.charAt(0)=="#") ? h.substring(1,7):h
}


text:
package org.usfirst.frc4531.DatBot4531.commands;

import org.usfirst.frc4531.DatBot4531.Robot;
import org.usfirst.frc4531.DatBot4531.subsystems.armSubsystem;

import edu.wpi.first.wpilibj.command.Command;

/**
 *
 */
public class allArmsUp extends Command {

    public allArmsUp() {
    	requires(Robot.armSubsystem);
        // Use requires() here to declare subsystem dependencies
        // eg. requires(chassis);
    }

    // Called just before this Command runs the first time
    protected void initialize() {
    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
    	armSubsystem.armFourDownwards.set(false);
    	armSubsystem.armThreeDownwards.set(false);
    	armSubsystem.armTwoDownwards.set(false);
    	armSubsystem.armOneDownwards.set(false);
    	armSubsystem.armFourUpwards.set(true);
    	armSubsystem.armThreeUpwards.set(true);
    	armSubsystem.armTwoUpwards.set(true);
    	armSubsystem.armOneUpwards.set(true);
    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
        return false;
    }

    // Called once after isFinished returns true
    protected void end() {
    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
    }
}


text:
import { Component, AfterViewInit, ChangeDetectorRef } from '@angular/core';

import { ToolsNameService } from '../../tools-name.service';
import { ToolsList } from '../../tools.list';

import { Subscription } from 'rxjs';

@Component({
  selector: 'extract-3d',
  templateUrl: './app/menu/tools/threed-extract/threed-extract.component.html',
  styles: [`
		:host button {
	    margin: 10px;
	    padding: 6px 10px 6px 10px;
	    background-color: #e9e9e9;
	    border: 1px solid #53565d;
	    border-radius: 2px;
			font-size: 14px;
		}
		.svg-measure {
			font-size: 16px;
	    top: 2px;
		}
	`]
})

export class ThreeDExtractComponent implements AfterViewInit {
  private toolActive = false;
  s: Subscription;

  constructor(private cdr: ChangeDetectorRef, private toolsNameService: ToolsNameService) {}

  toggleExtract() {
    this.toolActive = !this.toolActive;
    if (this.toolActive) {
      // reatatch chnage detaction when we open tool
      this.cdr.reattach();

			// set tool name Obs
			this.toolsNameService.setCurentToolName(ToolsList.extract);

      this.s = this.toolsNameService.currentToolName
        .subscribe((name) => {
          if (ToolsList.extract !== name) { this.closeMeasure() };
        });
    } else {
      this.closeMeasure();
    }

  }

  closeMeasure() {
    this.toolActive = false;
		if (this.s) {
			this.s.unsubscribe();
		}

    //  detach changes detection
    // and last time detect changes when closing tool
    this.cdr.detach();
    this.cdr.detectChanges();
  }

	ngAfterViewInit() {
		this.cdr.detach();
	}

}


text:
class QueuedPostSerializer < ApplicationSerializer

  attributes :id,
             :queue,
             :user_id,
             :state,
             :topic_id,
             :approved_by_id,
             :rejected_by_id,
             :raw,
             :post_options,
             :created_at,
             :category_id,
             :can_delete_user

  has_one :user, serializer: AdminUserListSerializer
  has_one :topic, serializer: BasicTopicSerializer

  def category_id
    cat_id = object.topic.try(:category_id) || object.post_options['category']
    cat_id.to_i if cat_id
  end

  def include_category_id?
    category_id.present?
  end

  def can_delete_user
    true
  end

  def include_can_delete_user?
    user && user.trust_level == TrustLevel[0]
  end

end


text:
package org.littleshoot.proxy;

import io.netty.handler.codec.http.*;
import org.littleshoot.proxy.extras.SelfSignedMitmManager;

import java.nio.charset.Charset;
import java.util.HashSet;
import java.util.Queue;
import java.util.Set;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

/**
 * Tests just a single basic proxy running as a man in the middle.
 */
public class MitmProxyTest extends BaseProxyTest {
    private Set<HttpMethod> requestPreMethodsSeen = new HashSet<HttpMethod>();
    private Set<HttpMethod> requestPostMethodsSeen = new HashSet<HttpMethod>();
    private StringBuilder responsePreBody = new StringBuilder();
    private StringBuilder responsePostBody = new StringBuilder();
    private Set<HttpMethod> responsePreOriginalRequestMethodsSeen = new HashSet<HttpMethod>();
    private Set<HttpMethod> responsePostOriginalRequestMethodsSeen = new HashSet<HttpMethod>();

    @Override
    protected void setUp() {
        this.proxyServer = bootstrapProxy()
                .withPort(proxyServerPort)
                // Include a ChainedProxyManager to make sure that MITM setting
                // overrides this
                .withChainProxyManager(new ChainedProxyManager() {
                    @Override
                    public void lookupChainedProxies(HttpRequest httpRequest,
                            Queue<ChainedProxy> chainedProxies) {
                    }
                })
                .withManInTheMiddle(new SelfSignedMitmManager())
                .withFiltersSource(new HttpFiltersSourceAdapter() {
                    @Override
                    public HttpFilters filterRequest(HttpRequest originalRequest) {
                        return new HttpFiltersAdapter(originalRequest) {
                            @Override
                            public HttpResponse clientToProxyRequest(
                                    HttpObject httpObject) {
                                if (httpObject instanceof HttpRequest) {
                                    requestPreMethodsSeen
                                            .add(((HttpRequest) httpObject)
                                                    .getMethod());
                                }
                                return null;
                            }

                            @Override
                            public HttpResponse proxyToServerRequest(
                                    HttpObject httpObject) {
                                if (httpObject instanceof HttpRequest) {
                                    requestPostMethodsSeen
                                            .add(((HttpRequest) httpObject)
                                                    .getMethod());
                                }
                                return null;
                            }

                            @Override
                            public HttpObject serverToProxyResponse(
                                    HttpObject httpObject) {
                                if (httpObject instanceof HttpResponse) {
                                    responsePreOriginalRequestMethodsSeen
                                            .add(originalRequest.getMethod());
                                } else if (httpObject instanceof HttpContent) {
                                    responsePreBody.append(((HttpContent) httpObject)
                                            .content().toString(
                                                    Charset.forName("UTF-8")));
                                }
                                return httpObject;
                            }

                            @Override
                            public HttpObject proxyToClientResponse(
                                    HttpObject httpObject) {
                                if (httpObject instanceof HttpResponse) {
                                    responsePostOriginalRequestMethodsSeen
                                            .add(originalRequest.getMethod());
                                } else if (httpObject instanceof HttpContent) {
                                    responsePostBody.append(((HttpContent) httpObject)
                                            .content().toString(
                                                    Charset.forName("UTF-8")));
                                }
                                return httpObject;
                            }
                        };
                    }
                })
                .start();
    }

    @Override
    protected boolean isMITM() {
        return true;
    }

    @Override
    public void testSimpleGetRequest() throws Exception {
        super.testSimpleGetRequest();
        assertMethodSeenInRequestFilters(HttpMethod.GET);
        assertMethodSeenInResponseFilters(HttpMethod.GET);
        assertResponseFromFiltersMatchesActualResponse();
    }

    @Override
    public void testSimpleGetRequestOverHTTPS() throws Exception {
        super.testSimpleGetRequestOverHTTPS();
        assertMethodSeenInRequestFilters(HttpMethod.CONNECT);
        assertMethodSeenInRequestFilters(HttpMethod.GET);
        assertMethodSeenInResponseFilters(HttpMethod.GET);
        assertResponseFromFiltersMatchesActualResponse();
    }

    @Override
    public void testSimplePostRequest() throws Exception {
        super.testSimplePostRequest();
        assertMethodSeenInRequestFilters(HttpMethod.POST);
        assertMethodSeenInResponseFilters(HttpMethod.POST);
        assertResponseFromFiltersMatchesActualResponse();
    }

    @Override
    public void testSimplePostRequestOverHTTPS() throws Exception {
        super.testSimplePostRequestOverHTTPS();
        assertMethodSeenInRequestFilters(HttpMethod.CONNECT);
        assertMethodSeenInRequestFilters(HttpMethod.POST);
        assertMethodSeenInResponseFilters(HttpMethod.POST);
        assertResponseFromFiltersMatchesActualResponse();
    }

    private void assertMethodSeenInRequestFilters(HttpMethod method) {
        assertTrue(method
                + " should have been seen in clientToProxyRequest filter",
                requestPreMethodsSeen.contains(method));
        assertTrue(method
                + " should have been seen in proxyToServerRequest filter",
                requestPostMethodsSeen.contains(method));
    }

    private void assertMethodSeenInResponseFilters(HttpMethod method) {
        assertTrue(
                method
                        + " should have been seen as the original requests's method in serverToProxyResponse filter",
                responsePreOriginalRequestMethodsSeen.contains(method));
        assertTrue(
                method
                        + " should have been seen as the original requests's method in proxyToClientResponse filter",
                responsePostOriginalRequestMethodsSeen.contains(method));
    }

    private void assertResponseFromFiltersMatchesActualResponse() {
        assertEquals(
                "Data received through HttpFilters.serverToProxyResponse should match response",
                lastResponse, responsePreBody.toString());
        assertEquals(
                "Data received through HttpFilters.proxyToClientResponse should match response",
                lastResponse, responsePostBody.toString());
    }

}


text:
import { Observable } from 'rxjs';
import {
    MultiConditionBehavior,
    ConditionType
} from './multi-condition';
import {
    Behavior,
    FormElement
} from '../common';

/**
 * Класс поведения, отвечающий за маппинг
 * валидации.
 */
@Behavior([
  'showWhenOr',
  'hideWhenOr',
  'showWhenAnd',
  'hideWhenAnd'
])
export class ShowHideBehavior extends MultiConditionBehavior {

  /**
   * Типы условий, которые ассоциированы с различными алиасами.
   * @type {Object}
   * @private
   */
    protected _conditionTypes = {
        showWhenOr: ConditionType.Or,
        hideWhenOr: ConditionType.Or,
        showWhenAnd: ConditionType.And,
        hideWhenAnd: ConditionType.And
    };

    /**
     * Определение типа условий: OR или AND.
     */
    protected get conditionType(): ConditionType{
        return this._conditionTypes[this.alias];
    }

    /**
     * Текущее состояние.
     * @type {boolean}
     * @private
     */
    private _isShowed: boolean = true;

    /**
     * Действие, которое выполняется при
     * положительном результате.
     */
    public doIf(): Observable<any> {

        let show = ((this.alias === 'showWhenOr') ||
                    (this.alias === 'showWhenAnd'));

        // todo придумать связку с Animations
        if (show !== this._isShowed) {
            this.element.setActiveStatus('show-hide', show);
        }

        this._isShowed = show;
        return Observable.of(this._isShowed);
    }

    /**
     * Действие, которое выполняется при
     * отрицательном результате.
     */
    public doElse(): Observable<any> {

        let hide = ((this.alias === 'showWhenOr') ||
                    (this.alias === 'showWhenAnd'));

        // todo придумать связку с Animations
        if (hide !== !this._isShowed) {
            this.element.setActiveStatus('show-hide', !hide);
        }

        this._isShowed = !hide;
        return Observable.of(this._isShowed);
    }
}


text:
package com.buterfleoge.whale.service.alipay.protocol;

/**
 * @author xiezhenzong
 *
 */
public class AlipayCreateReturnRequest extends AlipayCallbackRequest {

    public static final String SUCCESS_TAG = "T";

    /**
     * 接口调用是否成功
     */
    private String is_success;

    private String exterface;

    /**
     * @return the is_success
     */
    public String getIs_success() {
        return is_success;
    }

    /**
     * @param is_success
     *            the is_success to set
     */
    public void setIs_success(String is_success) {
        this.is_success = is_success;
    }

    /**
     * @return the exterface
     */
    public String getExterface() {
        return exterface;
    }

    /**
     * @param exterface
     *            the exterface to set
     */
    public void setExterface(String exterface) {
        this.exterface = exterface;
    }

}