text:
"""
BOSH Client
-----------

Based on https://friendpaste.com/1R4PCcqaSWiBsveoiq3HSy

"""

import gzip
import socket
import base64
import httplib
import logging
import StringIO

from random import randint
from urlparse import urlparse
from xml.etree import ElementTree as ET

from puresasl.client import SASLClient

try:  # Python 2.7+
    from logging import NullHandler
except ImportError:
    class NullHandler(logging.Handler):
        def emit(self, record):
            pass

HTTPBIND_NS = 'http://jabber.org/protocol/httpbind'
BOSH_NS = 'urn:xmpp:xbosh'
XMPP_SASL_NS = 'urn:ietf:params:xml:ns:xmpp-sasl'
XMPP_BIND_NS = 'urn:ietf:params:xml:ns:xmpp-bind'
JABBER_CLIENT_NS = 'jabber:client'
JABBER_STREAMS_NS = 'http://etherx.jabber.org/streams'
XMPP_VERSION = '1.0'
BOSH_VERSION = '1.6'
BOSH_CONTENT = 'text/xml; charset=utf-8'
XML_LANG = 'en'
BOSH_WAIT = 60
BOSH_HOLD = 1

class BOSHClient(object):
    def __init__(self, jid, password, bosh_service):
        """ Initialize the client.

        You must specify the Jabber ID, the corresponding password and the URL
        of the BOSH service to connect to.

        """
        self.log = logging.getLogger('conversejs.boshclient')
        self.log.addHandler(NullHandler())

        self._connection = None
        self._sid = None

        self.jid, self.to = jid.split('@')
        self.password = password
        self.bosh_service = urlparse(bosh_service)

        self.rid = randint(0, 10000000)
        self.log.debug('Init RID: %s' % self.rid)

        self.headers = {
            "Content-Type": "text/plain; charset=UTF-8",
            "Accept": "text/xml",
            "Accept-Encoding": "gzip, deflate"
        }

        self.server_auth = []

    @property
    def connection(self):
        """Returns an stablished connection"""

        if self._connection:
            return self._connection

        self.log.debug('Initializing connection to %s' % (self.bosh_service.
                                                          netloc))
        if self.bosh_service.scheme == 'http':
            Connection = httplib.HTTPConnection
        elif self.bosh_service.scheme == 'https':
            Connection = httplib.HTTPSConnection
        else:
            # TODO: raise proper exception
            raise Exception('Invalid URL scheme %s' % self.bosh_service.scheme)

        self._connection = Connection(self.bosh_service.netloc, timeout=10)
        self.log.debug('Connection initialized')
        # TODO add exceptions handler there (URL not found etc)

        return self._connection

    def close_connection(self):
        if not self._connection:
            self.log.debug('Trying to close connection before initializing it.')
            return

        self.log.debug('Closing connection')
        self.connection.close()
        self.log.debug('Connection closed')
        # TODO add execptions handler there

    def get_body(self, sid_request=False):
        body = ET.Element('body')

        body.set('xmlns', HTTPBIND_NS)

        if sid_request:
            body.set('xmlns:xmpp', BOSH_NS)
            body.set('wait', unicode(BOSH_WAIT))
            body.set('hold', unicode(BOSH_HOLD))
            body.set('content', BOSH_CONTENT)
            body.set('ver', unicode(BOSH_VERSION))

            body.set('xmpp:version', unicode(XMPP_VERSION))

            body.set('xml:lang', "en")

            body.set('to', self.to)

        if self._sid:
            body.set('sid', self.sid)

        body.set('rid', str(self.rid))

        return body

    def send_request(self, xml_stanza):
        ElementType = getattr(ET, '_Element', ET.Element)
        if isinstance(xml_stanza, ElementType):
            xml_stanza = ET.tostring(xml_stanza)

        self.log.debug('XML_STANZA: %s', xml_stanza)
        self.log.debug('Sending the request')

        self.connection.request("POST", self.bosh_service.path,
                                xml_stanza, self.headers)
        response = self.connection.getresponse()
        self.log.debug('Response status code: %s' % response.status)

        # Increment request id:
        #    http://xmpp.org/extensions/xep-0124.html#rids-syntax
        self.rid += 1

        if response.status == 200:
            data = response.read()
            if response.getheader('content-encoding', '').lower() == 'gzip':
                buf = StringIO.StringIO(data)
                f = gzip.GzipFile(fileobj=buf)
                data = f.read()
        else:
            self.log.debug('Something wrong happened!')
            return False

        self.log.debug('DATA: %s', data)
        return data

    @property
    def sid(self):
        if self._sid:
            return self._sid

        return self.request_sid()

    def request_sid(self):
        """ Request a BOSH session according to
        http://xmpp.org/extensions/xep-0124.html#session-request
        Returns the new SID (str).

        """
        if self._sid:
            return self._sid

        self.log.debug('Prepare to request BOSH session')

        data = self.send_request(self.get_body(sid_request=True))
        if not data:
            return None

        # This is XML. response_body contains the <body/> element of the
        # response.
        response_body = ET.fromstring(data)

        # Get the remote Session ID
        self._sid = response_body.get('sid')
        self.log.debug('sid = %s' % self._sid)

        # Get the longest time (s) that the XMPP server will wait before
        # responding to any request.
        self.server_wait = response_body.get('wait')
        self.log.debug('wait = %s' % self.server_wait)

        # Get the authid
        self.authid = response_body.get('authid')

        # Get the allowed authentication methods using xpath
        search_for = '{{{0}}}features/{{{1}}}mechanisms/{{{2}}}mechanism'.format(
            JABBER_STREAMS_NS, XMPP_SASL_NS, XMPP_SASL_NS
        )
        self.log.debug('Looking for "%s" into response body', search_for)
        mechanisms = response_body.findall(search_for)
        self.server_auth = []

        for mechanism in mechanisms:
            self.server_auth.append(mechanism.text)
            self.log.debug('New AUTH method: %s' % mechanism.text)

        if not self.server_auth:
            self.log.debug(('The server didn\'t send the allowed '
                            'authentication methods'))
            self._sid = None

        return self._sid

    def get_challenge(self, mechanism):
        body = self.get_body()
        auth = ET.SubElement(body, 'auth')
        auth.set('xmlns', XMPP_SASL_NS)
        auth.set('mechanism', mechanism)

        resp_root = ET.fromstring(self.send_request(body))
        challenge_node = resp_root.find('{{{0}}}challenge'.format(XMPP_SASL_NS))

        if challenge_node is not None:
            return challenge_node.text

        return None

    def send_challenge_response(self, response_plain):
        """Send a challenge response to server"""

        # Get a basic stanza body
        body = self.get_body()

        # Create a response tag and add the response content on it
        #   using base64 encoding
        response_node = ET.SubElement(body, 'response')
        response_node.set('xmlns', XMPP_SASL_NS)
        response_node.text = base64.b64encode(response_plain)

        # Send the challenge response to server
        resp_root = ET.fromstring(self.send_request(body))
        return resp_root

    def authenticate_xmpp(self):
        """Authenticate the user to the XMPP server via the BOSH connection."""

        self.request_sid()

        self.log.debug('Prepare the XMPP authentication')

        # Instantiate a sasl object
        sasl = SASLClient(
            host=self.to,
            service='xmpp',
            username=self.jid,
            password=self.password
        )

        # Choose an auth mechanism
        sasl.choose_mechanism(self.server_auth, allow_anonymous=False)

        # Request challenge
        challenge = self.get_challenge(sasl.mechanism)

        # Process challenge and generate response
        response = sasl.process(base64.b64decode(challenge))

        # Send response
        resp_root = self.send_challenge_response(response)

        success = self.check_authenticate_success(resp_root)
        if success is None and\
                resp_root.find('{{{0}}}challenge'.format(XMPP_SASL_NS)) is not None:
            resp_root = self.send_challenge_response('')
            return self.check_authenticate_success(resp_root)
        return success

    def check_authenticate_success(self, resp_root):
        if resp_root.find('{{{0}}}success'.format(XMPP_SASL_NS)) is not None:
            self.request_restart()
            self.bind_resource()
            return True
        elif resp_root.find('{{{0}}}failure'.format(XMPP_SASL_NS)) is not None:
            return False
        return None

    def bind_resource(self):
        body = self.get_body()

        iq = ET.SubElement(body, 'iq')
        iq.set('id', 'bind_1')
        iq.set('type', 'set')
        iq.set('xmlns', JABBER_CLIENT_NS)

        bind = ET.SubElement(iq, 'bind')
        bind.set('xmlns', XMPP_BIND_NS)

        self.send_request(body)

    def request_restart(self):
        body = self.get_body()
        body.set('xmpp:restart', 'true')
        body.set('xmlns:xmpp', BOSH_NS)
        self.send_request(body)

    def get_credentials(self):
        try:
            success = self.authenticate_xmpp()
        except socket.error as error:
            success = False
            self.log.exception(error)

            msg = 'Error trying to connect to bosh service: %s'
            self.log.error(msg, self.bosh_service.netloc)

        if not success:
            return None, None, None

        return u'{0}@{1}'.format(self.jid, self.to), self.sid, self.rid

if __name__ == '__main__':
    import sys

    if len(sys.argv) != 4:
        print 'usage: {0} SERVICE_URL USERNAME PASSWORD'.format(sys.argv[0])
        sys.exit(1)

    c = BOSHClient(sys.argv[2], sys.argv[3], sys.argv[1])
    print c.get_credentials()
    c.close_connection()


text:
package com.intellij.spring;

import static com.intellij.aop.psi.AopElementTypes.AOP_LEFT_PAR;
import static com.intellij.aop.psi.AopElementTypes.AOP_RIGHT_PAR;
import static com.intellij.aop.psi.AopPrattParser.parsePatternPart;

import javax.annotation.Nullable;
import jakarta.inject.Singleton;

import com.intellij.aop.AopBundle;
import com.intellij.aop.psi.AopPointcutTypes;
import com.intellij.aop.psi.PointcutDescriptor;
import com.intellij.aop.psi.PsiBeanPointcutExpression;
import com.intellij.aop.psi.PsiPointcutExpression;
import com.intellij.lang.ASTNode;
import com.intellij.lang.pratt.PrattBuilder;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtil;
import com.intellij.psi.PsiAnnotation;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.filters.ElementFilter;
import com.intellij.psi.impl.beanProperties.BeanProperty;
import com.intellij.psi.meta.MetaDataRegistrar;
import com.intellij.psi.xml.XmlTag;
import com.intellij.spring.metadata.SpringBeanMetaData;
import com.intellij.spring.metadata.SpringStereotypeQualifierMetaData;
import com.intellij.spring.model.jam.utils.JamAnnotationTypeUtil;
import com.intellij.spring.model.xml.CommonSpringBean;
import com.intellij.spring.model.xml.CustomBeanWrapper;
import com.intellij.spring.model.xml.DomSpringBean;
import com.intellij.spring.model.xml.beans.SpringBean;
import com.intellij.spring.model.xml.beans.SpringBeanPointer;
import com.intellij.spring.model.xml.beans.SpringImport;
import com.intellij.util.Function;
import com.intellij.util.NullableFunction;
import com.intellij.util.xml.DomElement;
import com.intellij.util.xml.DomManager;
import com.intellij.util.xml.ElementPresentationManager;

@Singleton
public class SpringApplicationComponent
{
	static
	{
		AopPointcutTypes.registerPointcut(new PointcutDescriptor("bean")
		{
			public void parseToken(final PrattBuilder builder)
			{
				if(builder.assertToken(AOP_LEFT_PAR, AopBundle.message("error.0.expected", "(")))
				{
					parsePatternPart(builder);
					builder.assertToken(AOP_RIGHT_PAR, AopBundle.message("error.0.expected", ")"));
				}
			}

			public PsiPointcutExpression createPsi(final ASTNode node)
			{
				return new PsiBeanPointcutExpression(node);
			}
		});
	}

	public SpringApplicationComponent()
	{
		registerPresentations();

		registerMetaData();
	}

	private static void registerMetaData()
	{
		MetaDataRegistrar.getInstance().registerMetaData(new ElementFilter()
		{
			public boolean isAcceptable(Object element, PsiElement context)
			{
				if(element instanceof XmlTag)
				{
					final XmlTag tag = (XmlTag) element;
					final DomElement domElement = DomManager.getDomManager(tag.getProject()).getDomElement(tag);
					if(!(domElement instanceof DomSpringBean))
					{
						return false;
					}

					if(!(domElement instanceof CustomBeanWrapper))
					{
						return true;
					}
					if(!((CustomBeanWrapper) domElement).isParsed())
					{
						return true;
					}
				}
				return false;
			}

			public boolean isClassAcceptable(Class hintClass)
			{
				return XmlTag.class.isAssignableFrom(hintClass);
			}
		}, SpringBeanMetaData.class);

		MetaDataRegistrar.getInstance().registerMetaData(new ElementFilter()
		{
			public boolean isAcceptable(Object element, PsiElement context)
			{
				if(element instanceof PsiAnnotation)
				{
					Module module = ModuleUtil.findModuleForPsiElement(context);
					if(module != null)
					{
						for(PsiClass psiClass : JamAnnotationTypeUtil.getQualifierAnnotationTypesWithChildren(module))
						{
							PsiAnnotation annotation = (PsiAnnotation) element;
							if(annotation.getQualifiedName().equals(psiClass.getQualifiedName()))
							{
								return true;
							}
						}
					}
				}
				return false;
			}

			public boolean isClassAcceptable(Class hintClass)
			{
				return PsiAnnotation.class.isAssignableFrom(hintClass);
			}
		}, SpringStereotypeQualifierMetaData.class);
	}

	private static void registerPresentations()
	{
		ElementPresentationManager.registerNameProvider(new Function<Object, String>()
		{

			@Nullable
			public String fun(final Object s)
			{

				if(s instanceof CommonSpringBean)
				{
					final CommonSpringBean springBean = (CommonSpringBean) s;
					final String beanName = springBean.getBeanName();
					if(beanName != null)
					{
						return beanName;
					}
					final PsiClass beanClass = springBean.getBeanClass();
					if(beanClass != null)
					{
						return beanClass.getName();
					}

					return SpringBundle.message("spring.bean.with.unknown.name");
				}
				else if(s instanceof BeanProperty)
				{
					return ((BeanProperty) s).getName();
				}
				else if(s instanceof SpringBeanPointer)
				{
					return ((SpringBeanPointer) s).getName();
				}
				else if(s instanceof SpringImport)
				{
					return ((SpringImport) s).getResource().getStringValue();
				}
				return null;
			}
		});

		ElementPresentationManager.registerDocumentationProvider(new NullableFunction<Object, String>()
		{
			public String fun(final Object o)
			{
				if(o instanceof SpringBean)
				{
					return ((SpringBean) o).getDescription().getStringValue();
				}
				return null;
			}
		});
	}
}

redpajama_set_name: RedPajamaGithub


text:
namespace rx
{

TextureStorage::TextureStorage()
    : mFirstRenderTargetSerial(0),
      mRenderTargetSerialsLayerStride(0)
{}

void TextureStorage::initializeSerials(unsigned int rtSerialsToReserve, unsigned int rtSerialsLayerStride)
{
    mFirstRenderTargetSerial = gl::RenderbufferStorage::issueSerials(rtSerialsToReserve);
    mRenderTargetSerialsLayerStride = rtSerialsLayerStride;
}

unsigned int TextureStorage::getRenderTargetSerial(const gl::ImageIndex &index) const
{
    unsigned int layerOffset = (index.hasLayer() ? (static_cast<unsigned int>(index.layerIndex) * mRenderTargetSerialsLayerStride) : 0);
    return mFirstRenderTargetSerial + static_cast<unsigned int>(index.mipIndex) + layerOffset;
}

}


text:
var rc = require('rc'),
  defaultConfig = {
    title: 'CraftML Online Editor',
    description: 'CraftML is an XML Markup Language for Defining 3D Printable Models. 100% Open Source!',
    googleWebmasterMeta: 'DAyGOgtsg8rJpq9VVktKzDkQ1UhXm1FYl8SD47hPkjA',
    keywords: '3D, OpenSCAD, OpenJSCAD, Open Source, Node.js',
    author: 'Sikuli Lab'
  };

module.exports = function() {
  return rc('dillinger', defaultConfig);
};


text:
[kakao](../../index.md) / [com.agoda.kakao.common.matchers](../index.md) / [ToolbarTitleMatcher](index.md) / [matchesSafely](./matches-safely.md)

# matchesSafely

`protected fun matchesSafely(view: Toolbar?): `[`Boolean`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-boolean/index.html)


text:
package translated.valueobjects;

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

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "TargetVO", propOrder = {
    "name",
    "type",
    "depends",
    "executions"
})
public class TargetVO {

    @XmlElement(required = true)
    protected String name;
    @XmlElement(required = true)
    protected String type;
    @XmlElement(required = true)
    protected List<CriteriaVO> depends;
    @XmlElement(required = true)
    protected List<ActionVO> executions;

    public String getName() {
        return name;
    }

    public void setName(String value) {
        this.name = value;
    }

    public String getType() {
        return type;
    }

    public void setType(String value) {
        this.type = value;
    }

    public List<CriteriaVO> getDepends() {
        if (depends == null) {
            depends = new ArrayList<CriteriaVO>();
        }
        return this.depends;
    }

    public List<ActionVO> getExecutions() {
        if (executions == null) {
            executions = new ArrayList<ActionVO>();
        }
        return this.executions;
    }

	public void setDepends(List<CriteriaVO> depends) {
		this.depends = depends;
	}

	public void setExecutions(List<ActionVO> executions) {
		this.executions = executions;
	}

}


text:
using System;

namespace FF9
{
	public class FF9SHOP_INFO
	{
		public Byte type;

		public Byte mode;

		public Byte mode_max;

		public Byte enter;

		public Byte come_count;

		public Byte[] pad = new Byte[3];

		public Byte shop_id;

		public Byte wipe_z;

		public Byte[] talk_text;

		public Int64 party_ct;

		public Byte[] slot_id = new Byte[8];

		public Int64 talk_z;
	}
}


text:
import Ember from 'ember';

export default Ember.Controller.extend({
  application: Ember.inject.controller(),

  thingsChanged: function() {
    console.log(this.get('application.currentRouteName'),this.get('model.hosts.length'),this.get('model.services.length'));
    if ( this.get('application.currentRouteName') === 'splash')
    {
      if ( this.get('model.hosts.length') && this.get('model.services.length') )
      {
        this.replaceRoute('environments');
      }
    }
  }.observes('model.hosts.length','model.services.length'),

  actions: {
    newService() {
      var environmentId = this.get('model.environmentId');

      if ( environmentId )
      {
        this.transitionToRoute('service.new', {queryParams: {environmentId: environmentId}});
      }
      else
      {
        var env = this.get('store').createRecord({
          type: 'environment',
          name: 'Default',
        });

        return env.save().then(() => {
          this.transitionToRoute('service.new', {queryParams: {environmentId: env.get('id') }});
        });
      }
    },
  },
});


text:
#include <aws/route53domains/model/UpdateDomainNameserversResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/UnreferencedParam.h>

#include <utility>

using namespace Aws::Route53Domains::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;

UpdateDomainNameserversResult::UpdateDomainNameserversResult()
{
}

UpdateDomainNameserversResult::UpdateDomainNameserversResult(const AmazonWebServiceResult<JsonValue>& result)
{
  *this = result;
}

UpdateDomainNameserversResult& UpdateDomainNameserversResult::operator =(const AmazonWebServiceResult<JsonValue>& result)
{
  const JsonValue& jsonValue = result.GetPayload();
  if(jsonValue.ValueExists("OperationId"))
  {
    m_operationId = jsonValue.GetString("OperationId");

  }

  return *this;
}


text:
import { Injectable } from '@angular/core';

@Injectable()
export class AudioService {

  audio = "assets/ice-bell.mp3";

  constructor() { }

  getAudio() {
    return this.audio;
  }

}


text:
- Mejorar en el aprendizaje y conocimiento sobre patrones de diseño
- Mejorar en el manejo y uso de la filosofía `T.D.D.` y su mantra `Red-Green-Refactor`

## Especificaciones

Resuelve los siguientes ejercicios propuestos utilizando los patrones de diseño correspondientes.

Asegúrate de generar las respectivas pruebas unitarias que satisfagan la implementación propuesta para cada patrón. Idealmente deberías de seguir la filosofía `T.D.D.`, pero puedes sentirte libre de hacerlo de la manera contraria, siempre y cuando adjuntes la suite de pruebas unitarias para cada ejercicio.

### Ejercicio 1

**Composite Pattern:** <https://refactoring.guru/es/design-patterns/composite>.

Suponga que tiene un sistema de archivos tipo [UNIX](http://math.uprm.edu/~luis/courses/unix/images/jerarquia.gif). El funcionamiento de este tipo de sistema de archivos es comúnmente representado por medio de una estructura de datos de tipo árbol jerárquico. Cada directorio puede contener 0 o varios directorios, pero también 0 o varios archivos. El principal objetivo es moverse a través del sistema de archivos de manera sencilla, mientras se puede tener ubicado cada archivo a través de una ruta, justo como se haría si te movieras a través de la misma terminal.

Partiendo del código inicial en el archivo [composite.py](composite.py), implementa el patrón de diseño `Composite` para ilustrar este ejemplo.

### Ejercicio 2

**Prototype Pattern:** <https://refactoring.guru/es/design-patterns/prototype>.

Partiendo del código base en el archivo [prototype.py](prototype.py), supongamos que se crea una instancia de la clase `Oveja` con el nombre de `Dolly`, ¿qué lógica de código necesitaríamos implementar para poder clonar a esta instancia de la clase `Oveja`?

Implementa el patrón de diseño `Prototype` para ilustrar este ejemplo.

### Ejercicio 3

**Template Method Pattern:** <https://refactoring.guru/es/design-patterns/template-method>.

Implementa el patrón de diseño `Templated Method` para el siguiente diagrama UML:

![Templated Method](template-method.png)

### Ejercicio 4

**Visitor Pattern:** <https://refactoring.guru/es/design-patterns/visitor>.

...

### Ejercicio 5

**Factory Method Pattern:** <https://refactoring.guru/es/design-patterns/factory-method>.

Implementa el patrón de diseño `Factory Method` para el diagrama UML propuesto en la sección de "_Pseudocódigo_" de la página de Refactoring Guru.

## Deadline

- `Domingo 13 de Marzo a las 11:59pm`


text:
package org.apache.lucene.index;

import java.io.IOException;

import org.apache.lucene.codecs.DocValuesConsumer;
import org.apache.lucene.search.similarities.Similarity;

final class NormsConsumerPerField extends InvertedDocEndConsumerPerField implements Comparable<NormsConsumerPerField> {
  private final FieldInfo fieldInfo;
  private final DocumentsWriterPerThread.DocState docState;
  private final Similarity similarity;
  private final FieldInvertState fieldState;
  private NumericDocValuesWriter consumer;

  public NormsConsumerPerField(final DocInverterPerField docInverterPerField, final FieldInfo fieldInfo, NormsConsumer parent) {
    this.fieldInfo = fieldInfo;
    docState = docInverterPerField.docState;
    fieldState = docInverterPerField.fieldState;
    similarity = docState.similarity;
  }

  @Override
  public int compareTo(NormsConsumerPerField other) {
    return fieldInfo.name.compareTo(other.fieldInfo.name);
  }

  @Override
  void finish() throws IOException {
    if (fieldInfo.isIndexed() && !fieldInfo.omitsNorms()) {
      if (consumer == null) {
        fieldInfo.setNormValueType(FieldInfo.DocValuesType.NUMERIC);
        consumer = new NumericDocValuesWriter(fieldInfo, docState.docWriter.bytesUsed);
      }
      consumer.addValue(docState.docID, similarity.computeNorm(fieldState));
    }
  }

  void flush(SegmentWriteState state, DocValuesConsumer normsWriter) throws IOException {
    int docCount = state.segmentInfo.getDocCount();
    if (consumer == null) {
      return; // null type - not omitted but not written -
              // meaning the only docs that had
              // norms hit exceptions (but indexed=true is set...)
    }
    consumer.finish(docCount);
    consumer.flush(state, normsWriter);
  }

  boolean isEmpty() {
    return consumer == null;
  }

  @Override
  void abort() {
    //
  }
}


text:
#include "syshdrs.h"
#ifdef PRAGMA_HDRSTOP
#	pragma hdrstop
#endif

/* We only use STAT to see if files or directories exist.
 * But since it is so rarely used in the wild, we need to
 * make sure the server supports the use where we pass
 * a pathname as a parameter.
 */
int
FTPFileExistsStat(const FTPCIPtr cip, const char *const file)
{
	int result;
	ResponsePtr rp;
	FTPLineList fileList;
	char savedCwd[512];

	if (cip == NULL)
		return (kErrBadParameter);
	if (strcmp(cip->magic, kLibraryMagic))
		return (kErrBadMagic);

	if (file == NULL)
		return (kErrBadParameter);

	if (cip->STATfileParamWorks == kCommandNotAvailable) {
		cip->errNo = result = kErrSTATwithFileNotAvailable;
		return (result);
	}

	if (cip->STATfileParamWorks == kCommandAvailabilityUnknown) {
		rp = InitResponse();
		if (rp == NULL) {
			result = kErrMallocFailed;
			cip->errNo = kErrMallocFailed;
			FTPLogError(cip, kDontPerror, "Malloc failed.\n");
			return (result);

		}

		/* First, make sure that when we STAT a pathname
		 * that does not exist, that we get an error back.
		 *
		 * We also assume that a valid STAT response has
		 * at least 3 lines of response text, typically
		 * a "start" line, intermediate data, and then
		 * a trailing line.
		 *
		 * We also can see a one-line case.
		 */
		result = RCmd(cip, rp, "STAT %s", "NoSuchFile");
		if ((result == 2) && ((rp->msg.nLines >= 3) || (rp->msg.nLines == 1))) {
			/* Hmmm.... it gave back a positive
			 * response.  So STAT <file> does not
			 * work correctly.
			 */
			if (
				(rp->msg.first->next != NULL) &&
				(rp->msg.first->next->line != NULL) &&
				(
					(strstr(rp->msg.first->next->line, "o such file") != NULL) ||
					(strstr(rp->msg.first->next->line, "ot found") != NULL)
				)
			) {
				/* OK, while we didn't want a 200
				 * level response, some servers,
				 * like wu-ftpd print an error
				 * message "No such file or
				 * directory" which we can special
				 * case.
				 */
				result = kNoErr;
			} else {
				cip->STATfileParamWorks = kCommandNotAvailable;
				cip->errNo = result = kErrSTATwithFileNotAvailable;
				DoneWithResponse(cip, rp);
				return (result);
			}
		}
		DoneWithResponse(cip, rp);

		/* We can't assume that we can simply say STAT rootdir/firstfile,
		 * since the remote host may not be using / as a directory
		 * delimiter.  So we have to change to the root directory
		 * and then do the STAT on that file.
		 */
		if (
			(FTPGetCWD(cip, savedCwd, sizeof(savedCwd)) != kNoErr) ||
			(FTPChdir(cip, cip->startingWorkingDirectory) != kNoErr)
		) {
			return (cip->errNo);
		}

		/* OK, we get an error when we stat
		 * a non-existant file, but now we need to
		 * see if we get a positive reply when
		 * we stat a file that does exist.
		 *
		 * To do this, we list the root directory,
		 * which we assume has one or more items.
		 * If it doesn't, the user can't do anything
		 * anyway.  Then we stat the first item
		 * we found to see if STAT says it exists.
		 */
		if (
			((result = FTPListToMemory2(cip, "", &fileList, "", 0, (int *) 0)) < 0) ||
			(fileList.last == NULL) ||
			(fileList.last->line == NULL)
		) {
			/* Hmmm... well, in any case we can't use STAT. */
			cip->STATfileParamWorks = kCommandNotAvailable;
			cip->errNo = result = kErrSTATwithFileNotAvailable;
			DisposeLineListContents(&fileList);
			(void) FTPChdir(cip, savedCwd);
			return (result);
		}

		rp = InitResponse();
		if (rp == NULL) {
			result = kErrMallocFailed;
			cip->errNo = kErrMallocFailed;
			FTPLogError(cip, kDontPerror, "Malloc failed.\n");
			DisposeLineListContents(&fileList);
			(void) FTPChdir(cip, savedCwd);
			return (result);

		}

		result = RCmd(cip, rp, "STAT %s", fileList.last->line);
		DisposeLineListContents(&fileList);

		if ((result != 2) || (rp->msg.nLines == 2)) {
			/* Hmmm.... it gave back a negative
			 * response.  So STAT <file> does not
			 * work correctly.
			 */
			cip->STATfileParamWorks = kCommandNotAvailable;
			cip->errNo = result = kErrSTATwithFileNotAvailable;
			DoneWithResponse(cip, rp);
			(void) FTPChdir(cip, savedCwd);
			return (result);
		} else if (
				(rp->msg.first->next != NULL) &&
				(rp->msg.first->next->line != NULL) &&
				(
					(strstr(rp->msg.first->next->line, "o such file") != NULL) ||
					(strstr(rp->msg.first->next->line, "ot found") != NULL)
				)
		) {
			/* Same special-case of the second line of STAT response. */
			cip->STATfileParamWorks = kCommandNotAvailable;
			cip->errNo = result = kErrSTATwithFileNotAvailable;
			DoneWithResponse(cip, rp);
			(void) FTPChdir(cip, savedCwd);
			return (result);
		}
		DoneWithResponse(cip, rp);
		cip->STATfileParamWorks = kCommandAvailable;

		/* Don't forget to change back to the original directory. */
		(void) FTPChdir(cip, savedCwd);
	}

	rp = InitResponse();
	if (rp == NULL) {
		result = kErrMallocFailed;
		cip->errNo = kErrMallocFailed;
		FTPLogError(cip, kDontPerror, "Malloc failed.\n");
		return (result);
	}

	result = RCmd(cip, rp, "STAT %s", file);
	if (result == 2) {
		result = kNoErr;
		if (((rp->msg.nLines >= 3) || (rp->msg.nLines == 1))) {
			if (
				(rp->msg.first->next != NULL) &&
				(rp->msg.first->next->line != NULL) &&
				(
					(strstr(rp->msg.first->next->line, "o such file") != NULL) ||
					(strstr(rp->msg.first->next->line, "ot found") != NULL)
				)
			) {
				cip->errNo = kErrSTATFailed;
				result = kErrSTATFailed;
			} else {
				result = kNoErr;
			}
		} else if (rp->msg.nLines == 2) {
			cip->errNo = kErrSTATFailed;
			result = kErrSTATFailed;
		} else {
			result = kNoErr;
		}
	} else {
		cip->errNo = kErrSTATFailed;
		result = kErrSTATFailed;
	}
	DoneWithResponse(cip, rp);
	return (result);
}	/* FTPFileExistsStat */

/* We only use STAT to see if files or directories exist.
 * But since it is so rarely used in the wild, we need to
 * make sure the server supports the use where we pass
 * a pathname as a parameter.
 */
int
FTPFileExistsNlst(const FTPCIPtr cip, const char *const file)
{
	int result;
	FTPLineList fileList, rootFileList;
	char savedCwd[512];
	int createdTempFile;
#define kFTPFileExistsNlstTestMessage "This file was created by an FTP client program using the LibNcFTP toolkit.  A temporary file needed to be created to ensure that this directory was not empty, so that the directory could be listed with the guarantee of at least one file in the listing.\r\n\r\nYou may delete this file manually if your FTP client program does not delete it for you.\r\n"
	const char *testFileMessage = kFTPFileExistsNlstTestMessage;
#undef kFTPFileExistsNlstTestMessage
	const char *testFileName = "testfile.ftp";

	if (cip == NULL)
		return (kErrBadParameter);
	if (strcmp(cip->magic, kLibraryMagic))
		return (kErrBadMagic);

	if (file == NULL)
		return (kErrBadParameter);

	if (cip->NLSTfileParamWorks == kCommandNotAvailable) {
		cip->errNo = result = kErrNLSTwithFileNotAvailable;
		return (result);
	}

	if (cip->NLSTfileParamWorks == kCommandAvailabilityUnknown) {
		/* First, make sure that when we NLST a pathname
		 * that does not exist, that we get an error back.
		 *
		 * We also assume that a valid NLST response has
		 * at least 3 lines of response text, typically
		 * a "start" line, intermediate data, and then
		 * a trailing line.
		 *
		 * We also can see a one-line case.
		 */
		if (
			((FTPListToMemory2(cip, "NoSuchFile", &fileList, "", 0, (int *) 0)) == kNoErr) &&
			(fileList.nLines >= 1) &&
			(strstr(fileList.last->line, "o such file") == NULL) &&
			(strstr(fileList.last->line, "ot found") == NULL) &&
			(strstr(fileList.last->line, "o Such File") == NULL) &&
			(strstr(fileList.last->line, "ot Found") == NULL)

		) {
			cip->NLSTfileParamWorks = kCommandNotAvailable;
			cip->errNo = result = kErrNLSTwithFileNotAvailable;
			DisposeLineListContents(&fileList);
			return (result);
		}
		DisposeLineListContents(&fileList);

		/* We can't assume that we can simply say NLST rootdir/firstfile,
		 * since the remote host may not be using / as a directory
		 * delimiter.  So we have to change to the root directory
		 * and then do the NLST on that file.
		 */
		if (
			(FTPGetCWD(cip, savedCwd, sizeof(savedCwd)) != kNoErr) ||
			(FTPChdir(cip, cip->startingWorkingDirectory) != kNoErr)
		) {
			return (cip->errNo);
		}

		/* OK, we get an error when we list
		 * a non-existant file, but now we need to
		 * see if we get a positive reply when
		 * we stat a file that does exist.
		 *
		 * To do this, we list the root directory,
		 * which we assume has one or more items.
		 * If it doesn't, the user can't do anything
		 * anyway.  Then we do the first item
		 * we found to see if NLST says it exists.
		 */
		createdTempFile = 0;
		if (
			((result = FTPListToMemory2(cip, "", &rootFileList, "", 0, (int *) 0)) < 0) ||
			(rootFileList.last == NULL) ||
			(rootFileList.last->line == NULL)
		) {
			if (AddLine(&rootFileList, testFileName) != NULL) {
				/* Hate to do this, but if the directory
				 * is empty but writable (i.e. a $HOME)
				 * then we can still continue.
				 */
				if (FTPPutFileFromMemory(cip, testFileName, testFileMessage, strlen(testFileMessage), kAppendNo) == kNoErr) {
					createdTempFile = 1;
				}
			}
			if (createdTempFile == 0) {
				/* Hmmm... well, in any case we can't use NLST. */
				cip->NLSTfileParamWorks = kCommandNotAvailable;
				cip->errNo = result = kErrNLSTwithFileNotAvailable;
				DisposeLineListContents(&rootFileList);
				(void) FTPChdir(cip, savedCwd);
				return (result);
			}
		}

		if (
			((FTPListToMemory2(cip, rootFileList.last->line, &fileList, "", 0, (int *) 0)) == kNoErr) &&
			(fileList.nLines >= 1) &&
			(strstr(fileList.last->line, "o such file") == NULL) &&
			(strstr(fileList.last->line, "ot found") == NULL) &&
			(strstr(fileList.last->line, "o Such File") == NULL) &&
			(strstr(fileList.last->line, "ot Found") == NULL)

		) {
			/* Good.  We listed the item. */
			if (createdTempFile != 0)
				(void) FTPDelete(cip, testFileName, kRecursiveNo, kGlobNo);
			DisposeLineListContents(&fileList);
			DisposeLineListContents(&rootFileList);
			cip->NLSTfileParamWorks = kCommandAvailable;

			/* Don't forget to change back to the original directory. */
			(void) FTPChdir(cip, savedCwd);
		} else {
			if (createdTempFile != 0)
				(void) FTPDelete(cip, testFileName, kRecursiveNo, kGlobNo);
			cip->NLSTfileParamWorks = kCommandNotAvailable;
			cip->errNo = result = kErrNLSTwithFileNotAvailable;
			DisposeLineListContents(&fileList);
			DisposeLineListContents(&rootFileList);
			(void) FTPChdir(cip, savedCwd);
			return (result);
		}
	}

	/* Check the requested item. */
	InitLineList(&fileList);
	if (
		((FTPListToMemory2(cip, file, &fileList, "", 0, (int *) 0)) == kNoErr) &&
		(fileList.nLines >= 1) &&
		(strstr(fileList.last->line, "o such file") == NULL) &&
		(strstr(fileList.last->line, "ot found") == NULL) &&
		(strstr(fileList.last->line, "o Such File") == NULL) &&
		(strstr(fileList.last->line, "ot Found") == NULL)

	) {
		/* The item existed. */
		result = kNoErr;
	} else {
		cip->errNo = kErrNLSTFailed;
		result = kErrNLSTFailed;
	}

	DisposeLineListContents(&fileList);
	return (result);
}	/* FTPFileExistsNlst*/

/* This functions goes to a great deal of trouble to try and determine if the
 * remote file specified exists.  Newer servers support commands that make
 * it relatively inexpensive to find the answer, but older servers do not
 * provide a standard way.  This means we may try a whole bunch of things,
 * but the good news is that the library saves information about which things
 * worked so if you do this again it uses the methods that work.
 */
int
FTPFileExists2(const FTPCIPtr cip, const char *const file, const int tryMDTM, const int trySIZE, const int tryMLST, const int trySTAT, const int tryNLST)
{
	int result;
	time_t mdtm;
	longest_int size;
	MLstItem mlsInfo;

	if (tryMDTM != 0) {
		result = FTPFileModificationTime(cip, file, &mdtm);
		if (result == kNoErr)
			return (kNoErr);
		if (result == kErrMDTMFailed) {
			cip->errNo = kErrNoSuchFileOrDirectory;
			return (kErrNoSuchFileOrDirectory);
		}
		/* else keep going */
	}

	if (trySIZE != 0) {
		result = FTPFileSize(cip, file, &size, kTypeBinary);
		if (result == kNoErr)
			return (kNoErr);
		/* SIZE could fail if the server does
		 * not support it for directories.
		 *
		 * if (result == kErrSIZEFailed)
		 *	return (kErrNoSuchFileOrDirectory);
		 */
		/* else keep going */
	}

	if (tryMLST != 0) {
		result = FTPMListOneFile(cip, file, &mlsInfo);
		if (result == kNoErr)
			return (kNoErr);
		if (result == kErrMLSTFailed) {
			cip->errNo = kErrNoSuchFileOrDirectory;
			return (kErrNoSuchFileOrDirectory);
		}
		/* else keep going */
	}

	if (trySTAT != 0) {
		result = FTPFileExistsStat(cip, file);
		if (result == kNoErr)
			return (kNoErr);
		if (result == kErrSTATFailed) {
			cip->errNo = kErrNoSuchFileOrDirectory;
			return (kErrNoSuchFileOrDirectory);
		}
		/* else keep going */
	}

	if (tryNLST != 0) {
		result = FTPFileExistsNlst(cip, file);
		if (result == kNoErr)
			return (kNoErr);
		if (result == kErrNLSTFailed) {
			cip->errNo = kErrNoSuchFileOrDirectory;
			return (kErrNoSuchFileOrDirectory);
		}
		/* else keep going */
	}

	cip->errNo = kErrCantTellIfFileExists;
	return (kErrCantTellIfFileExists);
}	/* FTPFileExists2 */

int
FTPFileExists(const FTPCIPtr cip, const char *const file)
{
	return (FTPFileExists2(cip, file, 1, 1, 1, 1, 1));
}	/* FTPFileExists */


text:
package org.kie.workbench.common.screens.server.management.client.navigation;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.Event;
import javax.enterprise.event.Observes;
import javax.inject.Inject;

import org.kie.server.controller.api.model.events.ServerTemplateUpdated;
import org.kie.server.controller.api.model.spec.ServerTemplate;
import org.kie.server.controller.api.model.spec.ServerTemplateKey;
import org.kie.workbench.common.screens.server.management.client.events.AddNewServerTemplate;
import org.kie.workbench.common.screens.server.management.client.events.ServerTemplateListRefresh;
import org.kie.workbench.common.screens.server.management.client.events.ServerTemplateSelected;
import org.slf4j.Logger;
import org.uberfire.client.mvp.UberView;

import static org.kie.soup.commons.validation.PortablePreconditions.*;

@ApplicationScoped
public class ServerNavigationPresenter {

    public interface View extends UberView<ServerNavigationPresenter> {

        void addTemplate(final String id,
                         final String name);

        void select(final String id);

        void clean();
    }

    private final Logger logger;
    private final View view;

    private final Event<AddNewServerTemplate> addNewServerTemplateEvent;
    private final Event<ServerTemplateListRefresh> serverTemplateListRefreshEvent;
    private final Event<ServerTemplateSelected> serverTemplateSelectedEvent;

    private Set<String> serverTemplates = new HashSet<String>();

    @Inject
    public ServerNavigationPresenter(final Logger logger,
                                     final View view,
                                     final Event<AddNewServerTemplate> addNewServerTemplateEvent,
                                     final Event<ServerTemplateListRefresh> serverTemplateListRefreshEvent,
                                     final Event<ServerTemplateSelected> serverTemplateSelectedEvent) {
        this.logger = logger;
        this.view = view;
        this.addNewServerTemplateEvent = addNewServerTemplateEvent;
        this.serverTemplateListRefreshEvent = serverTemplateListRefreshEvent;
        this.serverTemplateSelectedEvent = serverTemplateSelectedEvent;
    }

    @PostConstruct
    public void init() {
        view.init(this);
    }

    public View getView() {
        return view;
    }

    public void setup(final ServerTemplateKey firstTemplate,
                      final Collection<ServerTemplateKey> serverTemplateKeys) {
        view.clean();
        serverTemplates.clear();
        addTemplate(checkNotNull("serverTemplate2BeSelected",
                                 firstTemplate));
        for (final ServerTemplateKey serverTemplateKey : serverTemplateKeys) {
            if (!serverTemplateKey.equals(firstTemplate)) {
                addTemplate(serverTemplateKey);
            }
        }
    }

    private void addTemplate(final ServerTemplateKey serverTemplateKey) {
        checkNotNull("serverTemplateKey",
                     serverTemplateKey);
        serverTemplates.add(serverTemplateKey.getId());
        this.view.addTemplate(serverTemplateKey.getId(),
                              serverTemplateKey.getName());
    }

    public void onSelect(@Observes final ServerTemplateSelected serverTemplateSelected) {
        if (serverTemplateSelected != null &&
                serverTemplateSelected.getServerTemplateKey() != null &&
                serverTemplateSelected.getServerTemplateKey().getId() != null) {
            view.select(serverTemplateSelected.getServerTemplateKey().getId());
        } else {
            logger.warn("Illegal event argument.");
        }
    }

    public void onServerTemplateUpdated(@Observes final ServerTemplateUpdated serverTemplateUpdated) {
        if (serverTemplateUpdated != null &&
                serverTemplateUpdated.getServerTemplate() != null) {
            final ServerTemplate serverTemplate = serverTemplateUpdated.getServerTemplate();
            if (!serverTemplates.contains(serverTemplate.getId())) {
                addTemplate(serverTemplate);
            }
        } else {
            logger.warn("Illegal event argument.");
        }
    }

    public void select(final String id) {
        serverTemplateSelectedEvent.fire(new ServerTemplateSelected(new ServerTemplateKey(id,
                                                                                "")));
    }

    public void clear() {
        view.clean();
    }

    public void refresh() {
        serverTemplateListRefreshEvent.fire(new ServerTemplateListRefresh());
    }

    public void newTemplate() {
        addNewServerTemplateEvent.fire(new AddNewServerTemplate());
    }
}


text:
package com.google.common.collect;

import static com.google.common.truth.Truth.assertThat;

import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Optional;
import com.google.common.testing.NullPointerTester;

import junit.framework.TestCase;

import java.util.Arrays;
import java.util.List;

import javax.annotation.Nullable;

/**
 * Tests for {@code TreeTraverser}.
 *
 * @author Louis Wasserman
 */
@GwtCompatible(emulated = true)
public class TreeTraverserTest extends TestCase {
  private static final class Tree {
    final char value;
    final List<Tree> children;

    public Tree(char value, Tree... children) {
      this.value = value;
      this.children = Arrays.asList(children);
    }
  }

  private static final class BinaryTree {
    final char value;
    @Nullable
    final BinaryTree left;
    @Nullable
    final BinaryTree right;

    private BinaryTree(char value, BinaryTree left, BinaryTree right) {
      this.value = value;
      this.left = left;
      this.right = right;
    }
  }

  private static final TreeTraverser<Tree> ADAPTER = new TreeTraverser<Tree>() {
    @Override
    public Iterable<Tree> children(Tree node) {
      return node.children;
    }
  };

  private static final BinaryTreeTraverser<BinaryTree> BIN_ADAPTER =
      new BinaryTreeTraverser<BinaryTree>() {

    @Override
    public Optional<BinaryTree> leftChild(BinaryTree node) {
      return Optional.fromNullable(node.left);
    }

    @Override
    public Optional<BinaryTree> rightChild(BinaryTree node) {
      return Optional.fromNullable(node.right);
    }
  };

  //        h
  //      / | \
  //     /  e  \
  //    d       g
  //   /|\      |
  //  / | \     f
  // a  b  c
  static final Tree a = new Tree('a');
  static final Tree b = new Tree('b');
  static final Tree c = new Tree('c');
  static final Tree d = new Tree('d', a, b, c);
  static final Tree e = new Tree('e');
  static final Tree f = new Tree('f');
  static final Tree g = new Tree('g', f);
  static final Tree h = new Tree('h', d, e, g);

  //      d
  //     / \
  //    b   e
  //   / \   \
  //  a   c   f
  //         /
  //        g
  static final BinaryTree ba = new BinaryTree('a', null, null);
  static final BinaryTree bc = new BinaryTree('c', null, null);
  static final BinaryTree bb = new BinaryTree('b', ba, bc);
  static final BinaryTree bg = new BinaryTree('g', null, null);
  static final BinaryTree bf = new BinaryTree('f', bg, null);
  static final BinaryTree be = new BinaryTree('e', null, bf);
  static final BinaryTree bd = new BinaryTree('d', bb, be);

  static String iterationOrder(Iterable<Tree> iterable) {
    StringBuilder builder = new StringBuilder();
    for (Tree t : iterable) {
      builder.append(t.value);
    }
    return builder.toString();
  }

  static String binaryIterationOrder(Iterable<BinaryTree> iterable) {
    StringBuilder builder = new StringBuilder();
    for (BinaryTree t : iterable) {
      builder.append(t.value);
    }
    return builder.toString();
  }

  public void testPreOrder() {
    assertThat(iterationOrder(ADAPTER.preOrderTraversal(h))).isEqualTo("hdabcegf");
    assertThat(binaryIterationOrder(BIN_ADAPTER.preOrderTraversal(bd))).isEqualTo("dbacefg");
  }

  public void testPostOrder() {
    assertThat(iterationOrder(ADAPTER.postOrderTraversal(h))).isEqualTo("abcdefgh");
    assertThat(binaryIterationOrder(BIN_ADAPTER.postOrderTraversal(bd))).isEqualTo("acbgfed");
  }

  public void testBreadthOrder() {
    assertThat(iterationOrder(ADAPTER.breadthFirstTraversal(h))).isEqualTo("hdegabcf");
    assertThat(binaryIterationOrder(BIN_ADAPTER.breadthFirstTraversal(bd))).isEqualTo("dbeacfg");
  }

  public void testInOrder() {
    assertThat(binaryIterationOrder(BIN_ADAPTER.inOrderTraversal(bd))).isEqualTo("abcdegf");
  }

  @GwtIncompatible("NullPointerTester")
  public void testNulls() {
    NullPointerTester tester = new NullPointerTester();
    tester.testAllPublicInstanceMethods(ADAPTER);
    tester.testAllPublicInstanceMethods(BIN_ADAPTER);
  }
}


text:
const attachmentDal = require('./dal');
const urls = require('georap-urls-server');
const status = require('http-status-codes');
const uploads = require('../../../services/uploads');

exports.get = (req, res) => {
  // Fetch single attachment.
  // Already feched but here it is a good place to strip any unnecesary data.
  const attachmentWithUrls = urls.completeAttachment(req.attachment);
  return res.json(attachmentWithUrls);
};

exports.rotateImage = (req, res, next) => {
  // Try to rotate photo attachment.
  // This will create a new attachment with the rotated image.
  //
  // Response with JSON
  //   {
  //     attachment: <attachment with full urls>
  //   }
  //
  // NOTE At first, we tried to rotate images in place, overwriting the orig.
  // That had two drawbacks:
  // - identical path does not bust caches
  // - sharp cannot output image to the source path
  // Then, we tried rename the rotated file with -rot postfix and
  // update the paths in the attachment object.
  // That had one major drawback: the attachment key remained the same
  // and therefore there was no simple way to cancel the rotation
  // whenever user cancels the entry edit. Also, rotations would not
  // be visible in location_entry_changed events if key remains the same.
  // Therefore, it is better to create a brand new attachment.
  //
  const atta = req.attachment;

  // Detect if image
  if (!atta.mimetype.startsWith('image/')) {
    // No file attachment
    const msg = 'Cannot rotate ' + atta.mimetype;
    return res.status(status.BAD_REQUEST).send(msg);
  }

  // Positive for clockwise rotation.
  const degrees = parseInt(req.body.degrees, 10);
  if (isNaN(degrees)) {
    const msg = 'Invalid degree ' + degrees;
    return res.status(status.BAD_REQUEST).send(msg);
  }

  // If 0 degree, no need to rotate. Response with the same attachment
  const circle = 360;
  if (degrees % circle === 0) {
    return res.json({
      attachment: atta,
    });
  }

  const sourcePath = uploads.getAbsolutePath(atta.filepath);

  // Prepare directory for a new permanent upload.
  uploads.preparePermanent(sourcePath, (errp, targetPath) => {
    if (errp) {
      return next(errp);
    }

    // Rotate
    uploads.rotateImage(sourcePath, targetPath, degrees, (err, info) => {
      if (err) {
        return next(err);
      }

      // After rotate, recreate thumbnail.
      uploads.createThumbnail({
        path: targetPath,
        mimetype: atta.mimetype,
      }, (errt, thumb) => {
        if (errt) {
          return next(errt);
        }

        const creationParams = {
          username: atta.user, // TODO should be current user?
          filepath: uploads.getRelativePath(targetPath),
          mimetype: atta.mimetype,
          filesize: info.size,
          thumbfilepath: uploads.getRelativePath(thumb.path),
          thumbmimetype: thumb.mimetype,
        };

        // Create new attachment
        attachmentDal.create(creationParams, (errc, newAttachment) => {
          if (errc) {
            return next(errc);
          }

          return res.json({
            attachment: urls.completeAttachment(newAttachment),
          });
        });
      });
    });
  });
};

exports.remove = (req, res, next) => {
  // Remove an attachment
  const key = req.attachment.key;

  attachmentDal.remove({
    key: key,
  }, (err) => {
    if (err) {
      return next(err);
    }
    return res.json({
      removed: 1, // TODO actual value from mongo
    });
  });
};


text:
<?php

require_once __DIR__ . '/SplClassLoader.php';

$classLoader = new SplClassLoader('GA', dirname(__FILE__) . '/lib');
$classLoader->register();


text:
```js
angular.module('myModule', ['oui.list']);
```


text:
Amit Singhal's Home Page

Amit Singhal

Department of Computer Science,
Cornell University

singhal@cs.cornell.edu
Phone: 607/255-9211, Fax: 607/255-4428

My research interests are in the area of information retrieval and
text processing. My thesis advisor was (late) Prof. Gerard
Salton. My current thesis supervisors are Dr. Chris Buckley and Prof. Claire
Cardie

Here is a postscript copy of my resume.

The Smart group at Cornell CS department has been
one of the foremost research groups in the field of information
retrieval for last thirty years. Our current research involves:

Document Length Normalization in Information Retrieval

 To fairly retrieve texts of varying sizes, document length
normalization is commonly used in term weighting. We show that
effective systems should retrieve documents of all sizes with chances
similar to their likelihood of relevance. We propose pivoting,
a new technique that can be used to modify existing normalization
functions to yield substantial improvements in retrieval
effectiveness. We also propose a new and effective normalization
technique.Some papers ...

Our TREC
Participation

Text REtrieval Conference (TREC) is a NIST and ARPA co-sponsored
effort to objectively evaluate various information retrieval
techniques on an independent testbed. The Smart system has
consistently been one of the best systems at TREC.Some
papers ...

Automatic Text Structuring and Summarization

Non expository texts are not usually read from cover to
cover. Readers are helped in such circumstances by providing selective
access to text excerpts as needed. We have developed techniques to
analyze the structure of a text and provide tools for selective text
traversal.Some papers ...

Papers

Normalization papers:

Pivoted Document Length Normalization.  Amit Singhal, Chris Buckley, Mandar
Mitra, (Gerard Salton). (TR95-1560)

Document
Length Normalization. Amit Singhal, Gerard Salton, Mandar Mitra
and Chris Buckley. (TR95-1529)

Length
Normalization in Degraded Text Collections. Amit Singhal, Gerard
Salton and Chris Buckley. (TR95-1507)

TREC papers:

 Coming soon: New Retrieval Approaches Using
SMART: TREC 4. Chris Buckley, Amit Singhal, Mandar
Mitra, (Gerard Salton).

Automatic Query Expansion Using SMART: TREC 3. Chris Buckley,
Gerard Salton, James Allan, and Amit Singhal. In Proceedings
of the Third Text Retrieval Conference, NIST Special Publication
500-225, 69-80.

Text structuring papers:

Automatic Text Decomposition Using Text Segments and Text
Themes.  Gerard Salton, Amit Singhal, Chris Buckley, and Mandar Mitra,
Hypertext '96 (to appear). (TR95-1555)

 Automatic Text Decomposition and Structuring. Gerard Salton,
James Allan, and Amit Singhal, Information Processing and
Management (to appear).

Automatic Text Browsing Using Vector
Space Model. Amit Singhal and Gerard Salton. In Proceedings of
the Dual-Use Technologies and Applications Conference, May 1995,
318-324.

Selective Text Traversal. Gerard Salton and Amit Singhal. (TR95-1549)

Automatic Text Theme Generation and the Analysis of Text Structure.
Gerard Salton and Amit Singhal. (TR94-1438)

Automatic Analysis, Theme Generation, and Summarization of Machine
Readable Texts. Gerard Salton, James Allan, Chris Buckley, and Amit
Singhal, Science 264 (3 June, 1994), 1421-1426.

Smart Group

Members of the Smart group are:

Chris Buckley, senior research associate;
Amit Singhal, Ph.D. student;
Mandar Mitra, Ph.D. student;
David Fielding, Masters of Engineering student;

and others as the group slowly fluctuates.

  Thanks for visiting my home page. You are visitor  since Nov. 30, 1995 (that's when I
installed this counter :-).


text:
package com.phloc.commons.error;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import com.phloc.commons.mock.PhlocTestUtils;

/**
 * Test class for class {@link ResourceLocation}.
 *
 * @author Philip Helger
 */
public final class ResourceLocationTest
{
  @Test
  public void testBasic ()
  {
    ResourceLocation re = new ResourceLocation ("xx", "field");
    assertEquals ("xx", re.getResourceID ());
    assertEquals (IResourceLocation.ILLEGAL_NUMBER, re.getLineNumber ());
    assertEquals (IResourceLocation.ILLEGAL_NUMBER, re.getColumnNumber ());
    assertEquals ("field", re.getField ());
    assertEquals ("xx @ field", re.getAsString ());

    re = new ResourceLocation ("xx", 5, IResourceLocation.ILLEGAL_NUMBER, "field");
    assertEquals ("xx", re.getResourceID ());
    assertEquals (5, re.getLineNumber ());
    assertEquals (IResourceLocation.ILLEGAL_NUMBER, re.getColumnNumber ());
    assertEquals ("field", re.getField ());
    assertEquals ("xx(5:?) @ field", re.getAsString ());

    re = new ResourceLocation ("xx", 5, 7, "field");
    assertEquals ("xx", re.getResourceID ());
    assertEquals (5, re.getLineNumber ());
    assertEquals (7, re.getColumnNumber ());
    assertEquals ("field", re.getField ());
    assertEquals ("xx(5:7) @ field", re.getAsString ());

    PhlocTestUtils.testDefaultImplementationWithEqualContentObject (new ResourceLocation ("xx", "field"),
                                                                    new ResourceLocation ("xx", "field"));
    PhlocTestUtils.testDefaultImplementationWithDifferentContentObject (new ResourceLocation ("xx", "field"),
                                                                        new ResourceLocation ("xx2", "field"));
    PhlocTestUtils.testDefaultImplementationWithDifferentContentObject (new ResourceLocation ("xx", "field"),
                                                                        new ResourceLocation ("xx", "field2"));
    PhlocTestUtils.testDefaultImplementationWithDifferentContentObject (new ResourceLocation ("xx", 0, 1, "field"),
                                                                        new ResourceLocation ("xx", 0, 0, "field"));
    PhlocTestUtils.testDefaultImplementationWithDifferentContentObject (new ResourceLocation ("xx", 0, 1, "field"),
                                                                        new ResourceLocation ("xx", 1, 1, "field"));
  }
}


text:
import discord
from discord.ext import commands
import random

description = '''An example bot to showcase the discord.ext.commands extension
module.

There are a number of utility commands being showcased here.'''
bot = commands.Bot(command_prefix='?', description=description)

@bot.event
async def on_ready():
    print('Logged in as')
    print(bot.user.name)
    print(bot.user.id)
    print('------')

@bot.command()
async def add(ctx, left: int, right: int):
    """Adds two numbers together."""
    await ctx.send(left + right)

@bot.command()
async def roll(ctx, dice: str):
    """Rolls a dice in NdN format."""
    try:
        rolls, limit = map(int, dice.split('d'))
    except Exception:
        await ctx.send('Format has to be in NdN!')
        return

    result = ', '.join(str(random.randint(1, limit)) for r in range(rolls))
    await ctx.send(result)

@bot.command(description='For when you wanna settle the score some other way')
async def choose(ctx, *choices: str):
    """Chooses between multiple choices."""
    await ctx.send(random.choice(choices))

@bot.command()
async def repeat(ctx, times: int, content='repeating...'):
    """Repeats a message multiple times."""
    for i in range(times):
        await ctx.send(content)

@bot.command()
async def joined(ctx, member: discord.Member):
    """Says when a member joined."""
    await ctx.send('{0.name} joined in {0.joined_at}'.format(member))

@bot.group()
async def cool(ctx):
    """Says if a user is cool.

    In reality this just checks if a subcommand is being invoked.
    """
    if ctx.invoked_subcommand is None:
        await ctx.send('No, {0.subcommand_passed} is not cool'.format(ctx))

@cool.command(name='bot')
async def _bot(ctx):
    """Is the bot cool?"""
    await ctx.send('Yes, the bot is cool.')

bot.run('token')


text:
package groovy.io;

import java.io.File;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;

import org.codehaus.groovy.runtime.InvokerHelper;

/**
 * A PrintWriter that outputs objects in Groovy style.
 * That means print(Object) uses InvokerHelper.toString(Object)
 * to produce the same results as Writer.print(Object).
 *
 * @author Jim White
 * @since 1.6
 */
public class GroovyPrintWriter extends PrintWriter
{
    public GroovyPrintWriter(File file) throws FileNotFoundException
    {
        super(file);
    }

    public GroovyPrintWriter(File file, String csn)
        throws FileNotFoundException, UnsupportedEncodingException
    {
        super(file, csn);
    }

    public GroovyPrintWriter(Writer out)
    {
        super(out);
    }

    public GroovyPrintWriter(Writer out, boolean autoflush)
    {
        super(out, autoflush);
    }

    public GroovyPrintWriter(OutputStream out)
    {
        super(out);
    }

    public GroovyPrintWriter(OutputStream out, boolean autoflush)
    {
        super(out, autoflush);
    }

    public GroovyPrintWriter(String filename) throws FileNotFoundException
    {
        super(filename);
    }

    public GroovyPrintWriter(String filename, String csn)
        throws FileNotFoundException, UnsupportedEncodingException
    {
        super(filename, csn);
    }

// Don't need to do this if Groovy is going to print char[] like a string.
//    public void print(char[] x)
//    {
//        write(InvokerHelper.toString(x));
//    }

    public void print(Object x)
    {
        write(InvokerHelper.toString(x));
    }

    public void println(Object x)
    {
        // JDK 1.6 has changed the implementation to do a
        // String.valueOf(x) rather than call print(x).
        // Probably to improve performance by doing the conversion outside the lock.
        // This will do the same thing for us, and we don't have to have access to the lock.
        println(InvokerHelper.toString(x));
    }
}


text:
"""Automates creation and management of DEPS roll CLs.

This script is designed to be run in a loop (eg. with auto_roll_wrapper.sh) or
on a timer. It may take one of several actions, depending on the state of
in-progress DEPS roll CLs and the state of the repository:

- If there is already a DEPS roll CL in the Commit Queue, just exit.
- If there is an open DEPS roll CL which is not in the Commit Queue:
    - If there's a comment containing the "STOP" keyword, just exit.
    - Otherwise, close the issue and continue.
- If there is no open DEPS roll CL, create one using the
    src/tools/safely-roll-deps.py script.
"""

import datetime
import json
import optparse
import os.path
import re
import sys
import textwrap
import urllib2

SCRIPTS_DIR = os.path.realpath(os.path.join(os.path.dirname(__file__),
                                            os.pardir, os.pardir))
sys.path.insert(0, SCRIPTS_DIR)

# pylint: disable=W0611
from common import find_depot_tools

import auth
import rietveld
import scm
import subprocess2

ROLL_DESCRIPTION_STR = (
'''Roll %(dep_path)s %(before_rev)s:%(after_rev)s%(svn_range)s

Summary of changes available at:
%(revlog_url)s
''')

NO_TRY_STR = (
'''
Sheriffs: In case of breakage, do NOT revert this roll, revert the
offending commit in the %(project)s repository instead.

NOTRY=true''')

BLINK_SHERIFF_URL = (
  'http://build.chromium.org/p/chromium.webkit/sheriff_webkit.js')
CHROMIUM_SHERIFF_URL = (
  'http://build.chromium.org/p/chromium.webkit/sheriff.js')

CQ_INCLUDE_TRYBOTS = 'CQ_INCLUDE_TRYBOTS='

# Does not support unicode or special characters.
VALID_EMAIL_REGEXP = re.compile(r'^[A-Za-z0-9\.&\'\+-/=_]+@'
                                r'[A-Za-z0-9\.\-]+$')

def _get_skia_sheriff():
  """Finds and returns the current Skia sheriff."""
  skia_sheriff_url = 'https://skia-tree-status.appspot.com/current-sheriff'
  return json.load(urllib2.urlopen(skia_sheriff_url))['username']

def _complete_email(name):
  """If the name does not include '@', append '@chromium.org'."""
  if '@' not in name:
    return name + '@chromium.org'
  return name

def _names_from_sheriff_js(sheriff_js):
  match = re.match(r'document.write\(\'(.*)\'\)', sheriff_js)
  emails_string = match.group(1)
  # Detect 'none (channel is sheriff)' text and ignore it.
  if 'channel is sheriff' in emails_string.lower():
    return []
  return map(str.strip, emails_string.split(','))

def _email_is_valid(email):
  """Determines whether the given email address is valid."""
  return VALID_EMAIL_REGEXP.match(email) is not None

def _filter_emails(emails):
  """Returns the given list with any invalid email addresses removed."""
  rv = []
  for email in emails:
    if _email_is_valid(email):
      rv.append(email)
    else:
      print 'WARNING: Not including %s (invalid email address)' % email
  return rv

def _emails_from_url(sheriff_url):
  sheriff_js = urllib2.urlopen(sheriff_url).read()
  return map(_complete_email, _names_from_sheriff_js(sheriff_js))

def _current_gardener_emails():
  return _emails_from_url(BLINK_SHERIFF_URL)

def _current_sheriff_emails():
  return _emails_from_url(CHROMIUM_SHERIFF_URL)

def _do_git_fetch(git_dir):
  subprocess2.check_call(['git', '--git-dir', git_dir, 'fetch'])

PROJECT_CONFIGS = {
  'blink': {
    'extra_emails_fn': _current_gardener_emails,
    'path_to_project': os.path.join('third_party', 'WebKit'),
    'project_alias': 'webkit',
  },
  'skia': {
    'cq_extra_trybots': ['tryserver.blink:linux_blink_rel'],
    'extra_emails_fn': lambda: [_get_skia_sheriff()],
    'path_to_project': os.path.join('third_party', 'skia'),
    'include_commit_log': True,
    # 'dry_run': True,
  },
}

class AutoRollException(Exception):
  pass

class AutoRoller(object):
  RIETVELD_URL = 'https://codereview.chromium.org'
  RIETVELD_TIME_FORMAT = '%Y-%m-%d %H:%M:%S.%f'
  ROLL_TIME_LIMIT = datetime.timedelta(hours=24)
  STOP_NAG_TIME_LIMIT = datetime.timedelta(hours=12)
  ADMIN_EMAIL = 'dpranke@chromium.org'

  ROLL_DESCRIPTION_REGEXP = ROLL_DESCRIPTION_STR % {
    'dep_path': '%(project)s',
    'before_rev': '(?P<from_revision>[0-9a-fA-F]{2,40})',
    'after_rev': '(?P<to_revision>[0-9a-fA-F]{2,40})',
    'svn_range': '.*',
    'revlog_url': '.+',
  }

  # FIXME: These are taken from gardeningserver.py and should be shared.
  CHROMIUM_SVN_DEPS_URL = 'http://src.chromium.org/chrome/trunk/src/DEPS'

  ROLL_BOT_INSTRUCTIONS = textwrap.dedent(
    '''This roll was created by the Blink AutoRollBot.
    http://www.chromium.org/blink/blinkrollbot''')

  PLEASE_RESUME_NAG = textwrap.dedent('''
    Rollbot was stopped by the presence of 'STOP' in an earlier comment.
    The last update to this issue was over %(stop_nag_timeout)s hours ago.
    Please close this issue as soon as possible to allow the bot to continue.

    Please email (%(admin)s) if the Rollbot is causing trouble.
    ''' % {'admin': ADMIN_EMAIL, 'stop_nag_timeout': STOP_NAG_TIME_LIMIT})

  def __init__(self, project, author, path_to_chrome, auth_config=None,
               options=None):
    self._author = author
    self._project = project
    self._path_to_chrome = path_to_chrome
    self._rietveld = rietveld.Rietveld(
      self.RIETVELD_URL, auth_config, self._author)
    self._notry = options and options.notry
    self._cached_last_roll_revision = None

    project_config = PROJECT_CONFIGS.get(self._project, {
      'path_to_project': os.path.join('third_party', self._project),
    })
    self._project_alias = project_config.get('project_alias', self._project)
    self._path_to_project = project_config['path_to_project']
    self._get_extra_emails = project_config.get('extra_emails_fn', lambda: [])
    self._cq_extra_trybots = project_config.get('cq_extra_trybots', [])
    self._include_commit_log = project_config.get('include_commit_log', False)
    self._cq_dry_run = project_config.get('dry_run', False)

    self._chromium_git_dir = self._path_from_chromium_root('.git')
    self._project_git_dir = self._path_from_chromium_root(
        self._path_to_project, '.git')
    self._roll_description_regexp = (self.ROLL_DESCRIPTION_REGEXP % {
        'project': 'src/' + self._path_to_project
    }).splitlines()[0]

  def _parse_time(self, time_string):
    return datetime.datetime.strptime(time_string, self.RIETVELD_TIME_FORMAT)

  def _url_for_issue(self, issue_number):
    return '%s/%d/' % (self.RIETVELD_URL, issue_number)

  def _search_for_active_roll(self):
    # FIXME: Rietveld.search is broken, we should use closed=False
    # but that sends closed=1, we want closed=3.  Using closed=2
    # to that search translates it correctly to closed=3 internally.
    # https://code.google.com/p/chromium/issues/detail?id=242628
    for result in self._rietveld.search(owner=self._author, closed=2):
      if re.search(self._roll_description_regexp, result['subject']):
        return result
    return None

  def _rollbot_should_stop(self, issue):
    issue_number = issue['issue']
    for message in issue['messages']:
      if 'STOP' in message['text']:
        last_modified = self._parse_time(issue['modified'])
        time_since_last_comment = datetime.datetime.utcnow() - last_modified
        if time_since_last_comment > self.STOP_NAG_TIME_LIMIT:
          self._rietveld.add_comment(issue_number, self.PLEASE_RESUME_NAG)

        print '%s: Rollbot was stopped by %s on at %s, waiting.' % (
          self._url_for_issue(issue_number), message['sender'], message['date'])
        return True
    return False

  def _close_issue(self, issue_number, message=None):
    print 'Closing %s with message: \'%s\'' % (
      self._url_for_issue(issue_number), message)
    if message:
      self._rietveld.add_comment(issue_number, message)
    self._rietveld.close_issue(issue_number)

  def _path_from_chromium_root(self, *components):
    assert os.pardir not in components
    return os.path.join(self._path_to_chrome, *components)

  def _last_roll_revision(self):
    """Returns the revision of the last roll.

    Returns:
        revision of the last roll; either a 40-character Git commit hash or an
        SVN revision number.
    """
    if not self._cached_last_roll_revision:
      revinfo = subprocess2.check_output(['gclient', 'revinfo'],
                                         cwd=self._path_to_chrome)
      project_path = 'src/' + self._path_to_project
      for line in revinfo.splitlines():
        dep_path, source = line.split(': ', 1)
        if dep_path == project_path:
          self._cached_last_roll_revision = source.split('@')[-1]
          break
      assert len(self._cached_last_roll_revision) == 40
    return self._cached_last_roll_revision

  def _current_revision(self):
    git_revparse_cmd = ['git', '--git-dir', self._project_git_dir,
                        'rev-parse', 'origin/master']
    return subprocess2.check_output(git_revparse_cmd).rstrip()

  def _emails_to_cc_on_rolls(self):
    return _filter_emails(self._get_extra_emails())

  def _start_roll(self, last_roll_revision, new_roll_revision):
    roll_branch = '%s_roll' % self._project
    cwd_kwargs = {'cwd': self._path_to_chrome}
    subprocess2.check_call(['git', 'clean', '-d', '-f'], **cwd_kwargs)
    subprocess2.call(['git', 'rebase', '--abort'], **cwd_kwargs)
    subprocess2.call(['git', 'branch', '-D', roll_branch], **cwd_kwargs)
    subprocess2.check_call(['git', 'checkout', 'origin/master', '-f'],
                           **cwd_kwargs)
    subprocess2.check_call(['git', 'checkout', '-b', roll_branch,
                            '-t', 'origin/master', '-f'], **cwd_kwargs)
    try:
      subprocess2.check_call(['roll-dep-svn', self._path_to_project,
                              new_roll_revision], **cwd_kwargs)
      subprocess2.check_call(['git', 'add', 'DEPS'], **cwd_kwargs)
      subprocess2.check_call(['git', 'commit', '--no-edit'], **cwd_kwargs)
      commit_msg = subprocess2.check_output(
          ['git', 'log', '-n1', '--format=%B', 'HEAD'],
          **cwd_kwargs).decode('utf-8')

      if self._notry:
        commit_msg += NO_TRY_STR % { 'project': self._project }

      upload_cmd = ['git', 'cl', 'upload', '--bypass-hooks', '-f']
      if self._cq_dry_run:
        upload_cmd.append('--cq-dry-run')
      else:
        upload_cmd.append('--use-commit-queue')
      if self._cq_extra_trybots:
        commit_msg += ('\n' + CQ_INCLUDE_TRYBOTS +
                       ','.join(self._cq_extra_trybots))
      tbr = '\nTBR='
      emails = self._emails_to_cc_on_rolls()
      if emails:
        emails_str = ','.join(emails)
        tbr += emails_str
        upload_cmd.extend(['--cc', emails_str, '--send-mail'])
      commit_msg += tbr
      if self._include_commit_log:
        log_cmd = ['git', 'log', '--format=%h %ae %s',
                   '%s..%s' % (last_roll_revision, new_roll_revision)]
        git_log = subprocess2.check_output(log_cmd, cwd=self._project_git_dir)
        commit_msg += '\n\nCommits in this roll:\n' + git_log.decode('utf-8')
      upload_cmd.extend(['-m', commit_msg])
      subprocess2.check_call(upload_cmd, **cwd_kwargs)
    finally:
      subprocess2.check_call(['git', 'checkout', 'origin/master', '-f'],
                             **cwd_kwargs)
      subprocess2.check_call(
          ['git', 'branch', '-D', roll_branch], **cwd_kwargs)

    # FIXME: It's easier to pull the issue id from rietveld rather than
    # parse it from the safely-roll-deps output.  Once we inline
    # safely-roll-deps into this script this can go away.
    search_result = self._search_for_active_roll()
    if search_result:
      self._rietveld.add_comment(search_result['issue'],
          self.ROLL_BOT_INSTRUCTIONS)

  def _maybe_close_active_roll(self, issue):
    issue_number = issue['issue']

    # If the CQ failed, this roll is DOA.
    if not issue['commit']:
      self._close_issue(
          issue_number,
          'No longer marked for the CQ. Closing, will open a new roll.')
      return True

    create_time = self._parse_time(issue['created'])
    time_since_roll = datetime.datetime.utcnow() - create_time
    print '%s started %s ago' % (
      self._url_for_issue(issue_number), time_since_roll)
    if time_since_roll > self.ROLL_TIME_LIMIT:
      self._close_issue(
          issue_number,
          'Giving up on this roll after %s. Closing, will open a new roll.' %
          self.ROLL_TIME_LIMIT)
      return True

    last_roll_revision = self._short_rev(self._last_roll_revision())
    match = re.match(self._roll_description_regexp, issue['subject'])
    if match.group('from_revision') != last_roll_revision:
      self._close_issue(
          issue_number,
          'DEPS has already rolled to %s. Closing, will open a new roll.' %
          last_roll_revision)
      return True

    return False

  def _compare_revisions(self, last_roll_revision, new_roll_revision):
    """Ensure that new_roll_revision is newer than last_roll_revision."""
    # Ensure that new_roll_revision is not an ancestor of old_roll_revision.
    try:
      subprocess2.check_call(['git', '--git-dir', self._project_git_dir,
                              'merge-base', '--is-ancestor',
                              new_roll_revision, last_roll_revision])
      print ('Already at %s refusing to roll backwards to %s.' % (
                 last_roll_revision, new_roll_revision))
      return False
    except subprocess2.CalledProcessError:
      pass
    return True

  def _short_rev(self, revision):
    """Shorten a Git commit hash."""
    return subprocess2.check_output(['git', '--git-dir', self._project_git_dir,
                                     'rev-parse', '--short', revision]
                                    ).rstrip()

  def main(self):
    _do_git_fetch(self._chromium_git_dir)
    _do_git_fetch(self._project_git_dir)

    search_result = self._search_for_active_roll()
    issue_number = search_result['issue'] if search_result else None
    if issue_number:
      issue = self._rietveld.get_issue_properties(issue_number, messages=True)
    else:
      issue = None

    if issue:
      if self._rollbot_should_stop(issue):
        return 1
      if not self._maybe_close_active_roll(issue):
        print '%s is still active, nothing to do.' % \
            self._url_for_issue(issue_number)
        return 0

    last_roll_revision = self._last_roll_revision()
    new_roll_revision = self._current_revision()

    if not new_roll_revision:
      raise AutoRollException(
          'Could not determine the current revision.')

    if not self._compare_revisions(last_roll_revision, new_roll_revision):
      return 0

    self._start_roll(last_roll_revision, new_roll_revision)
    return 0

def main():
  usage = 'Usage: %prog project_name author path_to_chromium'

  # The default HelpFormatter causes the docstring to display improperly.
  class VanillaHelpFormatter(optparse.IndentedHelpFormatter):
    def format_description(self, description):
      if description:
        return description
      else:
        return ''

  parser = optparse.OptionParser(usage=usage,
                                 description=sys.modules[__name__].__doc__,
                                 formatter=VanillaHelpFormatter())

  parser.add_option('--no-try', action='store_true', dest='notry',
                    help='Create the CL with NOTRY=true')

  auth.add_auth_options(parser)
  options, args = parser.parse_args()
  auth_config = auth.extract_auth_config_from_options(options)
  if len(args) != 3:
    parser.print_usage()
    return 1

  AutoRoller(*args, auth_config=auth_config, options=options).main()

if __name__ == '__main__':
  sys.exit(main())


text:
import rangeParser from '../../src/middleware/rangeParser';
import {expect} from 'chai';
import Request from 'mock-express-request';
import Response from 'mock-express-response';
import sinon from 'sinon';

async function parseWithRangeParser(unit, range) {
    const req = new Request({
        headers: {
            'Range-Unit': unit || undefined,
            Range: range
        }
    });
    const res = new Response();
    const next = sinon.spy();
    rangeParser(req, res, next);
    next.should.have.been.calledOnce.and.calledWith();
    return req.range;
}

describe('rangeParser', function() {
    it('should be a function', function() {
        expect(rangeParser).to.exist
            .and.to.be.a('function');
    });

    it('should treat malformed range as items 0-', async function() {
        const rangeAll = {unit: 'items', first: 0, last: Infinity};
        (await parseWithRangeParser('', '')).should.deep.equal(rangeAll);
        (await parseWithRangeParser()).should.deep.equal(rangeAll);
        (await parseWithRangeParser(null, null)).should.deep.equal(rangeAll);
        (await parseWithRangeParser(null, false)).should.deep.equal(rangeAll);
        (await parseWithRangeParser(null, '')).should.deep.equal(rangeAll);
    });

    it('should use the given unit', async function() {
        (await parseWithRangeParser('ni', '')).should.have.property('unit', 'ni');
    });

    it('items 0-1', async function() {
        (await parseWithRangeParser('items', '0-1')).should.deep.equal(
            {unit: 'items', first: 0, last: 1}
        );
    });

    it('items 5-', async function() {
        (await parseWithRangeParser('items', '5-'))
            .should.deep.equal({unit: 'items', first: 5, last: Infinity});
    });

    it('should fail with 416 if first > last', async function() {
        const req = new Request({
            headers: {
                'Range-Unit': 'items',
                Range: '1-0'
            }
        });
        let res = {};
        const next = sinon.spy();
        await new Promise(resolve => {
            res = new Response({finish: resolve});

            rangeParser(req, res, next);
        });
        res.should.have.property('statusCode', 416);
        next.should.not.have.been.called;
        return req.range;
    });
});


text:
namespace ui {

OSExchangeDataProviderX11::OSExchangeDataProviderX11(
    x11::Window x_window,
    x11::Window source_window,
    const SelectionFormatMap& selection)
    : XOSExchangeDataProvider(x_window, source_window, selection) {}

OSExchangeDataProviderX11::OSExchangeDataProviderX11() {
  x11::Connection::Get()->AddEventObserver(this);
}

OSExchangeDataProviderX11::~OSExchangeDataProviderX11() {
  if (own_window())
    x11::Connection::Get()->RemoveEventObserver(this);
}

std::unique_ptr<OSExchangeDataProvider> OSExchangeDataProviderX11::Clone()
    const {
  std::unique_ptr<OSExchangeDataProviderX11> ret(
      new OSExchangeDataProviderX11());
  ret->set_format_map(format_map());
  return std::move(ret);
}

void OSExchangeDataProviderX11::OnEvent(const x11::Event& xev) {
  auto* selection = xev.As<x11::SelectionRequestEvent>();
  if (selection && selection->owner == x_window())
    selection_owner().OnSelectionRequest(*selection);
}

void OSExchangeDataProviderX11::SetSource(
    std::unique_ptr<DataTransferEndpoint> data_source) {}

DataTransferEndpoint* OSExchangeDataProviderX11::GetSource() const {
  return nullptr;
}

}  // namespace ui


text:
$(function() {

  // Number of points to be used in the K-Means Visualization
  var NUM_POINTS = 500;

  var $numClusters = $('#num-clusters');
  var numClusters = parseInt($numClusters.val(), 10);
  var $numCentroids = $('#num-centroids');
  var numCentroids = parseInt($numClusters.val(), 10);

  var $rangeSlider = $('#range-slider');
  var $meanSquareValue = $('.mean-square-value');

  var width = $('#kmeans-vis').width();
  var height = width;

  // Create SVG for d3
  var svg = d3.select('#kmeans-vis').append('svg')
    .attr('width', width)
    .attr('height', height);

  pointsGroup = svg.append('g').attr('id', 'points');
  var centroidsGroup = svg.append('g').attr('id', 'centroids');
  var voronoiGroup = svg.append('g').attr('id', 'voronoi');
  var triangle = d3.svg.symbol().type('triangle-up').size(function(d) { return 200; });
  var colors = d3.scale.category10();

  // Array of (x, y) points that will be classified
  var points = [];
  // Array of (x, y) centroids
  var centroids = [];
  var centroidBins = [];

  // Initial randomness. This is what the slider is set to.
  // 0 means data is very clustered, 100 means completely random
  var randomness = 25;
  var $step = $('.step');

  rangeSlider($rangeSlider[0], {
    value: randomness,
    drag: function(value) {
      // Update the randomness after the user drags the slider
      // and reset the points to be clustered
      randomness = value;
      resetPoints();
    }
  });

  // Resets the text on the centroid button
  function resetCentroidUpdateText() {
    $step.addClass('find');
    $step.html('Find closest centroid');

    $('.active').removeClass('active');
    $('.closest').addClass('active');
  }

  // Every time the step button is clicked, we alternate between finding the closest
  // centroid and updating the centroid
  $step.click(function() {
    if ($step.hasClass('find')) {
      findClosestCentroid();
      findClosestCentroidAnimation();
      $step.removeClass('find');
      $step.html('Update centroid');

      $('.active').removeClass('active');
      $('.update').addClass('active');
    } else {
      updateCentroid();
      updateCentroidAnimation();
      resetCentroidUpdateText();
    }
  });

  $('.closest').on('click', function() {
    if ($('.closest').hasClass('active')) {
      $step.click();
    }
  });

  $('.update').on('click', function() {
    if ($('.update').hasClass('active')) {
      $step.click();
    }
  });

  $('.new-points').click(function() {
    resetPoints();
  });

  $numClusters.blur(function() {
    var numClustersNew = parseInt($numClusters.val(), 10);
    if (!isNaN(numClustersNew) && numClustersNew != numClusters) {
      resetPoints();
    }
  });

  $numCentroids.blur(function() {
    var numCentroidsNew = parseInt($numCentroids.val(), 10);
    if (!isNaN(numCentroidsNew) && numCentroidsNew != numCentroids) {
      generateClusters();
    }
  });

  $('.new-centroids').click(function() {
    generateClusters();
  });

  $numClusters.blur(function() {
    var numClustersNew = parseInt($numClusters.val(), 10);
    if (!isNaN(numClustersNew) && numClustersNew != numClusters) {
      resetPoints();
    }
  });

  $numCentroids.blur(function() {
    var numCentroidsNew = parseInt($numCentroids.val(), 10);
    if (!isNaN(numCentroidsNew) && numCentroidsNew != numCentroids) {
      generateClusters();
    }
  });

  function uncolorPoints() {
    pointsGroup.selectAll('*').remove();
    pointsGroup.selectAll('circle')
      .data(points).enter()
      .append('circle')
      .attr('cx', function(d) {
        return d[0];
      }).attr('cy', function(d) {
        return d[1];
      }).attr('r', 3);
  }

  function resetPoints() {
    resetCentroidUpdateText();
    points = [];

    // Arbitrarily chosen variance and percentageClusteredPoints
    // There is no signficance behind the constants except that they looked good
    // with the slider.
    var variance = randomness / 2 + 5;
    var percentageClusteredPoints = (100 - 0.8 * randomness) / 100;

    numClusters = parseInt($numClusters.val(), 10);

    for (var i = 0; i < numClusters; i++) {
      // Creates a normal distribution with mean randomCenter(parameter)
      // and variance
      var xNorm = d3.random.normal(randomCenter(width), variance);
      var yNorm = d3.random.normal(randomCenter(height), variance);

      for (var j = 0; j < percentageClusteredPoints * NUM_POINTS / numClusters; j++) {
        points.push([normalPt(xNorm), normalPt(yNorm)]);
      }
    }

    // Scatter the remaining points randomly
    var length = points.length;
    for (var i = 0; i < NUM_POINTS - length; i++) {
      points.push([randomCenter(width), randomCenter(height)]);
    }

    uncolorPoints();
    resetCentroidUpdateText();
    voronoiGroup.selectAll('*').remove();

    $meanSquareValue.html('not yet calculated');
  }

  // Randomly generates the clusters and initializes the d3 animation
  function generateClusters() {
    centroids = [];
    numCentroids = parseInt($numCentroids.val(), 10);
    uncolorPoints();
    resetCentroidUpdateText();

    // Generate completely random centroids
    for (var k = 0; k < numCentroids; k++) {
      var randomX = randomCenter(width);
      var randomY = randomCenter(height);
      centroids.push([randomX, randomY]);
    }

    // Render initial centroid display
    centroidsGroup.selectAll('*').remove();
    voronoiGroup.selectAll('*').remove();

    centroidsGroup.selectAll('path')
      .data(centroids).enter()
      .append('path')
      .attr('d', triangle)
      .attr('fill', function(d, ndx){ return colors(ndx); })
      .style('stroke', 'black')
      .style('stroke-width', '0.7')
      .attr('transform', function(d){ return 'translate(' + d[0] + ',' + d[1] + ')'; });

    $meanSquareValue.html('not yet calculated');
  }

  // For each point, we find the centroid it is the closest to.
  function findClosestCentroid() {
    centroidBins = [];
    for (var i = 0; i < numCentroids; i++) {
      centroidBins.push([]);
    }

    for (var i = 0; i < points.length; i++) {
      var point = points[i];
      var minDist = Infinity;
      var minIndex = 0;
      for (var j = 0; j < centroids.length; j++) {
        centroid = centroids[j];
        var d = distance(point, centroid);
        if (d < minDist) {
          minDist = d;
          minIndex = j;
        }
      }
      centroidBins[minIndex].push(point);
    }

    var meanSquaredDistance = 0;
    for (var i = 0; i < centroidBins.length; i++) {
      bin = centroidBins[i];

      for (var j = 0; j < bin.length; j++) {
        var dist = distance(centroids[i], bin[j]);
        meanSquaredDistance += dist * dist;
      }
    }

    meanSquaredDistance /= NUM_POINTS;
    $meanSquareValue.html(meanSquaredDistance.toFixed(2));
  }

  function findClosestCentroidAnimation() {
    // TODO: This is terribly inefficient, fix later
    // Color the points according to the centroid to which they belong
    pointsGroup.selectAll('*')
      .data(points)
      .transition()
      .attr('fill', function(d, ndx){
        for (var i = 0; i < centroidBins.length; i++) {
          if (centroidBins[i].indexOf(d) != -1) {
            return colors(i);
          }
        }
      });

    // Render voronoi
    voronoiGroup.selectAll('*').remove();

    // Comment these lines out to get rid of Voronoi
    voronoiGroup.selectAll('path')
      .data(d3.geom.voronoi(centroids))
      .enter().append('path')
      .style('fill', function(d, ndx) {
        return colors(ndx);
      }).attr('d', function(d) {
        return 'M' + (d.join('L')) + 'Z';
      });
  }

  // Once the points have been assigned to the centroids, updates the
  // centroid to be the mean of all points assigned to it
  function updateCentroid() {
    var meanSquaredDistance = 0;
    // Find new centroids
    for (var i = 0; i < centroidBins.length; i++) {
      bin = centroidBins[i];
      newCentroid = avgXY(bin);

      for (var j = 0; j < bin.length; j++) {
        var dist = distance(newCentroid, bin[j]);
        meanSquaredDistance += dist * dist;
      }
      // If there are no points in the bin, newCentroid may be NaN
      // In this case, we don't update the centroid location
      if (!isNaN(newCentroid[0]) && !isNaN(newCentroid[1])) {
        centroids[i] = newCentroid;
      }
    }

    meanSquaredDistance /= NUM_POINTS;
    $meanSquareValue.html(meanSquaredDistance.toFixed(2));
  }

  function updateCentroidAnimation() {
    centroidsGroup.selectAll('path')
      .data(centroids)
      .transition()
      .attr('transform',function(d){ return 'translate(' + d[0] + ',' + d[1] + ')'; });
  }

  // Initial generation of clusters
  generateClusters();

  // Helper functions

  // Generate centers for dist centers and centroids
  function randomCenter(n) {
    return Math.random() * n;
  };

  // Euclidean distance between points a and b
  function distance(a, b) {
    return Math.sqrt(Math.pow(a[0] - b[0], 2) + Math.pow(a[1] - b[1], 2));
  }

  // Finds the average x value and average y value of all the points in arr
  function avgXY(arr) {
    var avgX = d3.sum(arr, function(d) { return d[0]; }) / arr.length;
    var avgY = d3.sum(arr, function(d) { return d[1]; }) / arr.length;
    return [avgX, avgY];
  }

  // Given a function normalFn, uses it to generate a value. If the value
  // is not within the range (0, width), continues to do so.
  function normalPt(normalFn) {
    var val = normalFn();
    if (val > 0 && val < width) {
      return val;
    } else {
      return normalPt(normalFn);
    }
  }
});


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Cerinthopsis foliosa Paine

### Remarks
null


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:iceVaccineGroupSpecificationFile xmlns:ns2="org.cdsframework.util.support.data.ice.vaccinegroup">
    <vaccineGroup code="400" codeSystem="2.16.840.1.113883.3.795.12.100.1" codeSystemName="ICE Vaccine Group" displayName="Polio"/>
    <cdsVersion>org.nyc.cir^ICE^1.0.0</cdsVersion>
    <ns2:priority>0</ns2:priority>
    <relatedVaccine code="110" codeSystem="2.16.840.1.113883.12.292" codeSystemName="CVX" displayName="DTaP-Hep B-IPV"/>
    <relatedVaccine code="130" codeSystem="2.16.840.1.113883.12.292" codeSystemName="CVX" displayName="DTaP-IPV"/>
    <relatedVaccine code="120" codeSystem="2.16.840.1.113883.12.292" codeSystemName="CVX" displayName="DTaP-Hib-IPV"/>
    <relatedVaccine code="10" codeSystem="2.16.840.1.113883.12.292" codeSystemName="CVX" displayName="IPV"/>
    <relatedVaccine code="89" codeSystem="2.16.840.1.113883.12.292" codeSystemName="CVX" displayName="polio NOS"/>
    <relatedVaccine code="02" codeSystem="2.16.840.1.113883.12.292" codeSystemName="CVX" displayName="OPV"/>
    <diseaseImmunity code="POLIO" codeSystem="2.16.840.1.113883.3.795.12.100.20" codeSystemName="ICE Disease" displayName="Acute Poliomyelitis"/>
    <openCdsMembership code="ICE206" displayName="Immunization Evaluation (Polio Vaccine Group)"/>
    <primaryOpenCdsConcept code="ICE206" displayName="Immunization Evaluation (Polio Vaccine Group)"/>
</ns2:iceVaccineGroupSpecificationFile>


text:
package org.pgscala.embedded

import java.net.{ConnectException, Socket}
import java.security.MessageDigest
import java.util.Locale
import javax.xml.bind.DatatypeConverter

import com.typesafe.scalalogging.StrictLogging

object Util extends StrictLogging {
  def bin2Hex(binary: Array[Byte]): String =
    DatatypeConverter.printHexBinary(binary).toLowerCase(Locale.ROOT)

  def digest(text: String): Array[Byte] = {
    val md = MessageDigest.getInstance("SHA-256")
    md.digest(text.getBytes("UTF-8"))
  }

  lazy val isWindows: Boolean = OS.Name.resolved match {
    case Some(OS.Name.Windows) => true
    case _ => false
  }

  lazy val isUnix: Boolean = OS.Name.resolved match {
    case Some(OS.Name.Linux) | Some(OS.Name.OSX) => true
    case _ => false
  }

  private[this] def socketIsFree(host: String, port: Int): Boolean =
    try {
      logger.trace(s"Checking if port $port is free...")
      new Socket(host, port).close()
      logger.debug(s"Port $port is free, choosing it for the cluster")
      false
    } catch {
      case _: ConnectException =>
        true
    }

  def findFreePort(host: String, portRange: Range): Int =
    portRange.find(port => socketIsFree(host, port))
      .getOrElse(sys.error(s"Could not find free port in range: [${portRange.head},${portRange.last}]"))
}


text:
import isArray from './array';
import {setDescription} from './utils/description';

/**
 * Checks whether value is an array and is not empty
 *
 * @example
 * is.notEmptyArray([1]); // true
 * is.notEmptyArray([]); // false
 * is.notEmptyArray('string'); // false
 */
export default function notEmptyArray<T = any>(value: any): boolean {
    return isArray(value) && value.length > 0;
}

setDescription(notEmptyArray, 'not an empty array');


text:
<?php

namespace Hoa\Xyl\Interpreter\Common;

use Hoa\Stream;
use Hoa\Xyl;

/**
 * Class \Hoa\Xyl\Interpreter\Common\XylElse.
 *
 * The <else /> component.
 *
 * @copyright  Copyright © 2007-2015 Hoa community
 * @license    New BSD License
 */
class XylElse extends Xyl\Element\Concrete
{
    /**
     * Paint the element.
     *
     * @param   \Hoa\Stream\IStream\Out  $out    Out stream.
     * @return  void
     */
    public function paint(Stream\IStream\Out $out)
    {
        return;
    }

    /**
     * Structural compute (if/elseif/else).
     *
     * @param   \Hoa\Stream\IStream\Out  $out    Out stream.
     * @return  void
     */
    public function structuralCompute(Stream\IStream\Out $out)
    {
        $this->computeValue($out);

        return;
    }
}


text:
import * as cacheManager from 'cache-manager'

const memoryCache: cacheManager.Cache = cacheManager.caching({ store: 'memory', max: 100, ttl: 10/*seconds*/ });
const ttl = 5;

memoryCache.set('foo', 'bar', { ttl: ttl }, (err) => {

    if (err) {
        throw err;
    }

    memoryCache.get('foo', (err, result) => {

        // console.log(result);

        memoryCache.del('foo', (err) => {
        });

    });
});

function getUser(id: number, cb: Function) {

    cb(null, { id: id, name: 'Bob' });
}

const userId = 123;
const key = 'user_' + userId;
const key2 = 'user_' + userId + '4';

// Note: ttl is optional in wrap()
memoryCache.wrap<{ id: number, name: string }>(key, (cb: any) => {

    getUser(userId, cb);

}, { ttl: ttl }, (err: any, user: { id: number, name: string }) => {

    //console.log(user);

    // Second time fetches user from memoryCache
    memoryCache.wrap<{ id: number, name: string }>(key, key2, (cb: any) => {

        getUser(userId, cb);

    }, (err: any, user: { id: number, name: string }) => {

        //console.log(user);

    });
});

if (memoryCache.store.keys) {
    memoryCache.store.keys().then((result) => {
        //console.log(result);
    });
}

memoryCache.reset().then(() => {
    // console.log('reset with promise');
});
memoryCache.reset(() => {
    // console.log('reset with callback');
});

async function promiseMemoryCache(cache: cacheManager.Cache) {
    const KEY = 'Key';
    const VALUE = 'string';

    const numberWrap: number = await cache.wrap<number>(KEY, () => 1);
    const stringWrap: string = await cache.wrap<string>(KEY, () => VALUE);
    const stringWrapWithCacheConfig: string = await cache.wrap<string>(KEY, () => VALUE, { ttl: 10 });

    const setWithoutOptional = await cache.set(KEY, VALUE);
    const setWitOptional = await cache.set(KEY, VALUE, { ttl: 10 });

    const stringTypeSet: string = await cache.set(KEY, VALUE);
    const stringTypeGet: string | undefined = await cache.get<string>(KEY);

    const numberTypeSet: number = await cache.set(KEY, 1);
    const numberTypeGet: number | undefined = await cache.get<number>(KEY);

    interface Custom {
        test: string;
    };

    const CustomValue: Custom = { test: VALUE };

    const customTypeSet: Custom = await cache.set(KEY, CustomValue);
    const customTypeGet: Custom | undefined = await cache.get<Custom>(KEY);
}

const multiCache = cacheManager.multiCaching([memoryCache]);

multiCache.set('foo', 'bar', { ttl: ttl }, (err) => {

    if (err) {
        throw err;
    }

    multiCache.get('foo', (err, result) => {

        // console.log(result);

        multiCache.del('foo', (err) => {
        });

    });
});

multiCache.reset(() => {
    // console.log('multiCache reset');
});


text:
echo "$locale" >> /etc/locale.gen
locale-gen