text:
package org.gradle.process.internal.worker.request;

import org.gradle.internal.serialize.DefaultSerializer;
import org.gradle.internal.serialize.DefaultSerializerRegistry;
import org.gradle.internal.serialize.SerializerRegistry;

public class RequestSerializerRegistry {
    public static SerializerRegistry create(ClassLoader classLoader, RequestArgumentSerializers argumentSerializers) {
        SerializerRegistry registry = new DefaultSerializerRegistry(false);
        registry.register(Request.class, new RequestSerializer(argumentSerializers.getSerializer(classLoader), false));
        return registry;
    }

    public static SerializerRegistry createDiscardRequestArg() {
        SerializerRegistry registry = new DefaultSerializerRegistry(false);
        registry.register(Request.class, new RequestSerializer(new DefaultSerializer<>(), true));
        return registry;
    }
}


text:
layout: post
title: Useful Comment Notification Emails for Drupal Site Admins
author: Jeff Geerling
nid: 331
comments: true
redirect_from: /blog/oscatholic/useful-comment-notificat/
created: 1285308732
---

I have, for some time, used the amazingly dexterous Rules module on my Drupal sites to receive email notifications when new comments were posted. I set up a Rule in the admin interface which would send an email if a new comment was saved on the site.

In the 'Message' section of the Rule's 'send email to arbitrary address' action, I would include a link to the commented-upon node, as well as the body of the comment text.

However, I wanted to also have a couple convenient links included: one link to allow me to quickly delete the comment (if the comment was spammy), and a link to edit the comment (sometimes I need to see the email address of the author, or change some wording if it's mildly inappropriate).

Luckily, Rules is well-acquainted with the similarly amazing Token module, so all I had to do was enter the following in the 'Message' (replacing what I had):

There's a new comment on the post [node:title-raw].
--------------------------------------------------------------------------------
By: "[comment_author:user-raw]"
"[comment:comment-body-raw]"
--------------------------------------------------------------------------------
Commented-upon node: http://www.lifeisaprayer.com/node/[node:nid]

Comment Administration:
Delete this comment: http://www.lifeisaprayer.com/comment/delete/[comment:comment-cid]
Edit this comment: http://www.lifeisaprayer.com/comment/edit/[comment:comment-cid]

Simple, but brilliant. Rules could be described that way.

Note: Check out this drupal.org page for more advanced comment notification options.

redpajama_set_name: RedPajamaGithub


text:
using Lucene.Net.Util;
using Lucene.Net.Util.Fst;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using JCG = J2N.Collections.Generic;

namespace Lucene.Net.Analysis.CharFilters
{

    // TODO: save/load?

    ///
    /// Holds a map of <see cref="string"/> input to <see cref="string"/> output, to be used
    /// with <see cref="Builder"/>.  Use the <see cref="MappingCharFilter"/>
    /// to create this.
    ///
    public class NormalizeCharMap
    {
        internal readonly FST<CharsRef> map;
        internal readonly IDictionary<char?, FST.Arc<CharsRef>> cachedRootArcs = new Dictionary<char?, FST.Arc<CharsRef>>();

        // Use the builder to create:
        private NormalizeCharMap(FST<CharsRef> map)
        {
            this.map = map;
            if (map != null)
            {
                try
                {
                    // Pre-cache root arcs:
                    var scratchArc = new FST.Arc<CharsRef>();
                    FST.BytesReader fstReader = map.GetBytesReader();
                    map.GetFirstArc(scratchArc);
                    if (FST<CharsRef>.TargetHasArcs(scratchArc))
                    {
                        map.ReadFirstRealTargetArc(scratchArc.Target, scratchArc, fstReader);
                        while (true)
                        {
                            Debug.Assert(scratchArc.Label != FST.END_LABEL);
                            cachedRootArcs[Convert.ToChar((char)scratchArc.Label)] = (new FST.Arc<CharsRef>()).CopyFrom(scratchArc);
                            if (scratchArc.IsLast)
                            {
                                break;
                            }
                            map.ReadNextRealArc(scratchArc, fstReader);
                        }
                    }
                    //System.out.println("cached " + cachedRootArcs.size() + " root arcs");
                }
                catch (IOException ioe)
                {
                    // Bogus FST IOExceptions!!  (will never happen)
                    throw new Exception("Should never happen", ioe);
                }
            }
        }

        ///
        /// Builds an NormalizeCharMap.
        /// <para>
        /// Call add() until you have added all the mappings, then call build() to get a NormalizeCharMap
        /// @lucene.experimental
        /// </para>
        ///
        public class Builder
        {
            // LUCENENET specific - we need to use StringComparer.Ordinal for the
            // sort order to correctly match Lucene, otherwise FST.Builder will throw Debug.Assert failures
            private readonly IDictionary<string, string> pendingPairs = new JCG.SortedDictionary<string, string>(StringComparer.Ordinal);

            ///
            /// Records a replacement to be applied to the input
            ///  stream.  Whenever singleMatch occurs in
            ///  the input, it will be replaced with
            ///  replacement.
            ///
            /// <param name="match"> input String to be replaced </param>
            /// <param name="replacement"> output String </param>
            /// <exception cref="ArgumentException"> if
            /// match is the empty string, or was
            /// already previously added </exception>
            public virtual void Add(string match, string replacement)
            {
                if (match.Length == 0)
                {
                    throw new ArgumentException("cannot match the empty string");
                }
                if (pendingPairs.ContainsKey(match))
                {
                    throw new ArgumentException("match \"" + match + "\" was already added");
                }
                pendingPairs[match] = replacement;
            }

            ///
            /// Builds the <see cref="NormalizeCharMap"/>; call this once you
            /// are done calling <see cref="Add"/>.
            ///
            public virtual NormalizeCharMap Build()
            {
                FST<CharsRef> map;
                try
                {
                    Outputs<CharsRef> outputs = CharSequenceOutputs.Singleton;
                    Builder<CharsRef> builder = new Builder<CharsRef>(FST.INPUT_TYPE.BYTE2, outputs);
                    Int32sRef scratch = new Int32sRef();
                    foreach (var ent in pendingPairs)
                    {
                        builder.Add(Lucene.Net.Util.Fst.Util.ToUTF16(ent.Key, scratch), new CharsRef(ent.Value));
                    }
                    map = builder.Finish();
                    pendingPairs.Clear();
                }
                catch (IOException ioe)
                {
                    // Bogus FST IOExceptions!!  (will never happen)
                    throw new Exception("Should never happen", ioe);
                }

                return new NormalizeCharMap(map);
            }
        }
    }
}


text:
import errno
import itertools
import logging
import os
import smtplib
import socket
import StringIO
import sys
import tempfile
import time
import webob
import zlib
from email import MIMEText
from webob import exc as web_exc

from conary.lib import log as cny_log
from conary.lib import util
from conary.lib.formattrace import formatTrace
from conary.lib.http.request import URL
from conary.repository import errors
from conary.repository import netclient
from conary.repository import shimclient
from conary.repository import xmlshims
from conary.repository.netrepos import netserver
from conary.repository.netrepos import proxy
from conary.repository.netrepos.auth_tokens import AuthToken
from conary.web import repos_web
from conary.web import webauth

log = logging.getLogger('wsgi_hooks')

def makeApp(settings):
    """Paster entry point"""
    envOverrides = {}
    if 'conary_config' in settings:
        envOverrides['conary.netrepos.config_file'] = settings['conary_config']
    elif 'CONARY_SERVER_CONFIG' in os.environ:
        envOverrides['conary.netrepos.config_file'
                ] = os.environ['CONARY_SERVER_CONFIG']
    if 'mount_point' in settings:
        envOverrides['conary.netrepos.mount_point'] = settings['mount_point']
    app = ConaryRouter(envOverrides)
    return app

def paster_main(global_config, **settings):
    """Wrapper to enable "paster serve" """
    return makeApp(settings)

def application(environ, start_response):
    """Trivial app entry point"""
    return makeApp({})(environ, start_response)

class ConaryRouter(object):

    requestFactory = webob.Request
    responseFactory = webob.Response

    def __init__(self, envOverrides=()):
        self.envOverrides = envOverrides
        self.configCache = {}

    def __call__(self, environ, start_response):
        if not logging.root.handlers:
            cny_log.setupLogging(consoleLevel=logging.INFO,
                    consoleFormat='apache',
                    consoleStream=environ['wsgi.errors'])
        # gunicorn likes to umask(0) when daemonizing, so put back something
        # reasonable if that's the case.
        oldUmask = os.umask(022)
        if oldUmask != 0:
            os.umask(oldUmask)
        environ.update(self.envOverrides)
        request = self.requestFactory(environ)
        try:
            response = self.handleRequest(request, start_response)
            if callable(response):
                # Looks like a webob response
                return response(environ, start_response)
            else:
                # Looks like a vanilla WSGI iterable
                return response
        except:
            exc_info = sys.exc_info()
            return self.handleError(request, exc_info, start_response)

    def handleRequest(self, request, start_response):
        if 'conary.netrepos.config_file' in request.environ:
            cfgPath = request.environ['conary.netrepos.config_file']
        else:
            raise ConfigurationError("conary.netrepos.config_file must be "
                    "present in the WSGI environment")
        cfg = self.configCache.get(cfgPath)
        if cfg is None:
            cfg = netserver.ServerConfig()
            cfg.read(cfgPath)
        handler = ConaryHandler(cfg)
        try:
            return handler.handleRequest(request)
        except:
            exc_info = sys.exc_info()
            return self.handleError(request, exc_info, start_response, cfg)

    def handleError(self, request, exc_info, start_response, cfg=None):
        trace, tracePath = self._formatErrorLarge(request, exc_info)
        short = self._formatErrorSmall(request, exc_info)
        short += 'Extended traceback at ' + tracePath
        log.error(short)

        if cfg and cfg.bugsFromEmail and cfg.bugsToEmail:
            try:
                self._sendMail(cfg, exc_info, trace, request)
            except:
                log.exception("Failed to send traceback mail:")

        response = self.responseFactory(
                "
500 Internal Server Error
\n"
                "
An unexpected error occurred on the server. Consult the "
                "server error logs for details.",
            status='500 Internal Server Error',
            content_type='text/html')
        # webob doesn't support exc_info, unfortunately
        start_response(response.status, response.headerlist, exc_info)
        return [response.body]

    def _formatErrorLarge(self, request, exc_info):
        e_class, e_value, e_tb = exc_info
        timestamp = time.ctime(time.time())

        # Format large traceback to file
        fd, tbPath = tempfile.mkstemp('.txt', 'repos-error-')
        tb = os.fdopen(fd, 'w+')
        print >> tb, "Unhandled exception from Conary repository", request.host
        print >> tb, "Time of occurence:", timestamp
        print >> tb, "System hostname:", socket.gethostname()
        print >> tb, "See also:", tbPath
        print >> tb
        formatTrace(e_class, e_value, e_tb, stream=tb, withLocals=False)
        print >> tb
        print >> tb, "WSGI Environment:"
        for key, value in sorted(request.environ.items()):
            print >> tb, " %s = %r" % (key, value)
        print >> tb
        print >> tb, "Full trace:"
        try:
            formatTrace(e_class, e_value, e_tb, stream=tb, withLocals=True)
        except:
            print >> tb, "*** Traceback formatter crashed! ***"
            print >> tb, "Formatter crash follows:"
            new_exc = sys.exc_info()
            formatTrace(new_exc[0], new_exc[1], new_exc[2], stream=tb,
                    withLocals=False)
            print >> tb, "*** End formatter crash log ***"
        print >> tb
        print >> tb, "End of traceback report"
        tb.seek(0)
        contents = tb.read()
        tb.close()
        return contents, tbPath

    def _formatErrorSmall(self, request, exc_info):
        e_class, e_value, e_tb = exc_info
        tb = StringIO.StringIO()
        print >> tb, "Unhandled exception from Conary repository", request.host
        formatTrace(e_class, e_value, e_tb, stream=tb, withLocals=False)
        return tb.getvalue()

    def _sendMail(self, cfg, exc_info, trace, request):
        firstLine = '%s: %s' % (exc_info[0].__name__, str(exc_info[1]))
        firstLine = firstLine.splitlines()[0]
        crashVars = dict(
                hostname=socket.gethostname(),
                firstLine=firstLine,
                )
        msg = MIMEText.MIMEText(trace)
        msg['Subject'] = cfg.bugsEmailSubject % crashVars
        msg['From'] = fromEmail = '"%s" <%s>' % (cfg.bugsEmailName,
                cfg.bugsFromEmail)
        msg['To'] = toEmail = '<%s>' % (cfg.bugsToEmail,)

        smtp = smtplib.SMTP()
        smtp.connect()
        smtp.sendmail(fromEmail, [toEmail], msg.as_string())
        smtp.close()

class ConaryHandler(object):

    requestFilter = xmlshims.RequestArgs
    responseFactory = webob.Response

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

        self.request = None
        self.auth = None
        self.isSecure = None
        self.repositoryServer = None
        self.proxyServer = None
        self.restHandler = None
        self.contentsStore = None

    def _getEnvBool(self, key, default=None):
        value = self.request.environ.get(key)
        if value is None:
            if default is None:
                raise KeyError("Environment variable %r must be set" % (key,))
            else:
                return default
        if value.lower() in ('yes', 'y', 'true', 't', '1', 'on'):
            return True
        elif value.lower() in ('no', 'n', 'false', 'f', '0', 'off'):
            return False
        else:
            raise ValueError(
                    "Environment variable %r must be a boolean, not %r" % (key,
                        value))

    def _loadCfg(self):
        """Load configuration and construct repository objects."""
        cfg = self.cfg
        req = self.request
        if cfg.repositoryDB:
            if cfg.proxyContentsDir:
                raise ConfigurationError("Exactly one of repositoryDB or "
                        "proxyContentsDir must be set.")
            for name in ('contentsDir', 'serverName'):
                if not cfg[name]:
                    raise ConfigurationError("%s must be set." % name)
        else:
            if not cfg.proxyContentsDir:
                raise ConfigurationError("Exactly one of repositoryDB or "
                        "proxyContentsDir must be set.")

        if os.path.realpath(cfg.tmpDir) != cfg.tmpDir:
            raise ConfigurationError("tmpDir must not contain symbolic links.")

        self._useForwardedHeaders = self._getEnvBool(
                'use_forwarded_headers', True)
        if self._useForwardedHeaders:
            for key in ('x-forwarded-scheme', 'x-forwarded-proto'):
                if req.headers.get(key):
                    req.scheme = req.headers[key]
                    break
            for key in ('x-forwarded-host', 'x-forwarded-server'):
                if req.headers.get(key):
                    req.host = req.headers[key]
                    break
        self.isSecure = req.scheme == 'https'

        if req.environ.get('PYTHONPATH'):
            # Allow SetEnv to propagate, so that commit hooks can have the
            # proper environment
            os.environ['PYTHONPATH'] = req.environ['PYTHONPATH']

        for mountPoint in [
                req.environ.get('conary.netrepos.mount_point'),
                cfg.baseUri, 'conary']:
            if mountPoint is not None:
                break
        for elem in mountPoint.split('/'):
            if not elem:
                continue
            if self.request.path_info_pop() != elem:
                raise web_exc.HTTPNotFound(
                        "Path %s is not handled by this application."
                        % self.request.script_name)

        urlBase = req.application_url
        if cfg.proxyContentsDir:
            # Caching proxy (no repository)
            self.repositoryServer = None
            self.shimServer = None
            self.proxyServer = proxy.ProxyRepositoryServer(cfg, urlBase)
        else:
            # Full repository with optional changeset cache
            self.repositoryServer = netserver.NetworkRepositoryServer(cfg,
                    urlBase)
            self.shimServer = shimclient.NetworkRepositoryServer(cfg, urlBase,
                    db=self.repositoryServer.db)

        if self.repositoryServer:
            self.proxyServer = proxy.SimpleRepositoryFilter(cfg, urlBase,
                    self.repositoryServer)
            self.contentsStore = self.repositoryServer.repos.contentsStore

    def _loadAuth(self):
        """Extract authentication info from the request."""
        self.auth = AuthToken()
        self._loadAuthPassword()
        self._loadAuthEntitlement()
        self.setRemoteIp(self.auth, self.request, self._useForwardedHeaders)

    @staticmethod
    def setRemoteIp(authToken, request, useForwarded=False):
        remote_ip = request.remote_addr
        forward = request.headers.get('X-Forwarded-For')
        if forward:
            forward = forward.split(',')
            if useForwarded:
                remote_ip = forward[-1].strip()
                forward = forward[:-1]
            authToken.forwarded_for = []
            for addr in forward:
                addr = addr.strip()
                if addr.startswith('::ffff:'):
                    addr = addr[7:]
                authToken.forwarded_for.append(addr)
        if remote_ip.startswith('::ffff:'):
            remote_ip = remote_ip[7:]
        authToken.remote_ip = remote_ip

    def _loadAuthPassword(self):
        """Extract HTTP Basic Authorization from the request."""
        info = self.request.authorization
        if not info or len(info) != 2 or info[0] != 'Basic':
            return
        try:
            info = info[1].decode('base64')
        except:
            return
        if ':' in info:
            self.auth.user, self.auth.password = info.split(':', 1)

    def _loadAuthEntitlement(self):
        """Extract conary entitlements from the request headers."""
        info = self.request.headers.get('X-Conary-Entitlement')
        if not info:
            return
        self.auth.entitlements = webauth.parseEntitlement(info)

    def _makeError(self, status, *lines):
        log.error("%s: %s: %s", self.auth.remote_ip, str(status), lines[0])
        body = "ERROR: " + "\r\n".join(lines) + "\r\n"
        return self.responseFactory(
                body=body,
                status=status,
                content_type='text/plain',
                )

    def getLocalPort(self):
        env = self.request.environ
        if 'gunicorn.socket' in env:
            return env['gunicorn.socket'].getsockname()[1]
        else:
            return 0

    def handleRequest(self, request):
        try:
            return self._handleRequest(request)
        except web_exc.HTTPException, err:
            return err
        finally:
            # This closes the repository server immediately after the initial
            # request handling phase, meaning that 'generator' responses will
            # not have access to it. Currently the only generator is
            # _produceChangeset() which does not need a repository server.
            self.close()

    def _handleRequest(self, request):
        self.request = request
        self._loadCfg()
        self._loadAuth()

        self.proxyServer.log.reset()

        if (self.auth.user != 'anonymous'
                and not self.isSecure
                and self.cfg.forceSSL):
            return self._makeError('403 Secure Connection Required',
                    "Password authentication is not allowed over unsecured "
                    "connections")

        if self.repositoryServer:
            self.repositoryServer.reopen()

        if self.request.method == 'GET':
            # cmd is the last part of the path, ignoring all intermediate
            # elements. When proxying, the intermediate part could be anything
            # depending on where the real repository is mounted.
            # e.g. /conary or /repos/foo
            cmd = os.path.basename(self.request.path_info.rstrip('/'))
            path = self.request.path_info_peek()
            if cmd == 'changeset':
                return self.getChangeset()
            elif path == 'api':
                self.request.path_info_pop()
                return self.getApi()
            # Fall through to web handler
        elif self.request.method == 'POST':
            # Only check content-type because of proxying considerations; as
            # above, the full URL will vary.
            if self.request.content_type == 'text/xml':
                return self.postRpc()
            # Fall through to web handler
        elif self.request.method == 'PUT':
            return self.putChangeset()
        else:
            return self._makeError('501 Not Implemented',
                    "Unsupported method %s" % self.request.method,
                    "Supported methods: GET POST PUT")

        if not self.repositoryServer:
            return self._makeError('404 Not Found',
                    "This is a Conary proxy server, it has no web interface.")
        if not self.cfg.webEnabled:
            return self._makeError('404 Not Found',
                    "Web interface disabled by administrator.")
        web = repos_web.ReposWeb(self.cfg, self.shimServer, authToken=self.auth)
        return web._handleRequest(request)

    def postRpc(self):
        if self.request.content_type != 'text/xml':
            return self._makeError('400 Bad Request',
                    "Unrecognized Content-Type")
        stream = self.request.body_file
        encoding = self.request.headers.get('Content-Encoding', 'identity')
        if encoding == 'deflate':
            stream = util.decompressStream(stream)
            stream.seek(0)
        elif encoding != 'identity':
            return self._makeError('400 Bad Request',
                    "Unrecognized Content-Encoding")

        try:
            params, method = util.xmlrpcLoad(stream)
        except:
            return self._makeError('400 Bad Request',
                    "Malformed XMLRPC request")

        localAddr = '%s:%s' % (socket.gethostname(), self.getLocalPort())
        try:
            request = self.requestFilter.fromWire(params)
        except (TypeError, ValueError, IndexError):
            return self._makeError('400 Bad Request',
                    "Malformed XMLRPC arguments")

        rawUrl = self.request.url
        scheme = self.request.headers.get('X-Conary-Proxy-Target-Scheme')
        if scheme in ('http', 'https'):
            rawUrl = str(URL(rawUrl)._replace(scheme=scheme))

        # Execution phase -- locate and call the target method
        try:
            responseArgs, extraInfo = self.proxyServer.callWrapper(
                    protocol=None,
                    port=None,
                    methodname=method,
                    authToken=self.auth,
                    request=request,
                    remoteIp=self.auth.remote_ip,
                    rawUrl=rawUrl,
                    localAddr=localAddr,
                    protocolString=self.request.http_version,
                    headers=self.request.headers,
                    isSecure=self.isSecure)
        except errors.InsufficientPermission:
            return self._makeError('403 Forbidden', "Insufficient permission")

        rawResponse, headers = responseArgs.toWire(request.version)
        if extraInfo:
            headers['Via'] = proxy.formatViaHeader(localAddr,
                    self.request.http_version, prefix=extraInfo.getVia())
        response = self.responseFactory(headerlist=headers.items())
        response.content_type = 'text/xml'

        # Output phase -- serialize and write the response
        body = util.xmlrpcDump((rawResponse,), methodresponse=1)
        accept = self.request.accept_encoding
        if len(body) > 200 and 'deflate' in accept:
            response.content_encoding = 'deflate'
            response.body = zlib.compress(body, 5)
        else:
            response.body = body

        if (method == 'getChangeSet'
                and request.version >= 71
                and not responseArgs.isException
                and response.status_int == 200
                and responseArgs.result[0]
                and 'multipart/mixed' in list(self.request.accept)
                ):
            return self.inlineChangeset(response, responseArgs, headers)
        else:
            return response

    def getChangeset(self, filename=None):
        """GET a prepared changeset file."""
        path = self._changesetPath('-out', filename)
        if not path:
            return self._makeError('403 Forbidden',
                    "Illegal changeset request")
        try:
            producer = proxy.ChangesetProducer(path, self.contentsStore)
        except IOError as err:
            if err.args[0] == errno.ENOENT:
                return self._makeError('404 Not Found', "Changeset not found")
            raise
        return self.responseFactory(
                status='200 OK',
                app_iter=producer,
                content_type='application/x-conary-change-set',
                content_length=str(producer.getSize()),
                )

    def inlineChangeset(self, rpcResponse, responseArgs, headers):
        filename = responseArgs.result[0].split('?')[-1]
        csResponse = self.getChangeset(filename=filename)
        if csResponse.status_int != 200:
            return csResponse

        # Build a multipart MIME response from the two responses
        boundary = os.urandom(24).encode('hex')
        totalSize = 0
        iterables = []
        for response in [rpcResponse, csResponse]:
            leader = "--%s\r\n" % boundary
            for name in ['Content-Type', 'Content-Length', 'Content-Encoding']:
                if name in response.headers:
                    leader += "%s: %s\r\n" % (name, response.headers[name])
            leader += "\r\n"
            trailer = "\r\n"
            totalSize += len(leader) + response.content_length + len(trailer)
            iterables.extend([[leader], response.app_iter, [trailer]])
        final = "--%s--\r\n" % boundary
        totalSize += len(final)
        iterables.append([final])

        response = self.responseFactory(
                status='200 OK',
                headerlist=headers.items(),
                app_iter=itertools.chain.from_iterable(iterables),
                )
        response.content_type = 'multipart/mixed; boundary="%s"' % boundary
        response.content_length=str(totalSize)
        return response

    def putChangeset(self):
        """PUT method -- handle changeset uploads."""
        if not self.repositoryServer:
            # FIXME: this mechanism is unauthenticated and can probably be used
            # to PUT content to random things on the internet
            if 'content-length' in self.request.headers:
                size = int(self.request.headers['content-length'])
            else:
                size = None
            headers = [x for x in self.request.headers.items()
                    if x[0].lower() in (
                        'x-conary-servername',
                        'x-conary-entitlement',
                        )]
            result = netclient.httpPutFile(self.request.url,
                    self.request.body_file,
                    size,
                    headers=headers,
                    chunked=(size is None),
                    withResponse=True,
                    )
            return self.responseFactory(
                    status='%s %s' % (result.status, result.reason),
                    app_iter=self._produceProxy(result),
                    #headerlist=result.getheaders(),
                    )

        # Copy request body to the designated temporary file.
        stream = self.request.body_file
        out = self._openForPut()
        if out is None:
            # File already exists or is in an illegal location.
            return self._makeError('403 Forbidden', "Illegal changeset upload")

        util.copyfileobj(stream, out)
        out.close()

        return self.responseFactory(status='200 OK')

    @staticmethod
    def _produceProxy(response):
        while True:
            d = response.read(1024)
            if not d:
                break
            yield d
        response.close()

    def _changesetPath(self, suffix, filename=None):
        if not filename:
            filename = self.request.query_string
            if not filename or os.path.sep in filename:
                return None
        server = self.repositoryServer or self.proxyServer
        return os.path.join(server.tmpPath, filename + suffix)

    def _openForPut(self):
        path = self._changesetPath('-in')
        if path:
            try:
                st = os.stat(path)
            except OSError, err:
                if err.errno != errno.ENOENT:
                    return None
                raise
            if st.st_size == 0:
                return open(path, 'wb+')
        return None

    def getApi(self):
        if not self.repositoryServer:
            return self._makeError('404 Not Found',
                    "Standalone Conary proxies cannot forward API requests")
        try:
            from crest import webhooks
        except ImportError:
            return self._makeError('404 Not Found',
                    "Conary web API is not enabled on this repository")
        prefix = self.request.script_name
        restHandler = webhooks.WSGIHandler(prefix, self.repositoryServer,
                authToken=self.auth)
        return restHandler.handle(self.request, path=None)

    def close(self):
        # Make sure any pooler database connections are released.
        if self.repositoryServer:
            self.repositoryServer.close()
        self.request = None
        self.auth = None
        self.isSecure = None
        self.repositoryServer = None
        self.proxyServer = None
        self.restHandler = None
        # Leave the contentsStore around in case produceChangeset needs it

class ConfigurationError(RuntimeError):
    pass


text:
from __future__ import absolute_import
from dbf.base import DBF
from aleph.text import string_value
from aleph.ingest.tabular import TabularIngestor

# TODO, dbf: https://pypi.python.org/pypi/pyDBF/

class DBFIngestor(TabularIngestor):
    MIME_TYPES = []
    EXTENSIONS = ['dbf']
    BASE_SCORE = 7

    def generate_rows(self, db, columns):
        if db.numrec == 0:
            return
        text = []
        for i in xrange(0, db.numrec):
            for v in db.select(i).values():
                if isinstance(v, str):
                    text.append(v)

        for i in xrange(0, db.numrec):
            row = db.select(i)
            record = {}
            for k, value in row.items():
                name = columns.get(k)
                record[name] = string_value(value)
            if len(record):
                for name in columns.values():
                    record[name] = record.get(name, None)
                yield record

    def ingest(self, meta, local_path):
        with open(local_path, 'rb') as fh:
            db = DBF(fh)
            document = self.create_document(meta)
            tabular = self.create_tabular(0)
            columns = [tabular.add_column(h) for h in db.fields.keys()]
            if not len(columns):
                return
            columns = {c.label: c.name for c in columns}

            document.insert_records(0, self.generate_rows(db, columns))
            meta.tables = [tabular]
            document.meta = meta
            self.emit(document)


text:
"""Tests for tensor2tensor.data_generators.program_search."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import gzip
import os
import shutil
import tempfile

from builtins import bytes  # pylint: disable=redefined-builtin
from tensor2tensor.data_generators import problem
from tensor2tensor.data_generators import program_search

import tensorflow.compat.v1 as tf

class ProgramSearchAlgolispStub(program_search.ProgramSearchAlgolisp):
  """Stub of ProgramSearchAlgolisp that stubs out maybe_download_dataset.

  The maybe_download_dataset writes one predetermined example in a zip file
  self.n number of times and returns the file path.
  """

  EXAMPLE = ('{"funcs": [], "tests": [{"output": 0, "input": {"a": 5}}, '
             '{"output": 1, "input": {"a": 20}}, {"output": 2, "input": '
             '{"a": 28}}, {"output": 1, "input": {"a": 13}}, {"output": 1, '
             '"input": {"a": 27}}, {"output": 1, "input": {"a": 13}}, '
             '{"output": 1, "input": {"a": 20}}, {"output": 0, '
             '"input": {"a": 8}}, {"output": 0, "input": {"a": 8}}, '
             '{"output": 0, "input": {"a": 4}}], "short_tree": ["invoke1", '
             '["lambda1", ["if", ["==", ["len", ["digits", "arg1"]], "1"], "0",'
             ' ["+", "1", ["self", ["reduce", ["digits", "arg1"], "0", '
             '"+"]]]]], "a"], "tags": [], "text": ["given", "a", "number", "a",'
             ' ",", "find", "how", "many", "times", "you", "can", "replace", '
             '"a", "with", "sum", "of", "its", "digits", "before", "it", '
             '"becomes", "a", "single", "digit", "number"], "return_type": '
             '"int", "args": {"a": "int"}, "nodes": ["l1_recursive_digits"]}')

  EXAMPLE_INPUT = ('given a number a , find how many times you can replace a '
                   'with sum of its digits before it becomes a single digit '
                   'number')

  EXAMPLE_TARGET = ('[ invoke1 [ lambda1 [ if [ == [ len [ digits arg1 ] ] 1 ]'
                    ' 0 [ + 1 [ self [ reduce [ digits arg1 ] 0 + ] ] ] ] ] a '
                    ']')

  N = 10

  def maybe_download_dataset(self, tmp_dir, dataset_split):
    (_, data_file) = tempfile.mkstemp(
        suffix='.gz', prefix=str(dataset_split) + '-', dir=tmp_dir)

    with gzip.open(data_file, 'wb') as gz_file:
      content = '\n'.join([self.EXAMPLE] * self.N)
      gz_file.write(bytes(content, 'utf-8'))
    return data_file

class ProgramSearchAlgolispTest(tf.test.TestCase):

  @classmethod
  def setUpClass(cls):
    # Setup the temp directory tree.
    cls.tmp_dir = tf.test.get_temp_dir()
    shutil.rmtree(cls.tmp_dir)
    os.mkdir(cls.tmp_dir)

  @classmethod
  def tearDownClass(cls):
    # Cleanup the temp directory tree.
    shutil.rmtree(cls.tmp_dir)

  def testEndToEnd(self):
    # End-to-end test, the stub problem class creates a .gz file with nps_stub.N
    # example and we check if we're able to process it correctly.
    nps_stub = ProgramSearchAlgolispStub()
    num = 0
    for example in nps_stub.generate_samples(None, self.tmp_dir,
                                             problem.DatasetSplit.TRAIN):

      # Only one example in 'file', so this is OK.
      self.assertEqual(example['inputs'],
                       ProgramSearchAlgolispStub.EXAMPLE_INPUT)

      self.assertEqual(example['targets'],
                       ProgramSearchAlgolispStub.EXAMPLE_TARGET)

      num += 1

    # assert that we have as many examples as there are in the file.
    self.assertEqual(num, nps_stub.N)

if __name__ == '__main__':
  tf.test.main()


text:
<?php

namespace Google\AdsApi\AdWords\Testing\BatchJobs\v201806;

/**
 * A fake operation class for testing purpose.
 */
abstract class FakeOperation
{

    protected $operator;

    /**
     * @return string
     */
    public function getOperator()
    {
        return $this->operator;
    }

    /**
     * @param string $operator
     */
    public function setOperator($operator)
    {
        $this->operator = $operator;
    }
}


text:
package org.myrobotlab.service.data;

import java.io.Serializable;

/**
 * The value & id of a component. It is sent when the value changes.
 *
 */
public class JoystickData implements Serializable {
  private static final long serialVersionUID = 1L;
  public String id;
  public Float value;

  public JoystickData(String id, Float value) {
    this.id = id;
    this.value = value;
  }

  @Override
  public String toString() {
    return String.format("[%s] %f", id, value);
  }
}


text:
using System.Web.Mvc;

namespace Masb.Mvc.TableBuilder
{
    ///
    /// Represents the `item` object that is passed to inline helpers,
    /// when the inline helper renders model information to the page.
    /// <para>Example:</para>
    /// <para>(Func<ITemplateArgs<Person>, HelperResult>)@<div>@item.Html.EditorFor(p => p.Name)</div></para>
    ///
    /// <typeparam name="TModel">Type of the model to render.</typeparam>
    /// <typeparam name="TInfo">Type of additional data provided to the rendering process.</typeparam>
    public class TemplateArgs<TModel, TInfo> : TemplateArgs<TModel>,
        ITemplateArgsWithData<TModel, TInfo>
    {
        public TemplateArgs(ViewDataDictionary<TModel> viewData, ViewContext viewContext, TInfo info)
            : base(viewData, viewContext)
        {
            this.Info = info;
        }

        ///
        /// Gets the index of the row.
        ///
        public TInfo Info { get; private set; }
    }

    ///
    /// Represents the `item` object that is passed to inline helpers,
    /// when the inline helper renders model information to the page.
    /// <para>Example:</para>
    /// <para>(Func<ITemplateArgs<Person>, HelperResult>)@<div>@item.Html.EditorFor(p => p.Name)</div></para>
    ///
    /// <typeparam name="TModel">Type of the model to render.</typeparam>
    public class TemplateArgs<TModel> :
        ITemplateArgs<TModel>,
        IViewDataContainer
    {
        public TemplateArgs(ViewDataDictionary<TModel> viewData, ViewContext viewContext)
        {
            this.ViewData = viewData;
            this.Meta = viewData.ModelMetadata;
            this.Url = new UrlHelper(viewContext.RequestContext);
            this.Html = new HtmlHelper<TModel>(viewContext, this);
            this.Ajax = new AjaxHelper<TModel>(viewContext, this);
        }

        ///
        /// Gets the <see cref="ModelMetadata"/> associated with this object.
        ///
        public ModelMetadata Meta { get; private set; }

        ///
        /// Gets the <see cref="T:System.Web.Mvc.UrlHelper"/> of the rendered snippet.
        ///
        public UrlHelper Url { get; private set; }

        ///
        /// Gets the <see cref="T:System.Web.Mvc.AjaxHelper"/> object that is used to render HTML markup using Ajax.
        ///
        /// <returns>
        /// The <see cref="T:System.Web.Mvc.AjaxHelper"/> object that is used to render HTML markup using Ajax.
        /// </returns>
        public AjaxHelper<TModel> Ajax { get; private set; }

        ///
        /// Gets the <see cref="T:System.Web.Mvc.AjaxHelper"/> object that is used to render HTML markup using Ajax.
        ///
        /// <returns>
        /// The <see cref="T:System.Web.Mvc.AjaxHelper"/> object that is used to render HTML markup using Ajax.
        /// </returns>
        AjaxHelper IHelperContext.Ajax
        {
            get { return this.Ajax; }
        }

        ///
        /// Gets the <see cref="T:System.Web.Mvc.HtmlHelper"/> object that is used to render HTML elements.
        ///
        /// <returns>
        /// The <see cref="T:System.Web.Mvc.HtmlHelper"/> object that is used to render HTML elements.
        /// </returns>
        public HtmlHelper<TModel> Html { get; private set; }

        ///
        /// Gets the current model object or value.
        ///
        public TModel Model
        {
            get { return this.Html.ViewData.Model; }
        }

        ///
        /// Gets the <see cref="T:System.Web.Mvc.HtmlHelper"/> object that is used to render HTML elements.
        ///
        /// <returns>
        /// The <see cref="T:System.Web.Mvc.HtmlHelper"/> object that is used to render HTML elements.
        /// </returns>
        HtmlHelper IHelperContext.Html
        {
            get { return this.Html; }
        }

        ///
        /// Gets or sets the view data dictionary.
        ///
        /// <returns>
        /// The view data dictionary.
        /// </returns>
        public ViewDataDictionary ViewData { get; set; }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#448AFF</color>
    <color name="colorLightWhite">#fafafa</color>
</resources>


text:
package nsxtreceiver // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/nsxtreceiver"
import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"
	"net/url"

	"go.opentelemetry.io/collector/component"
	"go.uber.org/zap"

	dm "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/nsxtreceiver/internal/model"
)

var _ (Client) = &nsxClient{}

// Client is a way of interacting with the NSX REST API
type Client interface {
	TransportNodes(ctx context.Context) ([]dm.TransportNode, error)
	ClusterNodes(ctx context.Context) ([]dm.ClusterNode, error)
	NodeStatus(ctx context.Context, nodeID string, class nodeClass) (*dm.NodeStatus, error)
	Interfaces(ctx context.Context, nodeID string, class nodeClass) ([]dm.NetworkInterface, error)
	InterfaceStatus(ctx context.Context, nodeID, interfaceID string, class nodeClass) (*dm.NetworkInterfaceStats, error)
}

type nsxClient struct {
	config   *Config
	client   *http.Client
	endpoint *url.URL
	logger   *zap.Logger
}

var (
	errUnauthorized = errors.New("STATUS 403, unauthorized")
)

func newClient(c *Config, settings component.TelemetrySettings, host component.Host, logger *zap.Logger) (*nsxClient, error) {
	client, err := c.HTTPClientSettings.ToClient(host, settings)
	if err != nil {
		return nil, err
	}

	endpoint, err := url.Parse(c.Endpoint)
	if err != nil {
		return nil, err
	}

	return &nsxClient{
		config:   c,
		client:   client,
		endpoint: endpoint,
		logger:   logger,
	}, nil
}

func (c *nsxClient) TransportNodes(ctx context.Context) ([]dm.TransportNode, error) {
	body, err := c.doRequest(
		ctx,
		"/api/v1/transport-nodes",
	)
	if err != nil {
		return nil, err
	}
	var nodes dm.TransportNodeList
	err = json.Unmarshal(body, &nodes)
	return nodes.Results, err
}

func (c *nsxClient) ClusterNodes(ctx context.Context) ([]dm.ClusterNode, error) {
	body, err := c.doRequest(
		ctx,
		"/api/v1/cluster/nodes",
	)
	if err != nil {
		return nil, fmt.Errorf("unable to get cluster nodes: %w", err)
	}
	var nodes dm.ClusterNodeList
	err = json.Unmarshal(body, &nodes)

	return nodes.Results, err
}

func (c *nsxClient) NodeStatus(ctx context.Context, nodeID string, class nodeClass) (*dm.NodeStatus, error) {
	body, err := c.doRequest(
		ctx,
		c.nodeStatusEndpoint(class, nodeID),
	)
	if err != nil {
		return nil, fmt.Errorf("unable to get a node's status from the REST API: %w", err)
	}

	switch class {
	case transportClass:
		var nodeStatus dm.TransportNodeStatus
		err = json.Unmarshal(body, &nodeStatus)
		return &nodeStatus.NodeStatus, err
	default:
		var nodeStatus dm.NodeStatus
		err = json.Unmarshal(body, &nodeStatus)
		return &nodeStatus, err
	}

}

func (c *nsxClient) Interfaces(
	ctx context.Context,
	nodeID string,
	class nodeClass,
) ([]dm.NetworkInterface, error) {
	body, err := c.doRequest(
		ctx,
		c.interfacesEndpoint(class, nodeID),
	)
	if err != nil {
		return nil, err
	}
	var interfaces dm.NodeNetworkInterfacePropertiesListResult
	err = json.Unmarshal(body, &interfaces)

	return interfaces.Results, err
}

func (c *nsxClient) InterfaceStatus(
	ctx context.Context,
	nodeID, interfaceID string,
	class nodeClass,
) (*dm.NetworkInterfaceStats, error) {
	body, err := c.doRequest(
		ctx,
		c.interfaceStatusEndpoint(class, nodeID, interfaceID),
	)

	if err != nil {
		return nil, fmt.Errorf("unable to get interface stats: %w", err)
	}
	var interfaceStats dm.NetworkInterfaceStats
	err = json.Unmarshal(body, &interfaceStats)
	return &interfaceStats, err
}

func (c *nsxClient) doRequest(ctx context.Context, path string) ([]byte, error) {
	endpoint, err := c.endpoint.Parse(path)
	if err != nil {
		return nil, err
	}

	req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint.String(), nil)
	if err != nil {
		return nil, err
	}
	req.SetBasicAuth(c.config.Username, c.config.Password)
	h := req.Header
	h.Add("User-Agent", "opentelemetry-collector")
	h.Add("Accept", "application/json")
	h.Add("Connection", "keep-alive")

	resp, err := c.client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	if resp.StatusCode == http.StatusOK {
		return io.ReadAll(resp.Body)
	}

	body, _ := io.ReadAll(resp.Body)
	switch resp.StatusCode {
	case 403:
		return nil, errUnauthorized
	default:
		c.logger.Info(fmt.Sprintf("%v", req))
		return nil, fmt.Errorf("got non 200 status code %d: %w, %s", resp.StatusCode, err, string(body))
	}
}

func (c *nsxClient) nodeStatusEndpoint(class nodeClass, nodeID string) string {
	switch class {
	case transportClass:
		return fmt.Sprintf("/api/v1/transport-nodes/%s/status", nodeID)
	default:
		return fmt.Sprintf("/api/v1/cluster/nodes/%s/status", nodeID)
	}
}

func (c *nsxClient) interfacesEndpoint(class nodeClass, nodeID string) string {
	switch class {
	case transportClass:
		return fmt.Sprintf("/api/v1/transport-nodes/%s/network/interfaces", nodeID)
	default:
		return fmt.Sprintf("/api/v1/cluster/nodes/%s/network/interfaces", nodeID)
	}
}

func (c *nsxClient) interfaceStatusEndpoint(class nodeClass, nodeID, interfaceID string) string {
	switch class {
	case transportClass:
		return fmt.Sprintf("/api/v1/transport-nodes/%s/network/interfaces/%s/stats", nodeID, interfaceID)
	default:
		return fmt.Sprintf("/api/v1/cluster/nodes/%s/network/interfaces/%s/stats", nodeID, interfaceID)
	}
}


text:
package metrics_test

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/julienschmidt/httprouter"
	"github.com/ory/hydra/metrics"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"github.com/urfave/negroni"
	//"time"
	"math/rand"
	"time"

	"encoding/json"

	"github.com/ory/herodot"
	"github.com/ory/hydra/health"
	"github.com/sirupsen/logrus"
)

func TestMiddleware(t *testing.T) {
	rand.Seed(time.Now().Unix())
	mw := metrics.NewMetricsManager(logrus.StandardLogger())
	n := negroni.New()
	r := httprouter.New()

	time.Sleep(time.Second)

	n.Use(mw)
	r.GET("/", handle)
	r.GET("/oauth2/introspect", handle)
	r.POST("/", handle)
	n.UseHandler(r)

	s := httptest.NewServer(n)
	defer s.Close()

	for i := 1; i <= 100; i++ {
		t.Run(fmt.Sprintf("case=%d", i), func(t *testing.T) {
			res, err := http.Get(s.URL)
			require.NoError(t, err)
			res.Body.Close()

			mw.RLock()
			require.Equal(t, http.StatusOK, res.StatusCode)
			mw.RUnlock()
		})
	}

	i := 100
	assert.EqualValues(t, i, mw.Snapshot.Requests)
	assert.EqualValues(t, i, mw.Snapshot.Requests)
	assert.EqualValues(t, i, mw.Snapshot.Responses)

	mw.Snapshot.Update()
	assert.True(t, mw.Snapshot.UpTime > 0)
	assert.True(t, mw.Snapshot.GetUpTime() > 0)

	assert.EqualValues(t, 0, mw.Snapshot.Status[http.StatusOK].Requests)
	assert.EqualValues(t, i, mw.Snapshot.Status[http.StatusOK].Responses)

	assert.EqualValues(t, i, mw.Snapshot.Methods["GET"].Requests)
	assert.EqualValues(t, i, mw.Snapshot.Methods["GET"].Responses)

	res, err := http.Get(s.URL + "/oauth2/introspect/1231")
	require.NoError(t, err)
	res.Body.Close()

	assert.EqualValues(t, 1, mw.Snapshot.Path("/oauth2/introspect").Requests)

	mw.Lock()
	mw.Update()
	assert.NotEqual(t, 0, mw.UpTime)
	mw.Unlock()

	out, _ := json.MarshalIndent(mw, "\t", "  ")
	t.Logf("%s", out)
}

func TestRacyMiddleware(t *testing.T) {
	rand.Seed(time.Now().Unix())
	mw := metrics.NewMetricsManager(logrus.StandardLogger())
	n := negroni.New()
	r := httprouter.New()

	h := health.Handler{
		H:       herodot.NewJSONWriter(nil),
		Metrics: mw,
	}

	n.Use(mw)
	h.SetRoutes(r)
	n.UseHandler(r)

	s := httptest.NewServer(n)
	defer s.Close()

	for i := 1; i <= 100; i++ {
		t.Run("type=concurrent", func(t *testing.T) {
			go func() {
				res, err := http.Get(s.URL + "/health")
				require.NoError(t, err)
				res.Body.Close()
			}()

		})
	}

	time.Sleep(time.Second)
}

func handle(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	time.Sleep(time.Duration(random(0, 10)) * time.Millisecond)
	w.WriteHeader(http.StatusOK)

	for i := 0; i <= random(1, 100); i++ {
		w.Write([]byte("ok"))
	}
}

func random(min, max int) int {
	return rand.Intn(max-min) + min
}


text:
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';

CREATE SCHEMA IF NOT EXISTS `ems` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ;
USE `ems` ;

-- -----------------------------------------------------
-- Table `ems`.`payments`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `ems`.`payments` (
  `id` INT NULL AUTO_INCREMENT,
  `name` VARCHAR(45) NULL,
  `acno_from` VARCHAR(45) NULL,
  `acno_to` VARCHAR(45) NULL,
  `address` VARCHAR(45) NULL,
  `phoneno` VARCHAR(45) NULL,
  `email` VARCHAR(45) NULL,
  PRIMARY KEY (`id`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `ems`.`clients`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `ems`.`clients` (
  `id` INT NULL AUTO_INCREMENT,
  `name` VARCHAR(45) NULL,
  `address` VARCHAR(50) NULL,
  `place` VARCHAR(45) NULL,
  `phoneno` VARCHAR(45) NULL,
  `bank_name` VARCHAR(45) NULL,
  `acno` VARCHAR(45) NULL,
  `amount` INT NULL,
  PRIMARY KEY (`id`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `ems`.`venues`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `ems`.`venues` (
  `id` INT NULL AUTO_INCREMENT,
  `name` VARCHAR(45) NULL,
  `description` VARCHAR(50) NULL,
  `type` VARCHAR(45) NULL,
  PRIMARY KEY (`id`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `ems`.`categories`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `ems`.`categories` (
  `id` INT NULL AUTO_INCREMENT,
  `name` VARCHAR(45) NULL,
  `description` VARCHAR(100) NULL,
  PRIMARY KEY (`id`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `ems`.`events`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `ems`.`events` (
  `id` INT NULL AUTO_INCREMENT,
  `name` VARCHAR(50) NULL,
  `description` VARCHAR(100) NULL,
  `start_time` TIME NULL,
  `start_date` DATE NULL,
  `end-time` TIME NULL,
  `end-date` DATE NULL,
  `noof_people` INT NULL,
  `payments_id` INT NOT NULL,
  `clients_id` INT NOT NULL,
  `venues_id` INT NOT NULL,
  `categories_id` INT NOT NULL,
  PRIMARY KEY (`id`, `payments_id`, `clients_id`, `venues_id`, `categories_id`),
  INDEX `fk_events_payments_idx` (`payments_id` ASC),
  INDEX `fk_events_clients1_idx` (`clients_id` ASC),
  INDEX `fk_events_venues1_idx` (`venues_id` ASC),
  INDEX `fk_events_categories1_idx` (`categories_id` ASC),
  CONSTRAINT `fk_events_payments`
    FOREIGN KEY (`payments_id`)
    REFERENCES `ems`.`payments` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_events_clients1`
    FOREIGN KEY (`clients_id`)
    REFERENCES `ems`.`clients` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_events_venues1`
    FOREIGN KEY (`venues_id`)
    REFERENCES `ems`.`venues` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_events_categories1`
    FOREIGN KEY (`categories_id`)
    REFERENCES `ems`.`categories` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `ems`.`users`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `ems`.`users` (
  `id` INT NULL AUTO_INCREMENT,
  `user_name` VARCHAR(45) NULL,
  `password` VARCHAR(45) NULL,
  `user_type` VARCHAR(45) NULL,
  PRIMARY KEY (`id`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `ems`.`food_items`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `ems`.`food_items` (
  `id` INT NULL AUTO_INCREMENT,
  `name` VARCHAR(45) NULL,
  `description` VARCHAR(100) NULL,
  PRIMARY KEY (`id`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `ems`.`foods`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `ems`.`foods` (
  `id` INT NULL AUTO_INCREMENT,
  `type` VARCHAR(45) NULL,
  `food_items_id` INT NOT NULL,
  PRIMARY KEY (`id`, `food_items_id`),
  INDEX `fk_foods_food_items1_idx` (`food_items_id` ASC),
  CONSTRAINT `fk_foods_food_items1`
    FOREIGN KEY (`food_items_id`)
    REFERENCES `ems`.`food_items` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `ems`.`vehicles`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `ems`.`vehicles` (
  `id` INT NULL AUTO_INCREMENT,
  `name` VARCHAR(45) NULL,
  `reg_no` VARCHAR(50) NULL,
  `seat` VARCHAR(45) NULL,
  `price` INT NULL,
  PRIMARY KEY (`id`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `ems`.`booking`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `ems`.`booking` (
  `id` INT NULL AUTO_INCREMENT,
  `name` VARCHAR(45) NULL,
  `events_id` INT NOT NULL,
  PRIMARY KEY (`id`, `events_id`),
  INDEX `fk_booking_events1_idx` (`events_id` ASC),
  CONSTRAINT `fk_booking_events1`
    FOREIGN KEY (`events_id`)
    REFERENCES `ems`.`events` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `ems`.`entertainments`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `ems`.`entertainments` (
  `id` INT NULL AUTO_INCREMENT,
  `name` VARCHAR(45) NULL,
  `type` VARCHAR(45) NULL,
  PRIMARY KEY (`id`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `ems`.`entertainment_type`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `ems`.`entertainment_type` (
  `id` INT NULL AUTO_INCREMENT,
  `name` VARCHAR(45) NULL,
  `events_id` INT NOT NULL,
  `entertainments_id` INT NOT NULL,
  PRIMARY KEY (`id`, `events_id`, `entertainments_id`),
  INDEX `fk_entertainment_type_events1_idx` (`events_id` ASC),
  INDEX `fk_entertainment_type_entertainments1_idx` (`entertainments_id` ASC),
  CONSTRAINT `fk_entertainment_type_events1`
    FOREIGN KEY (`events_id`)
    REFERENCES `ems`.`events` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_entertainment_type_entertainments1`
    FOREIGN KEY (`entertainments_id`)
    REFERENCES `ems`.`entertainments` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `ems`.`event_vehicles`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `ems`.`event_vehicles` (
  `id` INT NULL AUTO_INCREMENT,
  `noof_vehicle` INT NULL,
  `total_price` INT NULL,
  `vehicles_id` INT NOT NULL,
  PRIMARY KEY (`id`, `vehicles_id`),
  CONSTRAINT `fk_event_vehicles_vehicles1`
    FOREIGN KEY (`vehicles_id`)
    REFERENCES `ems`.`vehicles` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;


text:
potatonet-power
===============

Power Management and other code snippets for Potatonet.

More information at https://www.ibr.cs.tu-bs.de/projects/potatonet/index.html


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('base', '0004_auto_20150515_0927'),
    ]

    operations = [
        migrations.AddField(
            model_name='subpage',
            name='resource',
            field=models.ManyToManyField(to='base.Resource', blank=True),
        ),
        migrations.AlterField(
            model_name='translation',
            name='date',
            field=models.DateTimeField(auto_now_add=True),
        ),
    ]


text:
package eu.europeana.api.client;

import java.io.IOException;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class EuropeanaApi2Client extends EuropeanaConnection {

	public EuropeanaApi2Client(){
		super();
	}

	public EuropeanaApi2Client(String europeanaSearchUri, String apiKey){
		super(europeanaSearchUri, apiKey);
	}

	public EuropeanaApi2Results searchApi2(Api2Query query, int limit, int start) throws IOException {

		//String cadenaBusq = search.getSearchTerms();
		String url = query.getQueryUrl(this, limit, start);
        // Execute Europeana API request
        String json = getJSONResult(url);

        // Load results object from JSON
        Gson gson = new GsonBuilder().create();
        EuropeanaApi2Results res = gson.fromJson(json, EuropeanaApi2Results.class);

        return res;

	}

}


text:
namespace Caliburn4Fun.Demo.Views
{
    public partial class MainPage
    {
        public MainPage()
        {
            InitializeComponent();
        }
    }
}


text:
package org.deeplearning4j.nn.updater.custom;

import lombok.AllArgsConstructor;
import lombok.Data;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.learning.GradientUpdater;
import org.nd4j.linalg.learning.config.IUpdater;
import org.nd4j.linalg.schedule.ISchedule;

import java.util.Map;

/**
 * Created by Alex on 09/05/2017.
 */
@AllArgsConstructor
@Data
public class CustomIUpdater implements IUpdater {

    public static final double DEFAULT_SGD_LR = 1e-3;

    private double learningRate;

    public CustomIUpdater() {
        this(DEFAULT_SGD_LR);
    }

    @Override
    public long stateSize(long numParams) {
        return 0;
    }

    @Override
    public GradientUpdater instantiate(INDArray viewArray, boolean initializeViewArray) {
        if (viewArray != null) {
            throw new IllegalStateException("View arrays are not supported/required for SGD updater");
        }
        return new CustomGradientUpdater(this);
    }

    @Override
    public GradientUpdater instantiate(Map<String, INDArray> updaterState, boolean initializeStateArrays) {
        throw new UnsupportedOperationException();
    }

    @Override
    public CustomIUpdater clone() {
        return new CustomIUpdater(learningRate);
    }

    @Override
    public double getLearningRate(int iteration, int epoch) {
        return learningRate;
    }

    @Override
    public boolean hasLearningRate() {
        return true;
    }

    @Override
    public void setLrAndSchedule(double lr, ISchedule iSchedule) {
        this.learningRate = lr;
    }
}


text:
package com.opengamma.web.security;

import static com.opengamma.web.WebResourceTestUtils.assertJSONObjectEquals;

import java.util.List;

import org.json.JSONObject;
import org.testng.annotations.Test;

import com.opengamma.financial.security.FinancialSecurity;
import com.opengamma.financial.security.equity.EquitySecurity;
import com.opengamma.financial.security.future.BondFutureSecurity;
import com.opengamma.financial.security.test.SecurityTestCaseMethods;
import com.opengamma.util.test.TestGroup;

/**
 * Test {@link WebSecurityResource}.
 */
@Test(groups = TestGroup.UNIT)
public class WebSecurityResourceTest extends AbstractWebSecurityResourceTestCase implements SecurityTestCaseMethods {

  @Test
  @Override
  public void testEquitySecurity() throws Exception {
    assertGetSecurity(_securities.get(EquitySecurity.class));
  }

  @Test
  @Override
  public void testBondFutureSecurity() throws Exception {
    assertGetSecurity(_securities.get(BondFutureSecurity.class));
  }

  private void assertGetSecurity(final List<FinancialSecurity> securities) throws Exception {
    for (FinancialSecurity security : securities) {
      WebSecurityResource securityResource = _webSecuritiesResource.findSecurity(security.getUniqueId().toString());
      JSONObject actualJson = new JSONObject(securityResource.getJSON());

      JSONObject expectedJson = security.accept(new ExpectedSecurityJsonProvider());
      assertJSONObjectEquals(expectedJson, actualJson);
    }
  }

}


text:
[![Build Status](https://travis-ci.org/espebra/filebin.svg)](https://travis-ci.org/espebra/filebin)

**NOTE:** Active development has moved to [https://github.com/espebra/filebin2](https://github.com/espebra/filebin2). This repository is kept as an archive.

![Viewing a bin](doc/screenshot-web-interface-bin.png)

Filebin is a web application that facilitates convenient file sharing on the web. It was the software used at [https://filebin.net](https://filebin.net) earlier.

## Table of contents

* [Features](#features)
* [Requirements](#requirements)
* [Installation](#installation)
* [Configuration](#configuration)
* [Web interface](#web-interface)
* [Web service](#web-service)
* [Development](#development)
* [TODO](#todo)

## Features

* Responsive and mobile friendly [web interface](#web-interface).
* All functionality available through an [HTTP API](#web-service).
* Upload files using drag and drop, select files from a dialog box or use cURL ([examples below](#web-service))
* Large file support. 30 GB file upload has been tested, but it should work fine with larger files as well.
* Archive (tar and zip) download to make it easy to download multiple files in one go.
* Files expire automatically after a configurable period of time.
* Files and entire bins can be deleted manually.
* Thumbnails are displayed for image files.
* Album view is available in bins with images. Images are sorted based on the Exif DateTime timestamps.
* Triggers are capable of calling external scripts on certain events. One potential use case is to notify virus/malware scanners on file upload.
* No external dependencies once built.
* Cache invalidation support.

## Requirements

To build Filebin, a Golang build environment (Go version 1.13 or higher) and some Golang packages are needed. The build procedure will produce a statically linked binary that doesn't require any external dependencies to run. It even comes with its own web server bundled.

The build process requires quite a bit of memory to complete successfully. Rough experiments show that up to 4 GB of memory is needed. At runtime, though, the memory requirements are modest. It seems that with the more memory requirements have droppet with recent releases of Go.

It is recommended but not required to run it behind a TLS/SSL proxy such as [Hitch](http://hitch-tls.org/) and web cache such as [Varnish Cache](https://www.varnish-cache.org/). Example configurations for these [are provided](etc/).

## Installation

Install Golang:

```bash
$ sudo yum/apt-get/brew install golang
```

Last verified with Go 1.13.

Create the Go workspace and set the ``GOPATH`` environment variable:

```bash
$ mkdir ${HOME}/go
$ cd ${HOME}/go
$ mkdir src bin pkg
$ export GOPATH="${HOME}/go"
$ export PATH="${PATH}:${GOPATH}/bin"
```

Download and install Filebin:

```bash
$ go get -d github.com/espebra/filebin
$ cd ${GOPATH}/src/github.com/espebra/filebin
$ make get-deps
$ make install
```

The binary is created as ``${GOPATH}/bin/filebin``, which can be executed immediately. The ``--version`` argument prints the build time and the git commit hash used in the build.

```bash
$ ${GOPATH}/bin/filebin --version
Git Commit Hash: 40bd401ec350c86a46cdb3dc87f6b70c3c0b796b
UTC Build Time: 2015-11-11 23:01:35
```

Create the directories to use for storing files and temporary files:

```bash
$ mkdir ~/filebin ~/filebin/files ~/filebin/temp
```

## Configuration

Configuration is done using command line arguments when starting filebin. The built in help text will show the various arguments available:

```bash
$ ${GOPATH}/bin/filebin --help
```

Some arguments commonly used to start ``filebin`` are:

```bash
$ ${GOPATH}/bin/filebin \
  --host 0.0.0.0 --port 31337
  --baseurl http://api.example.com:31337
  --filedir ~/filebin/files \
  --tempdir ~/filebin/temp \
  --expiration 604800 \
  --cache-invalidation \
  --admin-username admin \
  --admin-password changeme \
  --client-address-header x-client \
  --access-log /var/log/filebin/access.log \
  [...]
```

By default it will listen on ``127.0.0.1:31337``.

### Command line arguments

The following are elaborations on some of the command line arguments.

#### Baseurl

The ``--baseurl`` parameter is used when building [HATEOAS](https://en.wikipedia.org/wiki/HATEOAS) links in the JSON responses and to generate the correct hyperlinks in the HTML responses. If ``--baseurl`` is wrong, the required css and javascript resources will not load properly.

An example when having a TLS/SSL proxy in front on port 443 would be ``--baseurl https://filebin.example.com``.

It is also possible to run filebin from a subdirectory if specifying this accordingly with for example ``--baseurl https://www.example.com/filebin``.

A trailing slash is not needed.

#### Expiration

Bins expire after some time of inactivity. By default, bins will expire 3 months after the most recent file was uploaded. It is not possible to download files or upload more files to bins that are expired.

``--expiration 86400`` will expire bins 24 hours after the last file has been uploaded.

#### Content-type filtering

To limit abuse it can be necessary to reject certain content-types. The ``--filter`` option can be applied multiple times in order to filter on multiple content-types. The filters are considered for each file upload using a sub string match on the content-type that is detected by the uploaded file.

``--filter text/html`` fill reject file uploads matching the content-type ``text/html``, including ``text/html; charset=utf-8``.

``--filter text/html --filter image`` fill reject file uploads matching the content-type ``text/html`` and all image files such as ``image/jpeg`` and ``image/png``.

#### Cache invalidation

Enabled with the parameter ``--cache-invalidation``. When enabled, HTTP PURGE requests will be sent to baseurl/path for every change to ensure content is invalidated on any frontend web cache.

#### Client Address Header

The parameter ``--client-address-header`` can specify a request header to read the original client IP address from. This might be useful if having one or more proxies on layer 7 in front of the filebin daemon.

#### Admin username and password

The parameters ``--admin-username`` and ``--admin-password`` will, if set, enable the administrator page. It is available at the URL baseurl/admin, with the specified username and password for login.

#### Access log

The parameter ``--access-log`` is used to set a full path for the access log. The access log is written in the [Combined Log Format](http://httpd.apache.org/docs/2.2/logs.html#combined).

#### Hot Linking

The parameter ``--hot-linking`` is enabled by default and allows hot linking of files. Hot linking is convenient sice it allows easy and direct access to files from other computers, but it also makes it easy to abuse the service. Starting Filebin with ``--hot-linking=false`` is a compromise that enables hot linking using tokens that are valid only for a short period of time.

#### Triggers

Triggers enable external scripts to be executed at certain events.

##### New bin

The parameter ``--trigger-new-bin <command>`` makes sure ``<command> <bin>`` is executed whenever a new bin is being created. The execution is non-blocking. Example:

``--trigger-new-bin /usr/local/bin/new-bin`` will execute ``/usr/local/bin/new-bin <binid>``.

##### Upload file

The parameter ``--trigger-upload-file <command>`` makes sure ``<command> <bin> <filename>`` is executed whenever a new file is uploaded. The execution is non-blocking. Example:

``--trigger-upload-file /usr/local/bin/upload-file`` will execute ``/usr/local/bin/upload-file <binid> <filename>``.

##### Download bin

The parameter ``--trigger-download-bin <command>`` makes sure ``<command> <bin>`` is executed whenever a bin is downloaded as an archive. The execution is non-blocking. Example:

``--trigger-download-bin /usr/local/bin/download-bin`` will execute ``/usr/local/bin/download-bin <binid>``.

##### Download file

The parameter ``--trigger-download-file <command>`` makes sure ``<command> <bin> <filename>`` is executed whenever a file is downloaded. The execution is non-blocking. Example:

``--trigger-download-file /usr/local/bin/download-file`` will execute ``/usr/local/bin/download-file <binid> <filename>``.

##### Delete bin

The parameter ``--trigger-delete-bin <command>`` makes sure ``<command> <bin>`` is executed whenever a bin is deleted. The execution is non-blocking. Example:

``--trigger-delete-bin /usr/local/bin/delete-bin`` will execute ``/usr/local/bin/delete-bin <binid>``.

##### Delete file

The parameter ``--trigger-delete-file <command>`` makes sure ``<command> <bin> <filename>`` is executed whenever a file is deleted. The execution is non-blocking. Example:

``--trigger-delete-file /usr/local/bin/delete-file`` will execute ``/usr/local/bin/delete-file <binid> <filename>``.

## Web interface

### Create new bin / empty bin

![New bin](doc/screenshot-web-interface-new-bin.png)

### File uploads in progress

![File uploads in progress](doc/screenshot-web-interface-uploading.png)

### View bin with files

![View bin with files](doc/screenshot-web-interface-bin.png)

## Web service

### Upload file

|			| Value						|
| --------------------- | ----------------------------------------------|
| **Method**		| ``POST``					|
| **URL**		| /						|
| **URL parameters**	| *None*					|
| **Request headers**	| ``filename``, ``bin``				|
| **Request body**	| File content in binary form			|
| **Success response**	| ``201``					|
| **Error response**	| ``400``					|

###### Examples

In all examples, the local file ``/path/to/some file`` will be uploaded.

Using the following command, the ``bin`` will be automatically generated and the ``filename`` of the uploaded file will be ``myfilename``:

```bash
$ curl --data-binary "@/path/to/some file" -H "filename: myfilename" https://filebin.example.com/
```

Using the following command, ``bin`` will be set to ``custombin`` and ``filename`` will be set to ``myfile``.

```bash
$ curl --data-binary "@/path/to/some file" https://filebin.example.com/ \
  -H "bin: custombin" -H "filename: myfile"
```

### Fetch bin details

|			| Value						|
| --------------------- | --------------------------------------------- |
| **Method**		| ``GET``					|
| **URL**		| /:bin						|
| **URL parameters**	| *None*					|
| **Request headers**	| ``Accept: application/json``		|
| **Request body**	| *None*					|
| **Success response**	| ``200``					|
| **Error response**	| ``404``					|

###### Examples

The following command will print a JSON structure showing which files that available in the bin ``custombin``.

```bash
$ curl -H "Accept: application/json" https://filebin.example.com/custombin
```

### Fetch bin as an archive

|			| Value						|
| --------------------- | --------------------------------------------- |
| **Method**		| ``GET``					|
| **URL**		| /:archive/:bin/:format			|
| **URL parameters**	| *None*					|
| **Request headers**	| *None*					|
| **Request body**	| *None*					|
| **Success response**	| ``200``					|
| **Error response**	| ``404``					|

###### Examples

The following commands will download the files in ``custombin`` as tar and zip archives:

```bash
# Tar
$ curl -o custombin.tar https://filebin.example.com/archive/custombin/tar

# Zip
$ curl -o custombin.zip https://filebin.example.com/archive/custombin/zip
```

### Download file

|			| Value			|
| --------------------- | ----------------------|
| **Method**		| ``GET``		|
| **URL**		| /:bin/:filename	|
| **URL parameters**	| *None*		|
| **Request headers**	| *None*		|
| **Request body**	| *None*		|
| **Success response**	| ``200``		|
| **Error response**	| ``404``		|

###### Examples

Downloading a file is as easy as specifying the ``bin`` and the ``filename`` in the request URI:

```bash
$ curl https://filebin.example.com/custombin/myfile
```

Note that if hot linking is disabled, then a token is introduced as a query parameter that makes the URL non-deterministic. A side effect is that this makes it harder to use the API to download files.

### Delete file

|			| Value			|
| --------------------- | ----------------------|
| **Method**		| ``DELETE``		|
| **URL**		| /:bin/:filename	|
| **URL parameters**	| *None*		|
| **Request headers**	| *None*		|
| **Request body**	| *None*		|
| **Success response**	| ``200``		|
| **Error response**	| ``404``		|

### Delete bin

|			| Value			|
| --------------------- | ----------------------|
| **Method**		| ``DELETE``		|
| **URL**		| /:bin			|
| **URL parameters**	| *None*		|
| **Request headers**	| *None*		|
| **Request body**	| *None*		|
| **Success response**	| ``200``		|
| **Error response**	| ``404``		|

###### Examples

```bash
$ curl -X DELETE https://filebin.example.com/custombin/myfile
```

## Logging

Logs are written to stdout, and can easily be redirected to for example syslog when using the [systemd service script provided](etc/systemd/filebin.service.example).

## Database

Filebin does currently not use any other database than the filesystem itself.

## Development

### Git hooks

There is a pre-commit hook available in the repository that will make sure that commited go source code is properly formatted. Enable it with a symlink:

```bash
$ ln -s tools/git/pre-commit .git/hooks/pre-commit
```

## TODO

* Automatically clean up expired bins.
* Avoid reuse of expired bins.
* Trigger cache invalidation on bin expiration.


text:
START_ATF_NAMESPACE
    namespace Info
    {

        using _pt_automine_info_zoclctor__pt_automine_info_zocl2_ptr = void (WINAPIV*)(struct _pt_automine_info_zocl*);
        using _pt_automine_info_zoclctor__pt_automine_info_zocl2_clbk = void (WINAPIV*)(struct _pt_automine_info_zocl*, _pt_automine_info_zoclctor__pt_automine_info_zocl2_ptr);
        using _pt_automine_info_zoclsize4_ptr = int (WINAPIV*)(struct _pt_automine_info_zocl*);
        using _pt_automine_info_zoclsize4_clbk = int (WINAPIV*)(struct _pt_automine_info_zocl*, _pt_automine_info_zoclsize4_ptr);
    }; // end namespace Info
END_ATF_NAMESPACE


text:
require File.expand_path('../../../spec_helper', __FILE__)

ruby_version_is "1.8.7" do
  describe "Range#max" do
    it "returns the maximum value in the range when called with no arguments" do
      (1..10).max.should == 10
      (1...10).max.should == 9
      ('f'..'l').max.should == 'l'
      ('a'...'f').max.should == 'e'
    end

    ruby_version_is "1.9" do
      it "returns the maximum value in the Float range when called with no arguments" do
        (303.20..908.1111).max.should == 908.1111
      end

      it "raises TypeError when called on an exclusive range and a non Integer value" do
        lambda { (303.20...908.1111).max }.should raise_error(TypeError)
      end
    end

    ruby_version_is ""..."1.9" do
      it "raises TypeError when called on a Float range" do
        lambda { (303.20..908.1111).max }.should raise_error(TypeError)
      end
    end

    it "returns nil when the endpoint is less than the start point" do
      (100..10).max.should be_nil
      ('z'..'l').max.should be_nil
    end

    it "returns nil when the endpoint equals the start point and the range is exclusive" do
      (5...5).max.should be_nil
    end

    it "returns the endpoint when the endpoint equals the start point and the range is inclusive" do
      (5..5).max.should equal(5)
    end

    ruby_version_is "1.9" do
      it "returns nil when the endpoint is less than the start point in a Float range" do
        (3003.20..908.1111).max.should be_nil
      end

      it "returns end point when the range is Time..Time(included end point)" do
        time_start = Time.now
        time_end = Time.now + 1.0
        (time_start..time_end).max.should equal(time_end)
      end

      it "raises TypeError when called on a Time...Time(excluded end point)" do
        time_start = Time.now
        time_end = Time.now + 1.0
        lambda { (time_start...time_end).max  }.should raise_error(TypeError)
      end
    end
  end

  describe "Range#max given a block" do
    it "passes each pair of values in the range to the block" do
      acc = []
      (1..10).max {|a,b| acc << [a,b]; a }
      acc.flatten!
      (1..10).each do |value|
        acc.include?(value).should be_true
      end
    end

    it "passes each pair of elements to the block in reversed order" do
      acc = []
      (1..5).max {|a,b| acc << [a,b]; a }
      acc.should == [[2,1],[3,2], [4,3], [5, 4]]
    end

    it "calls #> and #< on the return value of the block" do
      obj = mock('obj')
      obj.should_receive(:>).exactly(2).times
      obj.should_receive(:<).exactly(2).times
      (1..3).max {|a,b| obj }
    end

    it "returns the element the block determines to be the maximum" do
      (1..3).max {|a,b| -3 }.should == 1
    end

    it "returns nil when the endpoint is less than the start point" do
      (100..10).max {|x,y| x <=> y}.should be_nil
      ('z'..'l').max {|x,y| x <=> y}.should be_nil
      (5...5).max {|x,y| x <=> y}.should be_nil
    end
  end
end


text:
/* ========================================= */
/* = Themes admin plugin main css file = */
/* ========================================= */

/* Dashboard */
h1.dashboard-title {
  background-image: url('../images/icons/themes_40.png');
}

.current-theme h2 {
  margin-left: 10px;
  margin-bottom: 5px;
}

.current-theme .info {
  float: left;
  font-size: 120%;
}

.current-screenshot, .theme-screenshot {
  padding: 5px;
  border: 1px dotted #CCC;
  float: left;
  margin-right: 10px;
  margin-bottom: 5px;
}

.available-themes table th, .available-themes table td{
  border: 0;
  text-align: center;
  font-size: 18px;
}

#dialog	{display: none;}


text:
cask 'clockify' do
  version '2.2.8.83'
  sha256 '8836c2f920d241854ec1a8a79ba871f7b02bdd56e6ca748a9bbd1f39c96de7c7'

  # clockify-resources.s3.eu-central-1.amazonaws.com was verified as official when first introduced to the cask
  url "https://clockify-resources.s3.eu-central-1.amazonaws.com/downloads/ClockifyDesktop_#{version.no_dots}.zip"
  appcast 'https://clockify.me/mac-time-tracking',
          configuration: version.no_dots
  name 'Clockify'
  homepage 'https://clockify.me/mac-time-tracking'

  depends_on macos: '>= :sierra'

  app 'Clockify Desktop.app'
end


text:
package me.chanjar.weixin.mp.bean.result;

import me.chanjar.weixin.common.util.ToStringUtils;
import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;

import java.io.Serializable;

/**
 * <pre>
 * 群发消息一发送就返回的结果
 *
 * 真正的群发消息是否发送成功要看
 * http://mp.weixin.qq.com/wiki/index.php?title=高级群发接口#.E4.BA.8B.E4.BB.B6.E6.8E.A8.E9.80.81.E7.BE.A4.E5.8F.91.E7.BB.93.E6.9E.9C
 *
 * </pre>
 *
 * @author chanjarster
 */
public class WxMpMassSendResult implements Serializable {
    private static final long serialVersionUID = -4816336807575562818L;
    private String errorCode;
    private String errorMsg;
    private String msgId;
    private String msgDataId;

    public static WxMpMassSendResult fromJson(String json) {
        return WxMpGsonBuilder.create().fromJson(json, WxMpMassSendResult.class);
    }

    public String getErrorCode() {
        return this.errorCode;
    }

    public void setErrorCode(String errorCode) {
        this.errorCode = errorCode;
    }

    public String getErrorMsg() {
        return this.errorMsg;
    }

    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }

    public String getMsgId() {
        return this.msgId;
    }

    public void setMsgId(String msgId) {
        this.msgId = msgId;
    }

    public String getMsgDataId() {
        return this.msgDataId;
    }

    public void setMsgDataId(String msgDataId) {
        this.msgDataId = msgDataId;
    }

    @Override
    public String toString() {
        return ToStringUtils.toSimpleString(this);
    }

}


text:
package info.dgjones.abora.gold.collection.sets;

import info.dgjones.abora.gold.collection.sets.ActualHashSet;
import info.dgjones.abora.gold.collection.sets.ImmuSet;
import info.dgjones.abora.gold.collection.sets.MuSet;
import info.dgjones.abora.gold.collection.sets.ScruSet;
import info.dgjones.abora.gold.collection.steppers.Stepper;
import info.dgjones.abora.gold.java.AboraSupport;
import info.dgjones.abora.gold.java.exception.PasseException;
import info.dgjones.abora.gold.java.exception.SubclassResponsibilityException;
import info.dgjones.abora.gold.java.missing.smalltalk.Set;
import info.dgjones.abora.gold.spaces.basic.XnRegion;
import info.dgjones.abora.gold.xcvr.Rcvr;
import info.dgjones.abora.gold.xpp.basic.Heaper;

/**
 * MuSets are a changable collection of elements.  Added to the ScruSet protocol are messages
 * for performing these changes.  The "introduce/store/wipe/remove" suite is defined by
 * analogy with similar methods in MuTable.  See both ScruSet and MuTable.
 */
public class MuSet extends ScruSet {

/*
udanax-top.st:45823:
ScruSet subclass: #MuSet
	instanceVariableNames: ''
	classVariableNames: ''
	poolDictionaries: ''
	category: 'Xanadu-Collection-Sets'!
*/
/*
udanax-top.st:45827:
MuSet comment:
'MuSets are a changable collection of elements.  Added to the ScruSet protocol are messages for performing these changes.  The "introduce/store/wipe/remove" suite is defined by analogy with similar methods in MuTable.  See both ScruSet and MuTable.'!
*/
/*
udanax-top.st:45829:
(MuSet getOrMakeCxxClassDescription)
	friends:
'/- friends for class MuSet -/
friend class ImmuSetOnMu;
friend class COWMuSet;';
	attributes: ((Set new) add: #DEFERRED; add: #EQ; yourself)!
*/
/*
udanax-top.st:45926:
MuSet class
	instanceVariableNames: ''!
*/
/*
udanax-top.st:45929:
(MuSet getOrMakeCxxClassDescription)
	friends:
'/- friends for class MuSet -/
friend class ImmuSetOnMu;
friend class COWMuSet;';
	attributes: ((Set new) add: #DEFERRED; add: #EQ; yourself)!
*/
public static void initializeClassAttributes() {
	AboraSupport.findAboraClass(MuSet.class).setAttributes( new Set().add("DEFERRED").add("EQ"));
/*

Generated during transformation: AddMethod
*/
}
public boolean hasMember(Heaper someone) {
	throw new SubclassResponsibilityException();
/*
udanax-top.st:45838:MuSet methodsFor: 'accessing'!
{BooleanVar} hasMember: someone {Heaper}
	self subclassResponsibility!
*/
}
public boolean isEmpty() {
	throw new SubclassResponsibilityException();
/*
udanax-top.st:45841:MuSet methodsFor: 'accessing'!
{BooleanVar} isEmpty
	self subclassResponsibility!
*/
}
/**
 * Sort of intersect.  Wipe from myself all elements that I don't have in common with other.
 * Turn myself into the intersection of my current self and other.
 */
public void restrictTo(ScruSet other) {
	MuSet tmp;
	tmp = (MuSet) copy();
	tmp.wipeAll(other);
	wipeAll(tmp);
	tmp.destroy();
/*
udanax-top.st:45846:MuSet methodsFor: 'operations'!
{void} restrictTo: other {ScruSet}
	"Sort of intersect.  Wipe from myself all elements that I don't have in common with other.
	Turn myself into the intersection of my current self and other."
	| tmp {MuSet} |
	tmp _ self copy cast: MuSet.
	tmp wipeAll: other.
	self wipeAll: tmp.
	tmp destroy.!
*/
}
/**
 * Sort of union.  Store into myself all elements from other.
 * Turn myself into the union of my current self and other.
 */
public void storeAll(ScruSet other) {
	Stepper stomper = other.stepper();
	for (; stomper.hasValue(); stomper.step()) {
		Heaper elem = (Heaper) stomper.fetch();
		if (elem == null) {
			continue ;
		}
		store(elem);
	}
	stomper.destroy();
/*
udanax-top.st:45856:MuSet methodsFor: 'operations'!
{void} storeAll: other {ScruSet}
	"Sort of union.  Store into myself all elements from other.
	Turn myself into the union of my current self and other."
	other stepper forEach: [:elem {Heaper wimpy} | self store: elem]!
*/
}
/**
 * Sort of minus.  Wipe from myself all elements from other.
 * Turn myself into my current self minus other.
 */
public void wipeAll(ScruSet other) {
	Stepper stomper = other.stepper();
	for (; stomper.hasValue(); stomper.step()) {
		Heaper elem = (Heaper) stomper.fetch();
		if (elem == null) {
			continue ;
		}
		wipe(elem);
	}
	stomper.destroy();
/*
udanax-top.st:45862:MuSet methodsFor: 'operations'!
{void} wipeAll: other {ScruSet}
	"Sort of minus.  Wipe from myself all elements from other.
	Turn myself into my current self minus other."
	other stepper forEach: [:elem {Heaper wimpy} | self wipe: elem]!
*/
}
/**
 * Add anElement to my members, but only if it isn't already a member.
 * If it is already a member, BLAST
 */
public void introduce(Heaper anElement) {
	throw new SubclassResponsibilityException();
/*
udanax-top.st:45870:MuSet methodsFor: 'adding-removing'!
{void} introduce: anElement {Heaper}
	"Add anElement to my members, but only if it isn't already a member.
	If it is already a member, BLAST"

	self subclassResponsibility!
*/
}
/**
 * Remove anElement from my members.  If it isn't currently a member, then BLAST
 */
public void remove(Heaper anElement) {
	throw new SubclassResponsibilityException();
/*
udanax-top.st:45876:MuSet methodsFor: 'adding-removing'!
{void} remove: anElement {Heaper}
	"Remove anElement from my members.  If it isn't currently a member, then BLAST"

	self subclassResponsibility!
*/
}
/**
 * Add anElement to my set of members.  No semantic effect if anElement is already a member.
 */
public void store(Heaper anElement) {
	throw new SubclassResponsibilityException();
/*
udanax-top.st:45881:MuSet methodsFor: 'adding-removing'!
{void} store: anElement {Heaper}
	"Add anElement to my set of members.  No semantic effect if anElement is already a member."

	self subclassResponsibility!
*/
}
/**
 * make anElement no longer be one of my members.  No semantic effect if it already isn't a
 * member.
 */
public void wipe(Heaper anElement) {
	throw new SubclassResponsibilityException();
/*
udanax-top.st:45886:MuSet methodsFor: 'adding-removing'!
{void} wipe: anElement {Heaper}
	"make anElement no longer be one of my members.  No semantic effect if it already isn't a member."

	self subclassResponsibility!
*/
}
public ScruSet copy() {
	throw new SubclassResponsibilityException();
/*
udanax-top.st:45893:MuSet methodsFor: 'creation'!
{ScruSet} copy
	self subclassResponsibility!
*/
}
public ImmuSet asImmuSet() {
	if (isEmpty()) {
		return ImmuSet.make();
	}
	if (count() == 1) {
		return ImmuSet.make().with((theOne()));
	}
	return ImmuSet.make(this);
/*
udanax-top.st:45898:MuSet methodsFor: 'conversion'!
{ImmuSet} asImmuSet
	self isEmpty ifTrue: [^ ImmuSet make].
	self count == 1 ifTrue: [^ ImmuSet make with: (self theOne)].
	^ ImmuSet make: self!
*/
}
public MuSet asMuSet() {
	return (MuSet) copy();
/*
udanax-top.st:45903:MuSet methodsFor: 'conversion'!
{MuSet} asMuSet
	^ self copy quickCast: MuSet!
*/
}
public int count() {
	throw new SubclassResponsibilityException();
/*
udanax-top.st:45908:MuSet methodsFor: 'enumerating'!
{IntegerVar} count
	self subclassResponsibility!
*/
}
public Stepper stepper() {
	throw new SubclassResponsibilityException();
/*
udanax-top.st:45911:MuSet methodsFor: 'enumerating'!
{Stepper} stepper
	self subclassResponsibility!
*/
}
public Stepper immuStepper() {
	throw new SubclassResponsibilityException();
/*
udanax-top.st:45916:MuSet methodsFor: 'private: enumerating'!
{Stepper} immuStepper
	self subclassResponsibility!
*/
}
public int actualHashForEqual() {
	return asOop();
/*
udanax-top.st:45921:MuSet methodsFor: 'generated:'!
actualHashForEqual ^self asOop!
*/
}
public boolean isEqual(Heaper other) {
	return this == other;
/*
udanax-top.st:45923:MuSet methodsFor: 'generated:'!
isEqual: other ^self == other!
*/
}
/**
 * someSize is a non-semantic hint about how big the set might get.
 * @deprecated
 */
public static void makeRegion(XnRegion region) {
	throw new PasseException();
/*
udanax-top.st:45938:MuSet class methodsFor: 'smalltalk: passe'!
make.Region: region {XnRegion}
	"someSize is a non-semantic hint about how big the set might get."
	| result {MuSet} |
	self passe.
	result _ ActualHashSet make.IntegerVar: region count.
	region stepper forEach: [:position {Position} | result store: position].
	^result!
*/
}
public static MuSet fromStepper(Stepper stepper) {
	MuSet result;
	result = MuSet.make();
	Stepper stomper = stepper;
	for (; stomper.hasValue(); stomper.step()) {
		Heaper element = (Heaper) stomper.fetch();
		if (element == null) {
			continue ;
		}
		result.store(element);
	}
	stomper.destroy();
	return result;
/*
udanax-top.st:45949:MuSet class methodsFor: 'pseudo constructors'!
{MuSet} fromStepper: stepper {Stepper}
	| result {MuSet} |
	result _ MuSet make.
	stepper forEach: [ :element {Heaper} |
		result store: element].
	^result!
*/
}
public static MuSet make() {
	return ActualHashSet.make();
/*
udanax-top.st:45956:MuSet class methodsFor: 'pseudo constructors'!
{MuSet} make
	^ActualHashSet make!
*/
}
public static MuSet makeHeaper(Heaper item) {
	return ActualHashSet.makeHeaper(item);
/*
udanax-top.st:45959:MuSet class methodsFor: 'pseudo constructors'!
{MuSet} make.Heaper: item {Heaper}
	^ActualHashSet make.Heaper: item!
*/
}
/**
 * someSize is a non-semantic hint about how big the set might get.
 */
public static MuSet makeIntegerVar(int someSize) {
	return ActualHashSet.makeIntegerVar(someSize);
/*
udanax-top.st:45963:MuSet class methodsFor: 'pseudo constructors'!
{MuSet} make.IntegerVar: someSize {IntegerVar}
	"someSize is a non-semantic hint about how big the set might get."
	^ActualHashSet make.IntegerVar: someSize!
*/
}
/*
udanax-top.st:45969:MuSet class methodsFor: 'smalltalk: defaults'!
make: something
	(something isKindOf: Integer) ifTrue:
		[^self make.IntegerVar: something].
	^self make.Region: (something cast: XnRegion)!
*/
public static void initTimeNonInherited() {
/*
udanax-top.st:45976:MuSet class methodsFor: 'smalltalk: initialization'!
initTimeNonInherited
	self REQUIRES: ActualHashSet!
*/
}
/*
udanax-top.st:45982:MuSet class methodsFor: 'exceptions: exceptions'!
problems.AlreadyInSet
	^self signals: #(AlreadyInSet)!
*/
public MuSet() {
/*

Generated during transformation
*/
}
public MuSet(Rcvr receiver) {
	super(receiver);
/*

Generated during transformation
*/
}
public static MuSet make(int i) {
	return makeIntegerVar(i);
/*

Generated during transformation: AddMethod
*/
}
}


text:
cdi-jpa2-non-jta-datasource-integration
=======================================

Junit integration for jpa2 with a non jta datasource.


text:
package com.izforge.izpack.installer.bootstrap;

import com.izforge.izpack.api.container.Container;
import com.izforge.izpack.api.data.InstallData;
import com.izforge.izpack.api.exception.IzPackException;
import com.izforge.izpack.installer.console.ConsoleInstaller;
import com.izforge.izpack.installer.container.impl.ConsoleInstallerContainer;
import com.izforge.izpack.installer.container.impl.InstallerContainer;
import com.izforge.izpack.installer.language.LanguageConsoleDialog;
import com.izforge.izpack.installer.requirement.RequirementsChecker;
import com.izforge.izpack.util.Housekeeper;

import java.util.logging.Logger;

/**
 * Console installer bootstrap
 */
public class InstallerConsole
{
  private static final Logger logger = Logger.getLogger(InstallerConsole.class.getName());

  public static void run(final int type, final int consoleAction, final String path, final String langCode, final String mediaPath, final String[] args)
  {
    final InstallerContainer applicationComponent = new ConsoleInstallerContainer();
    final Container installerContainer = applicationComponent.getComponent(Container.class);
    try
    {
      if (mediaPath != null)
      {
        InstallData installData = applicationComponent.getComponent(InstallData.class);
        installData.setMediaPath(mediaPath);
      }
      ConsoleInstaller consoleInstaller = installerContainer.getComponent(ConsoleInstaller.class);
      if (langCode == null)
      {
        installerContainer.getComponent(LanguageConsoleDialog.class).initLangPack();
      }
      else
      {
        installerContainer.getComponent(LanguageConsoleDialog.class).propagateLocale(langCode);
      }
      if (!installerContainer.getComponent(RequirementsChecker.class).check())
      {
        logger.info("Not all installer requirements are fulfilled.");
        installerContainer.getComponent(Housekeeper.class).shutDown(-1);
      }
      consoleInstaller.run(consoleAction, path, args);
    }
    catch (Exception e)
    {
      throw new IzPackException(e);
    }
  }
}


text:
%  fcl kmeans fit
%
%  [ C ]    = fcl_kmeans_fit(X, k, opts) returns the cluster center matrix C.
%
%  [ C, T ] = fcl_kmeans_fit(X, k, opts) returns internal information about the algorithm (explanation see below).
%
%  Input:
%       X:      sparse input data (num columns, dim rows)
%       k:      the desired number of clusters
%       opts:   (Optional) struct containing the following additional parameters:
%
%               opts.algorithm: Choices are "kmeans", "bv_kmeans" (default), "yinyang",
%                               "bv_yinyang", "minibatch_kmeans", "bv_minibatch_kmeans", "elkan"
%               opts.init:      Initialization strategy. Choices are "random" (default) and "kmeans++".
%               opts.seed:      Seed when using random initializations. Default is 1.
%               opts.tol:       Tolerance (stopping criterion). Default is 1e-6.
%               opts.max_iter:  The iteration limit. Default is 1000.
%               opts.silent:    Suppress console output. Default is false.
%               opts.no_cores:  Specify how many cores to use. Default = all.
%               opts.remove_empty:  Remove empty clusters at the end of the clustering (default: false).
%
%
%  Output T aka tracking parameters:
%       T.general_params                   % stores all params kmeans was run with
%       T.general_params.no_clusters       % number of clusters requested
%       T.general_params.algorithm         % the used algorithms
%       T.general_params.seed              % The seed used for clustering
%       T.general_params.remove_empty      % If true, empty clusters are removed after clustering
%       T.general_params.iteration_limit   % After how many iterations to stop (if not converged by then)
%       T.general_params.tol               % If objective does not improve more than 'tol', converge
%       T.general_params.init              % Initialization strategy used
%       T.general_params.no_cores_used     % Number of cores used for this experiment
%
%       T.duration_init                    % Duration the initialization strategy took
%       T.initial_wcssd                    % Objective value before first iteration
%       T.input_samples                    % Number of samples in the dataset used for clustering
%       T.input_dimension                  % Dimensionality of the input dataset
%       T.additional_params                % Additional internal params set by the algorithms (can be modified from outside)
%       T.block_vector_data                % Data about block vector
%       T.iteration_bv_calcs               % This field only exists if a block vector algorithm is used and contains an for every iteration the amount of bv calculations
%       T.iteration_wcssd                  % Contains for every iteration the objective value
%       T.iteration_changes                % Contains how many samples moved to a new cluster in every iteration
%       T.iteration_remaining_clusters     % Number of non empty clusters in every iteration.
%       T.iteration_full_distance_calcs    % Number of full distance calculations per iteration.
%       T.iteration_durations_calcs        % Time it took to do the main loop of calculation
%       T.iteration_durations_update_clusters  % Time it took to move the clusters
%       T.iteration_durations              % Time the complete iteration took
%       T.no_iterations                    % Number of iterations needed to converge
%       T.duration_kmeans                  % Time the complete kmeans clustering took
%       T.no_clusters_remaining            % Number of clusters remaining (s. remove_empty option)
%
%  Tracking parameters are a very powerful tool for researchers and can even be extended with very little effort to output
%  arbitrary data about an algorithm. Have a look at fcl/examples/matlab/kmeans/basic/tracking_params.m for more information.
%
%
%  For more information about the implemented algorithms, see
%
%  Thomas Bottesch, Thomas Buehler, Markus Kaechele
%  Speeding up k-means by approximating Euclidean distances via blockvectors
%  Proc. 33rd International Conference on Machine Learning, New York, USA, 2016.
%  JMLR: W&CP volume 48. http://jmlr.org/proceedings/papers/v48/bottesch16.pdf