text:
package com.intellij.util.containers;

import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Conditions;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.Function;
import com.intellij.util.Functions;
import com.intellij.util.PairFunction;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.*;

/**
 * An in-house version of {@code com.google.common.collect.FluentIterable} with some Clojure-like additions.
 * As a bonus iterator instance is preserved during most transformations if it inherits JBIterator.
 *
 *

 * The original JavaDoc ('FluentIterable' replaced by 'JBIterable'):
 *

 * {@code JBIterable} provides a rich interface for manipulating {@code Iterable} instances in a
 * chained fashion. A {@code JBIterable} can be created from an {@code Iterable}, or from a set
 * of elements. The following types of methods are provided on {@code JBIterable}:
 *

 *
chained methods which return a new {@code JBIterable} based in some way on the contents
 * of the current one (for example {@link #transform})
 *
conversion methods which copy the {@code JBIterable}'s contents into a new collection or
 * array (for example {@link #toList})
 *
element extraction methods which facilitate the retrieval of certain elements (for example
 * {@link #last})
 *

 *

 *
Here is an example that merges the lists returned by two separate database calls, transforms
 * it by invoking {@code toString()} on each element, and returns the first 10 elements as an
 * {@code List}:
   {@code
 *   FluentIterable
 *       .from(database.getClientList())
 *       .filter(activeInLastMonth())
 *       .transform(Functions.toStringFunction())
 *       .toList();}

 *

 *
Anything which can be done using {@code JBIterable} could be done in a different fashion
 * (often with {@link Iterables}), however the use of {@code JBIterable} makes many sets of
 * operations significantly more concise.
 *
 * @author Marcin Mikosik
 */
public abstract class JBIterable<E> implements Iterable<E> {

  // We store 'iterable' and use it instead of 'this' to allow Iterables to perform instanceof
  // checks on the _original_ iterable when JBIterable#from is used.
  final Iterable<E> myIterable;

  /**
   * Constructor for use by subclasses.
   */
  protected JBIterable() {
    myIterable = this;
  }

  JBIterable(@NotNull Iterable<E> iterable) {
    myIterable = iterable;
  }

  /**
   * Returns a {@code JBIterable} that wraps {@code iterable}, or {@code iterable} itself if it
   * is already a {@code JBIterable}.
   */
  @NotNull
  public static <E> JBIterable<E> from(@Nullable Iterable<? extends E> iterable) {
    if (iterable == null) return empty();
    if (iterable instanceof JBIterable) return (JBIterable<E>)iterable;
    return new JBIterable<E>((Iterable<E>)iterable) {
      @Override
      public Iterator<E> iterator() {
        return myIterable.iterator();
      }
    };
  }

  /**
   * Returns a {@code JBIterable} that is generated by {@code generator} function applied to a previous element,
   * the first element is produced by the supplied {@code first} value.
   *
   * Generation stops if null is encountered.
   */
  @NotNull
  public static <E> JBIterable<E> generate(@Nullable final E first, @NotNull final Function<? super E, ? extends E> generator) {
    if (first == null) return empty();
    return new JBIterable<E>() {
      @Override
      public Iterator<E> iterator() {
        final Function<? super E, ? extends E> fun = Stateful.copy(generator);
        return new JBIterator<E>() {
          E cur = first;

          @Override
          public E nextImpl() {
            E result = cur;
            if (result == null) return stop();
            cur = fun.fun(cur);
            return result;
          }
        };
      }
    };
  }

  @NotNull
  public static <E> JBIterable<E> generate(@Nullable final E first1, @Nullable final E first2, @NotNull final PairFunction<? super E, ? super E, ? extends E> generator) {
    if (first1 == null) return empty();
    return new JBIterable<E>() {
      @Override
      public Iterator<E> iterator() {
        return new JBIterator<E>() {
          E cur1 = first1;
          E cur2 = first2;

          @Override
          public E nextImpl() {
            E result = cur1;
            cur1 = cur2;
            cur2 = generator.fun(result, cur2);
            if (result == null) return stop();
            return result;
          }
        };
      }
    };
  }

  /**
   * Returns a {@code JBIterable} containing {@code elements} in the specified order.
   */
  @NotNull
  public static <E> JBIterable<E> of(@Nullable E... elements) {
    return elements == null ? JBIterable.<E>empty() : from(ContainerUtil.newArrayList(elements));
  }

  private static final JBIterable EMPTY = new JBIterable() {
    @Override
    public Iterator iterator() {
      return ContainerUtil.emptyIterator();
    }
  };

  @NotNull
  public static <E> JBIterable<E> empty() {
    return (JBIterable<E>)EMPTY;
  }

  @NotNull
  public static <E> JBIterable<E> once(@NotNull Iterator<E> iterator) {
    return of(Ref.create(iterator)).intercept(new Function<Iterator<Ref<Iterator<E>>>, Iterator<E>>() {
      @Override
      public Iterator<E> fun(Iterator<Ref<Iterator<E>>> iterator) {
        Ref<Iterator<E>> ref = iterator.next();
        Iterator<E> result = ref.get();
        if (result == null) throw new UnsupportedOperationException();
        ref.set(null);
        return result;
      }
    });
  }

  public <T extends Iterator<E>> T typedIterator() {
    return (T) iterator();
  }

  /**
   * Returns a string representation of this iterable up to 50 elements, with the format
   * {@code (e1, e2, ..., en [, ...] )} for debugging purposes.
   */
  @Override
  public String toString() {
    int max = 50;
    List<E> list = take(max + 1).toList();
    return "(" + StringUtil.join(list.subList(0, Math.min(list.size(), max)), ", ") + (list.size() > max ? ", ..." : "") + ")";
  }

  /**
   * Returns the number of elements in this iterable.
   */
  public final int size() {
    int count = 0;
    for (E ignored : myIterable) {
      count++;
    }
    return count;
  }

  /**
   * Returns {@code true} if this iterable contains any object for which
   * {@code equals(element)} is true.
   */
  public final boolean contains(@Nullable Object element) {
    if (myIterable instanceof Collection) {
      return ((Collection)myIterable).contains(element);
    }
    for (E e : myIterable) {
      if (Comparing.equal(e, element)) return true;
    }
    return false;
  }

  /**
   * Returns a {@code JBIterable} whose iterators traverse first the elements of this iterable,
   * followed by those of {@code other}. The iterators are not polled until necessary.
   *

   *
The returned iterable's {@code Iterator} supports {@code remove()} when the corresponding
   * {@code Iterator} supports it.
   */
  public final JBIterable<E> append(@Nullable Iterable<? extends E> other) {
    return other == null ? this : this == EMPTY ? from(other) : of(myIterable, other).flatten(Functions.<Iterable<?>, Iterable<E>>identity());
  }

  public final <T> JBIterable<E> append(@Nullable Iterable<T> other, @NotNull Function<? super T, ? extends Iterable<? extends E>> fun) {
    return other == null ? this : this == EMPTY ? from(other).flatten(fun) : append(from(other).flatten(fun));
  }

  public final JBIterable<E> repeat(int count) {
    Function<JBIterable<E>, JBIterable<E>> fun = Functions.identity();
    return generate(this, fun).take(count).flatten(fun);
  }

  /**
   * Returns a {@code JBIterable} whose iterators traverse first the elements of this iterable,
   * followed by {@code elements}.
   */
  public final JBIterable<E> append(@NotNull E[] elements) {
    return this == EMPTY ? of(elements) : append(Arrays.asList(elements));
  }

  public final JBIterable<E> append(@Nullable E e) {
    return e == null ? this : this == EMPTY ? of(e) : append(Collections.singleton(e));
  }

  /**
   * Returns the elements from this iterable that satisfy a condition.
   */
  public final JBIterable<E> filter(@NotNull final Condition<? super E> condition) {
    return intercept(new Function<Iterator<E>, Iterator<E>>() {
      @Override
      public Iterator<E> fun(Iterator<E> iterator) {
        return JBIterator.from(iterator).filter(Stateful.copy(condition));
      }
    });
  }

  /**
   * Returns the elements from this iterable that are instances of class {@code type}.
   * @param type the type of elements desired
   */
  public final <T> JBIterable<T> filter(@NotNull Class<T> type) {
    //noinspection unchecked
    return (JBIterable<T>)filter(Conditions.instanceOf(type));
  }

  @NotNull
  public final JBIterable<E> take(final int count) {
    return intercept(new Function<Iterator<E>, Iterator<E>>() {
      @Override
      public Iterator<E> fun(Iterator<E> iterator) {
        return JBIterator.from(iterator).take(count);
      }
    });
  }

  @NotNull
  public final JBIterable<E> takeWhile(@NotNull final Condition<? super E> condition) {
    return intercept(new Function<Iterator<E>, Iterator<E>>() {
      @Override
      public Iterator<E> fun(Iterator<E> iterator) {
        return JBIterator.from(iterator).takeWhile(Stateful.copy(condition));
      }
    });
  }

  @NotNull
  public final JBIterable<E> skip(final int count) {
    return intercept(new Function<Iterator<E>, Iterator<E>>() {
      @Override
      public Iterator<E> fun(Iterator<E> iterator) {
        return JBIterator.from(iterator).skip(count);
      }
    });
  }

  @NotNull
  public final JBIterable<E> skipWhile(@NotNull final Condition<? super E> condition) {
    return intercept(new Function<Iterator<E>, Iterator<E>>() {
      @Override
      public Iterator<E> fun(Iterator<E> iterator) {
        return JBIterator.from(iterator).skipWhile(Stateful.copy(condition));
      }
    });
  }

  /**
   * Returns a {@code JBIterable} that applies {@code function} to each element of this
   * iterable.
   *

   *
The returned iterable's iterator supports {@code remove()} if this iterable's
   * iterator does. After a successful {@code remove()} call, this iterable no longer
   * contains the corresponding element.
   */
  @NotNull
  public final <T> JBIterable<T> transform(@NotNull final Function<? super E, T> function) {
    return intercept(new Function<Iterator<E>, Iterator<T>>() {
      @Override
      public Iterator<T> fun(Iterator<E> iterator) {
        return JBIterator.from(iterator).transform(Stateful.copy(function));
      }
    });
  }

  /**
   * Returns a {@code JBIterable} that applies {@code function} to each element of this
   * iterable and concats the produced iterables in one.
   *

   *
The returned iterable's iterator supports {@code remove()} if an underlying iterable's
   * iterator does. After a successful {@code remove()} call, this iterable no longer
   * contains the corresponding element.
   */
  @NotNull
  public <T> JBIterable<T> flatten(final Function<? super E, ? extends Iterable<? extends T>> function) {
    return intercept(new Function<Iterator<E>, Iterator<T>>() {
      @Override
      public Iterator<T> fun(final Iterator<E> iterator) {
        final Function<? super E, ? extends Iterable<? extends T>> fun = Stateful.copy(function);
        return new JBIterator<T>() {
          Iterator<? extends T> cur;

          @Override
          public T nextImpl() {
            while ((cur == null || !cur.hasNext()) && iterator.hasNext()) {
              cur = fun.fun(iterator.next()).iterator();
            }
            if (cur == null || !cur.hasNext()) return stop();
            return cur.next();
          }

          @Override
          public void remove() {
            cur.remove();
          }
        };
      }
    });
  }

  /**
   * The most generic iterator transformation.
   */
  @NotNull
  public final <T> JBIterable<T> intercept(@NotNull final Function<Iterator<E>, Iterator<T>> function) {
    if (this == EMPTY) return empty();
    final JBIterable<E> thisIterable = this;
    return new JBIterable<T>() {
      @Override
      public Iterator<T> iterator() {
        return function.fun(thisIterable.iterator());
      }
    };
  }

  /**
   * Returns the first element in this iterable or null.
   */
  @Nullable
  public final E first() {
    Iterator<E> iterator = myIterable.iterator();
    return iterator.hasNext() ? iterator.next() : null;
  }

  /**
   * Returns the last element in this iterable or null.
   */
  @Nullable
  public final E last() {
    if (myIterable instanceof List) {
      return ContainerUtil.getLastItem((List<E>)myIterable);
    }
    Iterator<E> iterator = myIterable.iterator();
    E cur = null;
    while (iterator.hasNext()) {
      cur = iterator.next();
    }
    return cur;
  }

  /**
   * Determines whether this iterable is empty.
   */
  public final boolean isEmpty() {
    return !myIterable.iterator().hasNext();
  }

  /**
   * Returns an {@code List} containing all of the elements from this iterable in
   * proper sequence.
   */
  public final List<E> toList() {
    return Collections.unmodifiableList(ContainerUtil.newArrayList(myIterable));
  }

  /**
   * Returns an {@code Set} containing all of the elements from this iterable with
   * duplicates removed.
   */
  public final Set<E> toSet() {
    return Collections.unmodifiableSet(ContainerUtil.newLinkedHashSet(myIterable));
  }

  /**
   * Returns an {@code Map} for which the elements of this {@code JBIterable} are the keys in
   * the same order, mapped to values by the given function. If this iterable contains duplicate
   * elements, the returned map will contain each distinct element once in the order it first
   * appears.
   */
  public final <V> Map<E, V> toMap(Convertor<E, V> valueFunction) {
    return Collections.unmodifiableMap(ContainerUtil.newMapFromKeys(iterator(), valueFunction));
  }

  /**
   * Copies all the elements from this iterable to {@code collection}. This is equivalent to
   * calling {@code Iterables.addAll(collection, this)}.
   *
   * @param collection the collection to copy elements to
   * @return {@code collection}, for convenience
   */
  public final <C extends Collection<? super E>> C addAllTo(@NotNull C collection) {
    if (myIterable instanceof Collection) {
      collection.addAll((Collection<E>)myIterable);
    }
    else {
      for (E item : myIterable) {
        collection.add(item);
      }
    }
    return collection;
  }

  @SuppressWarnings("unchecked")
  public abstract static class Stateful<Self extends Stateful> implements Cloneable {

    @NotNull
    static <T> T copy(@NotNull T o) {
      if (!(o instanceof Stateful)) {
        return o;
      }
      return (T)((Stateful)o).clone();
    }

    public Self clone() {
      try {
        return (Self)super.clone();
      }
      catch (CloneNotSupportedException e) {
        throw new AssertionError(e);
      }
    }
  }

  public abstract static class StatefulFilter<T> extends Stateful<StatefulFilter> implements Condition<T> {

  }

  public abstract static class StatefulTransform<S, T> extends Stateful<StatefulTransform> implements Function<S, T> {

  }
}


text:
package org.apache.camel.processor;

import org.apache.camel.ContextTestSupport;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.SynchronizationAdapter;

/**
 * @version $Revision$
 */
public class OnCompletionShouldBeLastTest extends ContextTestSupport {

    public void testOnCompletionShouldBeLast() throws Exception {
        getMockEndpoint("mock:sync").expectedBodiesReceived("C", "B", "A", "Hello World");
        getMockEndpoint("mock:result").expectedBodiesReceived("Hello World");

        template.sendBody("direct:start", "Hello World");

        assertMockEndpointsSatisfied();
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                onCompletion().to("mock:sync");

                from("direct:start")
                    .process(new Processor() {
                        public void process(Exchange exchange) throws Exception {
                            exchange.addOnCompletion(new SynchronizationAdapter() {
                                @Override
                                public void onDone(Exchange exchange) {
                                    template.sendBody("mock:sync", "A");
                                }

                                @Override
                                public String toString() {
                                    return "A";
                                }
                            });

                            exchange.addOnCompletion(new SynchronizationAdapter() {
                                @Override
                                public void onDone(Exchange exchange) {
                                    template.sendBody("mock:sync", "B");
                                }

                                @Override
                                public String toString() {
                                    return "B";
                                }
                            });

                            exchange.addOnCompletion(new SynchronizationAdapter() {
                                @Override
                                public void onDone(Exchange exchange) {
                                    template.sendBody("mock:sync", "C");
                                }

                                @Override
                                public String toString() {
                                    return "C";
                                }
                            });
                        }
                    })
                    .to("mock:result");
            }
        };
    }

}

redpajama_set_name: RedPajamaGithub


text:
#if LESSTHAN_NET35
extern alias nunitlinq;
#endif

// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
//
// Authors:
//      Federico Di Gregorio <fog@initd.org>

using System;
using System.Linq.Expressions;
using NUnit.Framework;

namespace MonoTests.System.Linq.Expressions
{
    [TestFixture]
    public class ExpressionTestPropertyOrField
    {
        [Test]
        public void Arg1Null()
        {
            Assert.Throws<ArgumentNullException>(() => Expression.PropertyOrField(null, "NoPropertyOrField"));
        }

        [Test]
        public void Arg2Null()
        {
            Assert.Throws<ArgumentNullException>(() => Expression.PropertyOrField(Expression.Constant(new MemberClass()), null));
        }

        [Test]
        public void InstanceProperty()
        {
            var expr = Expression.PropertyOrField(Expression.Constant(new MemberClass()), "TestProperty1");
            Assert.AreEqual(ExpressionType.MemberAccess, expr.NodeType, "PropertyOrField#01");
            Assert.AreEqual(typeof(int), expr.Type, "PropertyOrField#02");
            Assert.AreEqual("value(MonoTests.System.Linq.Expressions.MemberClass).TestProperty1", expr.ToString(), "PropertyOrField#04");
        }

        [Test]
        public void NoPropertyOrField()
        {
            Assert.Throws<ArgumentException>(() => Expression.PropertyOrField(Expression.Constant(new MemberClass()), "NoPropertyOrField"));
        }
    }
}


text:
package org.jetbrains.plugins.groovy.lang.completion;

import com.intellij.codeInsight.completion.CompletionConfidence;
import com.intellij.codeInsight.completion.CompletionParameters;
import com.intellij.patterns.ElementPattern;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiReference;
import com.intellij.util.ThreeState;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.groovy.console.GroovyShellAction;
import org.jetbrains.plugins.groovy.extensions.GroovyScriptTypeDetector;
import org.jetbrains.plugins.groovy.lang.lexer.TokenSets;
import org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement;
import org.jetbrains.plugins.groovy.lang.psi.GroovyFile;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrForStatement;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression;
import org.jetbrains.plugins.groovy.lang.psi.impl.PsiImplUtil;
import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil;

import static com.intellij.patterns.PsiJavaPatterns.psiElement;

/**
 * @author peter
 */
public class GroovyCompletionConfidence extends CompletionConfidence {
  private static final ElementPattern<PsiElement> CLOSURE_LBRACE = psiElement().withText("{").withParent(GrClosableBlock.class);

  private static boolean isPossibleClosureParameter(GrReferenceExpression ref) {
    return psiElement().afterLeaf(CLOSURE_LBRACE).accepts(ref) ||
           psiElement().afterLeaf(
             psiElement().afterLeaf(",").withParent(
               psiElement(GrVariable.class).withParent(
                 psiElement(GrVariableDeclaration.class).afterLeaf(CLOSURE_LBRACE)))).accepts(ref) ||
           GroovyCompletionContributor.isInPossibleClosureParameter(ref);
  }

  @NotNull
  @Override
  public ThreeState shouldFocusLookup(@NotNull CompletionParameters parameters) {
    final PsiElement position = parameters.getPosition();

    PsiFile file = position.getContainingFile();
    if (file instanceof GroovyFile && GroovyScriptTypeDetector.getScriptType((GroovyFile)file) != GroovyScriptTypeDetector.DEFAULT_TYPE) {
      return ThreeState.NO;
    }

    if (position.getParent() instanceof GrReferenceElement &&
        psiElement().afterLeaf(psiElement().withText("(").withParent(GrForStatement.class)).accepts(position)) {
      return ThreeState.NO;
    }

    if (position.getParent() instanceof GrReferenceExpression) {
      final GrReferenceExpression ref = (GrReferenceExpression)position.getParent();
      final GrExpression qualifier = ref.getQualifierExpression();
      if (qualifier == null) {
        if (isPossibleClosureParameter(ref)) return ThreeState.NO;
        if (parameters.getOriginalFile().getUserData(GroovyShellAction.GROOVY_SHELL_FILE) == Boolean.TRUE) {
          return ThreeState.NO;
        }

        GrExpression runtimeQualifier = PsiImplUtil.getRuntimeQualifier(ref);
        if (runtimeQualifier != null && runtimeQualifier.getType() == null) {
          return ThreeState.NO;
        }

        return ThreeState.YES;
      }

      if (qualifier.getType() == null) {
        return ThreeState.NO;
      }
      return ThreeState.YES;
    }
    return ThreeState.UNSURE;
  }

  @NotNull
  @Override
  public ThreeState shouldSkipAutopopup(@NotNull PsiElement contextElement, @NotNull PsiFile psiFile, int offset) {
    if (PsiUtil.isLeafElementOfType(contextElement, TokenSets.STRING_LITERALS)) {
      @SuppressWarnings("ConstantConditions")
      PsiElement parent = contextElement.getParent();
      if (parent != null) {
        for (PsiReference reference : parent.getReferences()) {
          if (!reference.isSoft() && reference.getRangeInElement().shiftRight(parent.getTextOffset()).containsOffset(offset)) {
            return ThreeState.NO;
          }
        }
      }

      return ThreeState.YES;
    }

    if (psiElement().afterLeaf("def").accepts(contextElement)) {
      return ThreeState.YES;
    }

    return ThreeState.UNSURE;
  }
}


text:
<?php
namespace TYPO3\Flow\Persistence\Doctrine\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration,
	Doctrine\DBAL\Schema\Schema;

/**
 * Auto-generated Migration: Please modify to your need!
 */
class Version20150527131717 extends AbstractMigration {

	/**
	 * @param Schema $schema
	 * @return void
	 */
	public function up(Schema $schema) {
		// this up() migration is autogenerated, please modify it to your needs
		$this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql");

		$this->addSql("ALTER TABLE sandstorm_newsletter_domain_model_receiversource ADD dtype VARCHAR(255) NOT NULL, CHANGE sourcefilename sourcefilename VARCHAR(255) DEFAULT NULL");
	}

	/**
	 * @param Schema $schema
	 * @return void
	 */
	public function down(Schema $schema) {
		// this down() migration is autogenerated, please modify it to your needs
		$this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql");

		$this->addSql("ALTER TABLE sandstorm_newsletter_domain_model_receiversource DROP dtype, CHANGE sourcefilename sourcefilename VARCHAR(255) NOT NULL COLLATE utf8_unicode_ci");
	}
}


text:
import datetime
import sqlalchemy
from pypi_secure.data.modelbase import SqlAlchemyBase

class User(SqlAlchemyBase):
    __tablename__ = 'users'

    id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True, autoincrement=True)
    name = sqlalchemy.Column(sqlalchemy.String, nullable=True)
    email = sqlalchemy.Column(sqlalchemy.String, index=True, unique=True, nullable=True)
    hashed_password = sqlalchemy.Column(sqlalchemy.String, nullable=True, index=True)
    created_date = sqlalchemy.Column(sqlalchemy.DateTime, default=datetime.datetime.now, index=True)
    profile_image_url = sqlalchemy.Column(sqlalchemy.String)
    last_login = sqlalchemy.Column(sqlalchemy.DateTime, default=datetime.datetime.now, index=True)


text:
import numpy as np
import os

def load_data(path='simple-examples.tgz'):
    """Loads the Penn Treebank (PTB) dataset.

    # Arguments
        path: path where to cache the dataset locally
            (relative to ~/.keras/datasets).

    # Returns
        Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`.
    """


text:
import bcrypt
from flask import request
from bson import json_util, ObjectId
import pymongo

from api import auth, db
from api.module import Module
from api.models.user import SqlUser as User, UserException
from api.role import Role

users = Module('users', __name__, url_prefix='/users', no_version=True)

def count_users():
	""" FIXME not used, remove """
	return db.users.count()

def lookup_user(user):
	""" FIXME not used, remove """
	user_id = user.get("user_id", None)

	query = {"$or" : [
		{"_id" : None if user_id == None else ObjectId(user_id)},
		{"username" : user.get("username", None)},
		{"email" : user.get("email", None)}
		]}

	cursor = db.users.find(query)

	return list(cursor)

def user_exists(user):
	""" FIXME not used, remove """
	return False if db.users.find({"$or" : [
		{"username" : user.get("username", None)},
		{"email" : user.get("email", None)}
		]}).count() == 0 else True

@auth.required(Role.admin)
def get_users():
	res = User.query.all()
	users = []

	for user in res:
		tmp = user.to_dict()
		tmp.pop("password", None)
		users.append(tmp)

	return(json_util.dumps(users))

@auth.required(Role.admin)
def get_user(user_id):
	user = User.query.get_or_404(user_id)
	user = user.to_dict()
	user.pop('password', None)
	return(json_util.dumps(user))

def unprotected_add_user(user_data):
	"""
	Create a user and add it to database

	Fields:
		* password
		* email
		* username
	"""
	try:
		user = User.from_dict(user_data)
	except Exception as e:
		print(e)
		raise UserException("Could not convert dictionary to user")

	if user.password == None:
		raise UserException("Missing password")

	user.password = auth.create_hash(user.password)

	try:
		db.db.session.add(user)
		res = db.db.session.commit()
		return user
	except Exception as e:
		db.db.session.rollback()
		print(e)
		raise UserException("Could not add user to database")

@auth.required(Role.admin)
def add_user():
	r = request.get_json()
	try:
		user = User.from_dict(r)
	except Exception as e:
		print(e)
		raise UserException("Could not convert dictionary to User")

	#if user_exists(user):
	#	raise UserException("User '" + user.username + "' already exists", status_code = 400)

	user = unprotected_add_user(user.to_dict())

	inserted = User.query.get_or_404(user.id)

	user = inserted.to_dict()
	user.pop("password", None)

	return(json_util.dumps(user))

@auth.required(Role.admin)
def remove_user(user_id):
	"""
	Remove the user
	"""

	user = User.query.get_or_404(user_id)

	try:
		db.db.session.delete(user)
		db.db.session.commit()
	except Exception as e:
		db.db.session.rollback()
		print(e)
		raise UserException("Could not remove user")

	user.password = None
	tmp = user.to_dict()

	return(json_util.dumps(tmp))

@auth.required(Role.admin)
def edit_user(user_id):
	"""
	TODO: differentiate between PUT and PATCH -> PATCH partial update
	"""
	user_dict = request.get_json()
	user = User.query.get_or_404(user_id)

	# If the user updates their profile check for all fields to be updated
	if "first_name" in user_dict and user_dict["first_name"]!= "":
		user.first_name = user_dict["first_name"]

	if "last_name" in user_dict and user_dict["last_name"] != "":
		user.last_name = user_dict["last_name"]

	if "email" in user_dict and user_dict["email"] != "":
		user.email = user_dict["email"]

	if "role" in user_dict and User.parseRole(user_dict["role"]) >= 0:
		user.role = User.parseRole(user_dict["role"])

	if "settings" in user_dict and user_dict["settings"] != {}:
		user.settings = user_dict["settings"]

	# In case of password change, verify that it is really them (revalidate their password)
	if "password" in user_dict and user_dict["password"] != "":
		if not auth.check_password(user_dict["password"], user.password.decode('utf8')):
			raise UserException("Password mismatch")

		try:
			user.password = auth.create_hash(user_dict["password_new"])
		except Exception as e:
			print(e)
			raise UserException("Could not create password hash")

	# Update the user and return updated document
	try:
		db.db.session.commit()
	except Exception as e:
		db.db.session.rollback()
		print(e)
		raise UserException("Could not edit user")

	# Remove password hash from the response
	user.password = None
	tmp = user.to_dict()

	return(json_util.dumps(tmp))

users.add_url_rule('', view_func=get_users, methods=['GET'])
users.add_url_rule('', view_func=add_user, methods=['POST'])
users.add_url_rule('/<string:user_id>', view_func=get_user, methods=['GET'])
users.add_url_rule('/<string:user_id>', view_func=edit_user, methods=['PUT'])
users.add_url_rule('/<string:user_id>', view_func=remove_user, methods=['DELETE'])


text:
var React = require('react'),
    injectTapEventPlugin = require('react-tap-event-plugin'),
    mui = require('material-ui'),
    ThemeManager = new mui.Styles.ThemeManager(),
    AppBar = mui.AppBar,
    Router = require('react-router'),
    RouteHandler = Router.RouteHandler,
    AppLeftNav = require('./AppLeftNav.react');

ThemeManager.setTheme(ThemeManager.types.LIGHT);
injectTapEventPlugin();

App = React.createClass({

    childContextTypes: {
        muiTheme: React.PropTypes.object
    },

    getChildContext() {
        return {
            muiTheme: ThemeManager.getCurrentTheme()
        };
    },
    handleLeftIconButtonTouchTap: function () {
        this.refs.AppLeftNav.toggle();
    },
    render: function () {
        return (

                <AppBar onLeftIconButtonTouchTap={this.handleLeftIconButtonTouchTap} title="Company name"
                        iconClassNameRight="muidocs-icon-navigation-expand-more"/>
                <AppLeftNav ref="AppLeftNav"/>

                    <RouteHandler />

        );
    }
});

module.exports = App;


text:
describe PersistentVolumeClaim do
  describe "#storage_capacity" do
    let(:storage_size) { 123_456_789 }

    it "returns value for :storage key in Hash column :capacity" do
      persistent_volume = FactoryBot.create(
        :persistent_volume_claim,
        :capacity => {:storage => storage_size, :foo => "something"}
      )
      expect(persistent_volume.storage_capacity).to eq storage_size
    end

    it "returns nil if there is no :storage key in Hash column :capacity" do
      persistent_volume = FactoryBot.create(
        :persistent_volume_claim,
        :capacity => {:foo => "something"}
      )
      expect(persistent_volume.storage_capacity).to be nil
    end
  end
end


text:
use warnings ;
use strict;
use Getopt::Long qw(:config no_ignore_case);
use Bio::EnsEMBL::Utils::Exception qw(stack_trace);
use Bio::EnsEMBL::DBSQL::DBAdaptor;
use Bio::EnsEMBL::Pipeline::DBSQL::DBAdaptor;
use Bio::EnsEMBL::Pipeline::DBSQL::FlagAdaptor;
use Bio::EnsEMBL::Pipeline::Flag;
use Bio::EnsEMBL::Pipeline::Utils::InputIDFactory;
use Bio::EnsEMBL::Pipeline::DBSQL::StateInfoContainer;
use Bio::SeqIO;
use ncRNA_update_config ;
my $dbhost;
my $dbuser;
my $pass;
my $dbname;
my $dbport;
my $chunk = 5;
my $help;
my %RFAM;

my @dbID;
my $count =0;
my $num=0;
my $start;
my $dln = 'DummyFlag';

my @multiexon_files;
my @species_list;
my $verbose;
my $norfam;

$| = 1;

GetOptions(
	    'pass|p|dbpass=s'    => \$pass,
	    'verbose!'  => \$verbose,
	    'species=s' => \@species_list,
	    'norfam!'      => \$norfam,
           );

if(!$pass || $help){
  die ("perl predict_ncRNA.pl
-pass *(password)
-species (species list)
-verbose
-norfam  (Only run miRNA annotation)
writes paths and rulemanager command lines to shell script species.csh(* required)\n");
  $help = 1;
}

my @speciess;
if (scalar(@species_list)) {
  @species_list = split(/,/,join(',',@species_list));
  foreach my $species (@species_list){
    if ($CONFIG->{$species}){
      push @speciess, $species;
    } else {
    print "Skipping species $species\n";
    }
  }
} else {
  @speciess = (keys %$CONFIG);
}

# might want to check some config first
SPECIES:  foreach my $species (@speciess){
   print "checking species $species\n";
  # check that all the dbs exist and have finished their run!
  my $sdb = new Bio::EnsEMBL::Pipeline::DBSQL::DBAdaptor
    (
     -host   => $CONFIG->{$species}->{"WRITEHOST"},
     -user   => 'ensro',
     -port   => $CONFIG->{$species}->{"WRITEPORT"},
     -dbname => $CONFIG->{$species}->{"WRITENAME"},
    );
  my $dna_db = new Bio::EnsEMBL::Pipeline::DBSQL::DBAdaptor
    (
     '-host'   => $CONFIG->{$species}->{"DBHOST"},
     '-user'   => 'ensro',
     '-dbname' => $CONFIG->{$species}->{"DBNAME"},
     '-port'   => $CONFIG->{$species}->{"DBPORT"},
    );
  #add dna_db
   $sdb->dnadb($dna_db);
   my $sic = $sdb->get_StateInfoContainer;
   # assumes dbs were set up using the update_ncRNA script so the analysis ids aer correct.
   my $RFAM = $sic->list_input_ids_by_analysis('2');
   my $jobs = $sic->list_input_ids_by_analysis('7');
   my $miRBase = $sic->list_input_ids_by_analysis('3');
   my $lock = $sdb->get_meta_value_by_key('pipeline.lock');
   die "Pipeline is locked, rulemanager may still be running aborting...\n" if $lock;
   die "RFAM jobs not finished yet ".scalar(@$RFAM)." jobs finished out of ".scalar(@$jobs)." jobs submitted\n" unless (scalar(@$RFAM) == scalar(@$jobs) or $norfam);
   die "miRBase jobs not finished yet ".scalar(@$miRBase)." jobs finished out of ".scalar(@$jobs)." jobs submitted\n" unless (scalar(@$miRBase) == scalar(@$jobs));
   print " ok\n";
  }
 print "Checks complete - loading the next stage of input_ids...\n";

  SPECIES :foreach my $species (@speciess){
  my @input_ids;
  my @flags;
  print "Running species $species\n";
  print "opening connections to databases\n";

  my $sdb = new Bio::EnsEMBL::Pipeline::DBSQL::DBAdaptor
    (
     -host   => $CONFIG->{$species}->{"WRITEHOST"},
     -user   => $WRITEUSER,
     -pass   => $pass,
     -port   => $CONFIG->{$species}->{"WRITEPORT"},
     -dbname => $CONFIG->{$species}->{"WRITENAME"},
    );
;
  my $fa = Bio::EnsEMBL::Pipeline::DBSQL::FlagAdaptor->new($sdb);
  # dont rerun the filtering if it has already been done
  my @test_flags = @{$fa->fetch_all};
  unless (scalar(@test_flags > 0)){
    my $aa = $sdb->get_AnalysisAdaptor;
    my $sa = $sdb->get_SliceAdaptor;
    my $analysis = $aa->fetch_by_logic_name('ncRNA');
    my $mianalysis = $aa->fetch_by_logic_name('BlastmiRNA');
    my $RFanalysis = $aa->fetch_by_logic_name('RfamBlast');
    my $migoalanalysis = $aa->fetch_by_logic_name('miRNA');
    my $limit = 0;
    my %rfam_blasts;
    my %mirbase_blasts;
    my %rfam_threshold;
    my $dafa = $sdb->get_DnaAlignFeatureAdaptor;
    my @dafs;
    unless ($norfam){
      print "reading RFAM family data...\n";
      # fetch them by familly!!!!!!!!!
      my %thr;
      my @domcount =  @{sql("select count(*) , LEFT(hit_name,7) from dna_align_feature where  analysis_id = ". $RFanalysis->dbID .
			    " group by LEFT(hit_name,7) ;",$sdb)};
      foreach my $dom (@domcount){
	$thr{$dom->[1]} = $dom->[0];
      }

      my $total = scalar(keys (%thr));
      my $complete;
      my $last = 0;
      print "\n0_________10________20________30________40________50________60________70________80________90_______100\n";
      foreach my $domain (sort keys %thr){
	$count ++;
	my @dafs;
	if ($thr{$domain} > 2000){
	  my @top_scores = @{sql("SELECT evalue FROM dna_align_feature WHERE analysis_id = ". $RFanalysis->dbID .
				 " AND LEFT(hit_name,7) = '".$domain."' ORDER BY  evalue ASC limit 2000;",$sdb)};
	  my $cutoff = pop (@top_scores)->[0];
	  @dafs = @{$dafa->generic_fetch("left(hit_name,7) = \"$domain\" AND evalue <= $cutoff")};
	} else {
	  @dafs = @{$dafa->generic_fetch("left(hit_name,7) = \"$domain\" ")};
	}
	$complete = int($count/$total*100);
	if ($complete > $last){
	  my $num = $complete -  $last;
	  foreach (my $i = 0; $i < $num; $i++){
	    print "=";
	  }
	}
	$last = $complete;
	@dafs = sort {$a->p_value <=> $b->p_value} @dafs if (scalar(@dafs) > 2000 );
      DAF:  foreach my $daf(@dafs){
	  next if ($daf->p_value > 0.01);
	  #    print $daf->p_value." ";
	  last DAF if ($rfam_blasts{$domain} &&  scalar(@{$rfam_blasts{$domain}}) >= 2000 );
	  push @{$rfam_blasts{$domain}},$daf;
	}
    }
      print "\nGenerating Flags\n";

      foreach my $domain(keys %rfam_blasts){
	my @hits = @{$rfam_blasts{$domain}};
	foreach my $hit (@hits){
	  my $flag = Bio::EnsEMBL::Pipeline::Flag->new
	    (
	     '-type'         => 'dna_align_feature',
	     '-ensembl_id'   => $hit->dbID,
	     '-goalAnalysis' => $analysis,
	    );
	  push @flags,$flag;
	}
      }
    }

    print "Filtering miRNAs";
    print "\n0_________10________20________30________40________50________60________70________80________90_______100\n";

    my %mi_types;
    my @domcount =  @{sql("select count(*) , hit_name from dna_align_feature where  analysis_id = ". $mianalysis->dbID .
			  " group by hit_name;",$sdb)};
    foreach my $dom (@domcount){
      $mi_types{$dom->[1]} = $dom->[0];
    }
   $count = 0;
    my $total = scalar(keys %mi_types);
    my $last = 0;
    foreach my $type (keys %mi_types){
      $count ++;
      if ($mi_types{$type} > 50){
	my @top_scores = @{sql("SELECT evalue FROM dna_align_feature WHERE analysis_id = ". $mianalysis->dbID .
			       " AND hit_name = '".$type."' ORDER BY  evalue ASC limit 50;",$sdb)};
	my $cutoff = pop (@top_scores)->[0];
	@dafs = @{$dafa->generic_fetch("hit_name = \"$type\" AND evalue <= $cutoff")};
      } else {
	@dafs = @{$dafa->generic_fetch("hit_name = \"$type\" ")};
      }
      my $complete = int($count/$total*100);
      if ($complete > $last){
	my $num = $complete -  $last;
	foreach (my $i = 0; $i < $num; $i++){
	  print "=";
	}
      }
      $last = $complete;
      @dafs = sort {$a->p_value <=> $b->p_value} @dafs if (scalar(@dafs) > 50 );
    DAF:  foreach my $daf(@dafs){
	#    print $daf->p_value." ";
	last DAF if ($mirbase_blasts{$type} &&  scalar(@{$mirbase_blasts{$type}}) >= 50 );
	push @{$mirbase_blasts{$type}},$daf;
      }
    }
    print "\nGenerating Flags\n";

    foreach my $domain(keys %mirbase_blasts){
      my @hits = @{$mirbase_blasts{$domain}};
      foreach my $hit (@hits){
	my $flag = Bio::EnsEMBL::Pipeline::Flag->new
	  (
	   '-type'         => 'dna_align_feature',
	   '-ensembl_id'   => $hit->dbID,
	   '-goalAnalysis' => $migoalanalysis,
	  );
	push @flags,$flag;
      }
    }

    print "Storing and randomizing flags so the input ids dont run in families\n";
    while (scalar(@flags >= 1)){
      my $random =  rand($#flags);
      # make sure you have an integer
      $random = int $random;
      $fa->store($flags[$random]);
      splice(@flags,$random,1);
    }
    $count =0;
    print "Making input ids for ncRNA\n";

    die("analysis object not found ncRNA\n") unless ($analysis);
    my @ids = @{$fa->fetch_by_analysis($analysis)};
    @ids = sort {$a->dbID <=> $b->dbID} @ids;
    foreach my $id (@ids){
      push @input_ids,$id->dbID;
    }

    my $inputIDFactory = new Bio::EnsEMBL::Pipeline::Utils::InputIDFactory
      (
       -db => $sdb,
       -top_level => 'top_level',
       -slice     => 1,
       -logic_name => 'DummyFlag',
      );
    $inputIDFactory->input_ids(\@input_ids);
    $inputIDFactory->store_input_ids;
  }
  # add the single input id to start the miRNA job
  # check its not already there first...
  my @check =  @{sql("select count(*) from input_id_analysis where input_id = \"BlastmiRNA\"",$sdb)};
  unless ($check[0]->[0]){
    sql_write(" insert into input_id_analysis(input_id,input_id_type,analysis_id,created) ".
	      "values(\"BlastmiRNA\",\"GENOME\",6,now());",$sdb);
  }

  print "Finished species $species\n";
  # do I want to start the rulemanager again at this point?

  open (SPEC,">$species.csh") or die ("Cannot open file $species.csh");
  print SPEC "#!/bin/csh\n\n";
  print SPEC 'setenv PERL5LIB ', "$DATADIR/$species:$CVSDIR", '/ensembl-analysis/modules:',
     $CVSDIR, '/ensembl-pipeline/modules:', $CVSDIR, '/ensembl/modules:', $BIOPERL_PATH, "\n";

  # if all be well, run the rulemanager
  my $cmd_rulemanager = "bsub -o $species.out -q normal perl $CVSDIR/ensembl-pipeline/scripts/rulemanager.pl ".
    "-dbname  $CONFIG->{$species}->{\"WRITENAME\"} ".
      "-dbport $CONFIG->{$species}->{\"WRITEPORT\"} ".
	"-dbhost $CONFIG->{$species}->{\"WRITEHOST\"} ".
	  "-dbuser ensadmin -dbpass $pass -once\n";

  print SPEC "$cmd_rulemanager\n";
  close(SPEC) || die('Could not close csh script file');
  print "Monitor:\n";
  print 'perl ', $CVSDIR, '/ensembl-pipeline/scripts/monitor -dbname', $CONFIG->{$species}->{'WRITENAME'},
      '-dbport ', $CONFIG->{$species}->{'WRITEPORT'}, '-dbhost ', $CONFIG->{$species}->{'WRITEHOST'},
	  '-dbuser ensadmin -dbpass ', $pass, ' -current -finishedp';

  # set it back to previous
}

exit;

sub sql {
  my ($query,$db) = @_;
  my @array;
#  print "QUERY\n$query\n";
  my $sth = $db->dbc->prepare($query);
  $sth->execute();
  while ( my @row = $sth->fetchrow_array ) {
    push @array , \@row;
  }
  return \@array;
}

sub sql_write {
  my ($query,$db) = @_;
  my $sth = $db->dbc->prepare($query);
  $sth->execute();
  return ;
}
__END__


text:
package com.emistoolbox.common.model.analysis;

import com.emistoolbox.common.excelMerge.ExcelReportConfig;
import com.emistoolbox.common.model.meta.EmisMetaEnum;
import com.emistoolbox.common.model.meta.EmisMetaGroupEnum;
import com.emistoolbox.common.model.priolist.PriorityReportConfig;
import com.emistoolbox.common.renderer.pdfreport.EmisPdfReportConfig;
import com.emistoolbox.common.results.PriorityMetaResult;

import java.util.List;

public interface EmisReportConfig
{
    public int getDefaultDateIndex();
    public void setDefaultDateIndex(int paramInt);

    public List<EmisIndicator> getIndicators();
    public void setIndicators(List<EmisIndicator> paramList);

    public List<EmisPdfReportConfig> getPdfReports();
    public void setPdfReports(List<EmisPdfReportConfig> reports);

    public List<ExcelReportConfig> getExcelReports();
    public void setExcelReports(List<ExcelReportConfig> reports);

    public List<PriorityReportConfig> getPriorityReports();
    public void setPriorityReports(List<PriorityReportConfig> reports);

    public List<EmisMetaGroupEnum> getGroupEnums();
    public List<EmisMetaGroupEnum> getGroupEnums(EmisMetaEnum baseEnum);
    public void setGroupEnums(List<EmisMetaGroupEnum> groupEnums);
}


text:
Hello::Engine.routes.draw do
  # root 'management/profiles#show'

  #
  # REGISTRATION
  #
  scope module: 'registration' do
    get 'sign_up' => 'sign_up#index'
    post 'sign_up' => 'sign_up#create'
    get 'sign_up/widget' => 'sign_up#widget'
    match 'sign_up/disabled' => 'sign_up#disabled', via: [:get, :post]
  end

  #
  # AUTHENTICATION
  #
  scope module: 'authentication' do
    resources :sessions, only: [:index, :new, :show, :destroy]
    delete 'sign_out' => 'sessions#sign_out'

    get  'sign_in' => 'sign_in#index'
    post 'sign_in' => 'sign_in#authenticate'

    get 'sudo_mode' => 'sudo_mode#form'
    patch 'sudo_mode' => 'sudo_mode#authenticate'
    get 'sudo_mode/expire' => 'sudo_mode#expire'
  end

  #
  # MANAGEMENT
  #
  scope module: 'management' do
    resources :accesses, only: [:index, :destroy]

    root 'profiles#show'
    resource :profile, only: [:show, :update, :destroy] do
      member do
        get :cancel
      end
    end

    resources :emails, only: [:index, :create, :destroy] do
      member do
        post 'deliver'
        get 'confirm/:token' => 'confirm_emails#confirm', as: 'confirm'
      end
      collection do
        get 'expired_confirmation_token' => 'confirm_emails#expired_confirmation_token'
      end
    end

    resources :passwords, only: [:index, :show, :update] do
      collection do
        get 'forgot' => 'forgot_password#index'
        post 'forgot' => 'forgot_password#forgot'
      end
      member do
        scope '/reset/:user_id/:token' do
          get '/' => 'reset_password#index', as: 'reset'
          post '/' => 'reset_password#update', as: nil
        end
      end
    end
  end

  #
  # INTERNATIONALIZATION
  #
  scope module: 'internationalization' do
    get 'locale' => 'locale#index'
    post 'locale' => 'locale#update'
  end

end


text:
Directive with isolated scope

	Fiat make: <input type='text' ng-model='carFiat.make'/>

	Fiat hp: <input type='number' ng-model='carFiat.hp'/>

	Red Color: <input type='text' ng-model='colorRed'/>

	Blue Color: <input type='text' ng-model='colorBlue'/>


text:
/*
 * too slow, but correct
 */
#include <stdlib.h>

struct TreeNode {
	int	val;
	struct TreeNode *left;
	struct TreeNode *right;
};

struct link_node {
	struct TreeNode *data;
	struct link_node *next;
	struct link_node *prev;
};

static struct link_node *path, *path_tail, *pathp, *pathq;

static void init(void)
{
	path = path_tail = pathp = pathq = NULL;
}
static void clean(struct link_node *head)
{
	struct link_node *tmp;

	while (head) {
		tmp = head;
		head = head->next;
		free(tmp);
	}
}

static void path_add(struct TreeNode *data)
{
	struct link_node *nodep = malloc(sizeof(struct link_node));
	nodep->data = data;
	nodep->next = nodep->prev = NULL;
	if (path == NULL) {
		path = path_tail = nodep;
	} else {
		path_tail->next = nodep;
		nodep->prev = path_tail;
		path_tail = nodep;
	}
}

static void path_rm(void)
{
	struct link_node *tail_bak;

	tail_bak = path_tail;
	path_tail = path_tail->prev;
	if (path_tail == NULL)
		path = NULL;
	else
		path_tail->next = NULL;
	free(tail_bak);
}

static struct link_node *path_cpy(void)
{
	struct link_node *newpath, *newtail, *tmp1, *tmp2;

	newpath = NULL;
	for (tmp1 = path; tmp1; tmp1 = tmp1->next) {
		tmp2 = malloc(sizeof(struct link_node));
		tmp2->next = NULL;
		tmp2->data = tmp1->data;
		if (newpath == NULL) {
			newpath = newtail = tmp2;
		} else {
			newtail->next = tmp2;
			newtail = tmp2;
		}
	}
	return(newpath);
}

static void trav(struct TreeNode *root, struct TreeNode *p,
		struct TreeNode *q)
{
	if (root == NULL)
		return;
	path_add(root);
	if (root == p)
		pathp = path_cpy();
	if (root == q)
		pathq = path_cpy();
	trav(root->left, p, q);
	trav(root->right, p, q);
	path_rm();
}

struct TreeNode *lowestCommonAncestor(struct TreeNode *root,
		struct TreeNode *p, struct TreeNode *q)
{
	struct TreeNode *ance;
	struct link_node *tmp1, *tmp2;

	init();
	trav(root, p, q);
	if (pathp == NULL || pathq == NULL) {
		ance = NULL;
		goto out;
	}

	for (tmp1 = pathp, tmp2 = pathq; tmp1 && tmp2; tmp1 = tmp1->next,
			tmp2 = tmp2->next) {
		if (tmp1->data != tmp2->data)
			break;
		ance = tmp1->data;
	}
out:
	clean(pathp);
	clean(pathq);
	return ance;
}

int main(void)
{
}


text:
# Title: ToDo Classification Sample
**Abstract:** Highlight any instances of the text 'ToDo' in the Visual Studio
Editor and display a glyph in the corresponding line.
[ View this sample online ](https://github.com/Microsoft/VSSDK-Extensibility-Samples).

* Technologies: Visual Studio 2015 SDK

* Topics: Visual Studio Shell, VSX

* Last Updated: 05/21/2015

** Description**

This sample provides a general purpose TodoTagger as well as classification
and a glyph factory. Anytime _ToDo_ appears in the text editor, it will be
highlighted and a glyph will be displayed on that line.

  * The binaries for this sample can also be installed via the extension manager.
  * This is the sample code written during the Visual Studio Ecosystem Summit presentation ** I Want Coloring: A scenario based look at the new editor**

**Requirements**

[ Visual Studio 2015 ](http://www.microsoft.com/visualstudio/en-us/try/default.mspx#download)

[ Visual Studio 2015 SDK ](https://www.visualstudio.com/en-us/downloads/visual-studio-2015-downloads-vs.aspx)

** Build the sample**

  * Download the zip file associated with the sample
  * Unzip the sample to your machine
  * Double click on the .sln file to launch the solution

** Run the sample**

  1. To run the sample, hit F5 or choose the ** Debug > Start Debugging** menu command. A new instance of Visual Studio will launch under the experimental hive.
  2. Once loaded, open any file in the Text Editor.
  3. Type _ToDo_ anywhere in the Text Editor.
  4. _ToDo_ is highlighted, and a glyph is displayed on that line in the glyph column.

**Related topics**

* [ Editor Documentation ](https://msdn.microsoft.com/en-us/library/dd885118(v=vs.140).aspx)
* [ Visual Studio SDK Documentation ](https://msdn.microsoft.com/en-us/library/bb166441(v=vs.140).aspx)


text:
NS_ASSUME_NONNULL_BEGIN

//Any string can be used for convienence,
//but you are encouraged to implement these methods on your custom classes for re-usability
@interface NSString (WMFAnalytics) <WMFAnalyticsContextProviding, WMFAnalyticsContentTypeProviding>

@end

@interface PiwikTracker (WMFExtensions)

+ (void)wmf_start;

- (void)wmf_logView:(id<WMFAnalyticsViewNameProviding>)view;

- (void)wmf_logActionImpressionInContext:(id<WMFAnalyticsContextProviding>)context contentType:(id<WMFAnalyticsContentTypeProviding>)contentType;

- (void)wmf_logActionPreviewInContext:(id<WMFAnalyticsContextProviding>)context contentType:(id<WMFAnalyticsContentTypeProviding>)contentType;
- (void)wmf_logActionPreviewInContext:(id<WMFAnalyticsContextProviding>)context contentType:(id<WMFAnalyticsContentTypeProviding>)contentType date:(nullable NSDate *)date;

- (void)wmf_logActionTapThroughInContext:(id<WMFAnalyticsContextProviding>)context contentType:(id<WMFAnalyticsContentTypeProviding>)contentType;
- (void)wmf_logActionTapThroughMoreInContext:(id<WMFAnalyticsContextProviding>)context contentType:(id<WMFAnalyticsContentTypeProviding>)contentType;

- (void)wmf_logActionSaveInContext:(id<WMFAnalyticsContextProviding>)context contentType:(id<WMFAnalyticsContentTypeProviding>)contentType;
- (void)wmf_logActionUnsaveInContext:(id<WMFAnalyticsContextProviding>)context contentType:(id<WMFAnalyticsContentTypeProviding>)contentType;

- (void)wmf_logActionSwitchLanguageInContext:(id<WMFAnalyticsContextProviding>)context contentType:(id<WMFAnalyticsContentTypeProviding>)contentType;

- (void)wmf_logActionEnableInContext:(id<WMFAnalyticsContextProviding>)context contentType:(id<WMFAnalyticsContentTypeProviding>)contentType;
- (void)wmf_logActionDisableInContext:(id<WMFAnalyticsContextProviding>)context contentType:(id<WMFAnalyticsContentTypeProviding>)contentType;

- (void)wmf_logActionPushInContext:(id<WMFAnalyticsContextProviding>)context contentType:(id<WMFAnalyticsContentTypeProviding>)contentType date:(nullable NSDate *)date;

@end

NS_ASSUME_NONNULL_END


text:
title: "Simplify checkout with requestAutocomplete API"
description: "Embora o requestAutocomplete tenha sido criado para ajudar o usuário a preencher qualquer formulário, seu uso mais comum nos dias de hoje é no eCommerce, onde o abandono do carrinho de compras na Web móvel pode ser de até 97%."
updated_on: 2014-10-21
key-takeaways:
  use-request-auto-complete:
    - "O requestAutocomplete pode simplificar muito o processo de finalização da compra e melhorar a experiência do usuário."
    - "Se requestAutocomplete estiver disponível, oculte o formulário de finalização da compra e direcione o usuário diretamente para a página de confirmação."
    - "Certifique-se de que os campos de entrada incluem o atributo autocomplete adequado."
notes:
  use-placeholders:
    - "Os espaços reservados desaparecem assim que o foco é colocado em um elemento, portanto não substituem etiquetas.  Eles devem ser usados como um auxílio para ajudar a orientar o usuário no formato e conteúdo exigidos."
  recommend-input:
    - "O preenchimento automático funciona apenas quando o método de formulário é mensagem."
  use-datalist:
    - "Os valores datalist são fornecidos como sugestões e o usuário não fica restrito às sugestões fornecidas."
  provide-real-time-validation:
    - "Mesmo com validação de entrada do lado do cliente, é importante validar dados no servidor para garantir consistência e segurança em seus dados."
  show-all-errors:
    - "Mostre ao usuário todos os problemas no formulário de uma vez ao invés de mostrá-los um a um."
  request-auto-complete-flow:
    - "Ao solicitar qualquer tipo de informação pessoal ou dados de cartão de crédito, certifique-se de que a página é disponibilizada via SSL.  Caso contrário, o diálogo avisará o usuário que suas informações podem não estar seguras."
---

  Embora o requestAutocomplete tenha sido criado para ajudar o usuário a preencher qualquer formulário, seu uso mais comum nos dias de hoje é no eCommerce, onde o abandono do carrinho de compras na Web móvel pode ser de até 97%. Imagine 97% das pessoas em um supermercado, com um carrinho cheio de coisas, deixando-o e indo embora.

{% include shared/takeaway.liquid list=page.key-takeaways.use-request-auto-complete %}

Em vez confiar em um determinado provedor de pagamentos,
o `requestAutocomplete` solicita detalhes de pagamento (como nome, endereço e informação do cartão de
crédito) a partir do navegador, onde são opcionalmente armazenados
assim como outros campos de preenchimento automático.

{% ytvideo ljYeHwGgzQk %}

### fluxo do `requestAutocomplete`

A experiência ideal mostra a caixa de diálogo `requestAutocomplete` em vez de carregar a
página que exibe o formulário de finalização da compra. Se tudo correr bem, o usuário não vê
o formulário.  Pode-se adicionar facilmente `requestAutocomplete` aos formulários existentes
sem alteração alguma nos nomes de campos.  Basta adicionar o atributo `autocomplete`
a cada elemento do formulário com o valor adequado e adicionar a função
`requestAutocomplete()` no elemento do formulário. O navegador fará
o resto.

{% include_code src=_code/rac.html snippet=rac lang=javascript %}

A função `requestAutocomplete` no elemento `form` indica que o
navegador deve preencher o formulário.  Como um recurso de segurança, a função
deve ser chamada através de um gesto do usuário, como um toque ou um clique do mouse. Uma caixa de diálogo é
mostrada pedindo a permissão do usuário para preencher os campos e quais detalhes
ele deseja utilizar.

{% include_code src=_code/rac.html snippet=handlerac lang=javascript %}

Depois da conclusão do `requestAutocomplete`, a função acionará o evento
`autocomplete` se tiver concluído com êxito ou `autocompleteerror` se
não foi possível preencher o formulário.  Se for concluído com êxito e o formulário
estiver de acordo com as suas necessidades, basta enviá-lo e continuar com a confirmação
final.

{% include shared/remember.liquid title="Remember" list=page.notes.request-auto-complete-flow %}


text:
from swgpy.object import *

def create(kernel):
	result = Tangible()

	result.template = "object/tangible/wearables/armor/ubese/shared_armor_ubese_shirt.iff"
	result.attribute_template_id = 0
	result.stfName("wearables_name","armor_ubese_shirt")

	#### BEGIN MODIFICATIONS ####
	####  END MODIFICATIONS  ####

	return result


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;

namespace KayakoRestApi.Core.Tickets
{
    /// <summary>
    /// Definition of a list of ticket posts
    ///
    /// <remarks>
    /// See : http://wiki.kayako.com/display/DEV/REST+-+TicketPost
    /// </remarks>
    /// </summary>
    [XmlRoot("posts")]
    public class TicketPostCollection : List<TicketPost>
    {
        /// <summary>
        /// Create a list of ticket posts.
        /// </summary>
        public TicketPostCollection()
        {
        }
    }
}


text:
package com.sun.tools.xjc.generator.annotation.spec;

import jakarta.xml.bind.annotation.XmlElementDecl;
import com.sun.codemodel.JAnnotationWriter;
import com.sun.codemodel.JType;

/**
 *

 *     Auto-generated, do not edit.
 *

 */
public interface XmlElementDeclWriter
    extends JAnnotationWriter<XmlElementDecl>
{

    XmlElementDeclWriter name(String value);

    XmlElementDeclWriter scope(Class value);

    XmlElementDeclWriter scope(JType value);

    XmlElementDeclWriter namespace(String value);

    XmlElementDeclWriter defaultValue(String value);

    XmlElementDeclWriter substitutionHeadNamespace(String value);

    XmlElementDeclWriter substitutionHeadName(String value);

}


text:
 jQuery.Plugin.wAlert is best way to display a sample message, support not iOS/Android drive.
##Demo Page
http://williesmithchen.github.io/jQuery.plugin.wAlert/


text:
package org.apache.xmlbeans.test.performance.v2;

import java.io.CharArrayReader;

import org.apache.xmlbeans.XmlCursor;
import org.apache.xmlbeans.XmlObject;
import org.apache.xmlbeans.test.performance.utils.Constants;
import org.apache.xmlbeans.test.performance.utils.PerfUtil;

public class CursorGetElementV2
{

  public static void main(String[] args) throws Exception
  {

    final int iterations = Constants.GET_SET_ITERATIONS;
    String flavor;

    // the only flavors that should be used are
    // wide-text and any others that have text values (none of as 8/18/04)
    // because this scenario focuses on element values
    if(args.length == 0)
      flavor = "wide-text";
    else
      flavor = args[0];

    CursorGetElementV2 test = new CursorGetElementV2();
    PerfUtil util = new PerfUtil();
    long cputime;
    int hash = 0;

    // get the xml cursor
    char[] chars = util.createXmlData(flavor, Constants.XML_SIZE);
    XmlObject doc = XmlObject.Factory.parse(new CharArrayReader(chars));
    XmlCursor cursor = doc.newCursor();

    // warm up the vm
    cputime = System.currentTimeMillis();
    for(int i=0; i<iterations; i++){
      hash += test.run(cursor);
      cursor.toStartDoc();
    }
    cputime = System.currentTimeMillis() - cputime;

    // run it again for the real measurement
    cputime = System.currentTimeMillis();
    for(int i=0; i<iterations; i++){
      hash += test.run(cursor);
      cursor.toStartDoc();
    }
    cputime = System.currentTimeMillis() - cputime;

    // print the results
    // Class.getSimpleName() is only provided in jdk1.5, so have to trim package name off test name for logging to support 1.4
    System.out.print(Constants.DELIM+test.getClass().getName().substring(test.getClass().getName().lastIndexOf('.')+1)+" flavor="+flavor+" ");
    System.out.print("hash "+hash+" ");
    System.out.print("time "+cputime+" ");
    System.out.print("time/it " + ((double)cputime)/((double)iterations) + "\n");
  }

  private int run(XmlCursor p_cursor) throws Exception
  {
    p_cursor.toFirstChild();
    p_cursor.toFirstChild();
    return p_cursor.getTextValue().length() * 17;
  }
}


text:
package com.facebook.imagepipeline.core;

import javax.annotation.concurrent.NotThreadSafe;

import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Rect;
import android.os.Build;

import com.facebook.cache.common.CacheKey;
import com.facebook.cache.disk.DiskCacheFactory;
import com.facebook.cache.disk.DiskStorageCache;
import com.facebook.common.executors.DefaultSerialExecutorService;
import com.facebook.common.executors.SerialExecutorService;
import com.facebook.common.executors.UiThreadImmediateExecutorService;
import com.facebook.common.internal.AndroidPredicates;
import com.facebook.common.internal.Preconditions;
import com.facebook.common.time.MonotonicClock;
import com.facebook.common.time.RealtimeSinceBootClock;
import com.facebook.imagepipeline.animated.base.AnimatedDrawableBackend;
import com.facebook.imagepipeline.animated.base.AnimatedDrawableOptions;
import com.facebook.imagepipeline.animated.base.AnimatedImageResult;
import com.facebook.imagepipeline.animated.factory.AnimatedDrawableFactory;
import com.facebook.imagepipeline.animated.factory.AnimatedImageFactory;
import com.facebook.imagepipeline.animated.impl.AnimatedDrawableBackendImpl;
import com.facebook.imagepipeline.animated.impl.AnimatedDrawableBackendProvider;
import com.facebook.imagepipeline.animated.impl.AnimatedDrawableCachingBackendImpl;
import com.facebook.imagepipeline.animated.impl.AnimatedDrawableCachingBackendImplProvider;
import com.facebook.imagepipeline.animated.util.AnimatedDrawableUtil;
import com.facebook.imagepipeline.bitmaps.ArtBitmapFactory;
import com.facebook.imagepipeline.bitmaps.DalvikBitmapFactory;
import com.facebook.imagepipeline.bitmaps.EmptyJpegGenerator;
import com.facebook.imagepipeline.bitmaps.GingerbreadBitmapFactory;
import com.facebook.imagepipeline.bitmaps.PlatformBitmapFactory;
import com.facebook.imagepipeline.cache.BitmapCountingMemoryCacheFactory;
import com.facebook.imagepipeline.cache.BitmapMemoryCacheFactory;
import com.facebook.imagepipeline.cache.BufferedDiskCache;
import com.facebook.imagepipeline.cache.CountingMemoryCache;
import com.facebook.imagepipeline.cache.EncodedCountingMemoryCacheFactory;
import com.facebook.imagepipeline.cache.EncodedMemoryCacheFactory;
import com.facebook.imagepipeline.cache.MemoryCache;
import com.facebook.imagepipeline.decoder.ImageDecoder;
import com.facebook.imagepipeline.image.CloseableImage;
import com.facebook.imagepipeline.memory.PoolFactory;
import com.facebook.imagepipeline.memory.PooledByteBuffer;

/**
 * Factory class for the image pipeline.
 *
 *
This class constructs the pipeline and its dependencies from other libraries.
 *
 *
As the pipeline object can be quite expensive to create, it is strongly
 * recommended that applications create just one instance of this class
 * and of the pipeline.
 */
@NotThreadSafe
public class ImagePipelineFactory {

  private static ImagePipelineFactory sInstance = null;

  /** Gets the instance of {@link ImagePipelineFactory}. */
  public static ImagePipelineFactory getInstance() {
    return Preconditions.checkNotNull(sInstance, "ImagePipelineFactory was not initialized!");
  }

  /** Initializes {@link ImagePipelineFactory} with default config. */
  public static void initialize(Context context) {
    initialize(ImagePipelineConfig.newBuilder(context).build());
  }

  /** Initializes {@link ImagePipelineFactory} with the specified config. */
  public static void initialize(ImagePipelineConfig imagePipelineConfig) {
    sInstance = new ImagePipelineFactory(imagePipelineConfig);
  }

  /** Shuts {@link ImagePipelineFactory} down. */
  public static void shutDown() {
    if (sInstance != null) {
      sInstance.getBitmapMemoryCache().removeAll(AndroidPredicates.<CacheKey>True());
      sInstance.getEncodedMemoryCache().removeAll(AndroidPredicates.<CacheKey>True());
      sInstance = null;
    }
  }

  private final ImagePipelineConfig mConfig;

  private AnimatedDrawableUtil mAnimatedDrawableUtil;
  private AnimatedDrawableFactory mAnimatedDrawableFactory;
  private AnimatedImageFactory mAnimatedImageFactory;
  private CountingMemoryCache<CacheKey, CloseableImage>
      mBitmapCountingMemoryCache;
  private MemoryCache<CacheKey, CloseableImage> mBitmapMemoryCache;
  private CountingMemoryCache<CacheKey, PooledByteBuffer> mEncodedCountingMemoryCache;
  private MemoryCache<CacheKey, PooledByteBuffer> mEncodedMemoryCache;
  private BufferedDiskCache mMainBufferedDiskCache;
  private DiskStorageCache mMainDiskStorageCache;
  private ImageDecoder mImageDecoder;
  private ImagePipeline mImagePipeline;
  private PlatformBitmapFactory mPlatformBitmapFactory;
  private ProducerFactory mProducerFactory;
  private ProducerSequenceFactory mProducerSequenceFactory;
  private BufferedDiskCache mSmallImageBufferedDiskCache;
  private DiskStorageCache mSmallImageDiskStorageCache;

  public ImagePipelineFactory(ImagePipelineConfig config) {
    mConfig = Preconditions.checkNotNull(config);
  }

  // We need some of these methods public for now so internal code can use them.

  private AnimatedDrawableUtil getAnimatedDrawableUtil() {
    if (mAnimatedDrawableUtil == null) {
      mAnimatedDrawableUtil = new AnimatedDrawableUtil();
    }
    return mAnimatedDrawableUtil;
  }

  public static AnimatedImageFactory buildAnimatedImageFactory(
      final AnimatedDrawableUtil animatedDrawableUtil,
      PlatformBitmapFactory platformBitmapFactory) {
    AnimatedDrawableBackendProvider animatedDrawableBackendProvider =
        new AnimatedDrawableBackendProvider() {
          @Override
          public AnimatedDrawableBackend get(AnimatedImageResult imageResult, Rect bounds) {
            return new AnimatedDrawableBackendImpl(animatedDrawableUtil, imageResult, bounds);
          }
        };
   return new AnimatedImageFactory(animatedDrawableBackendProvider, platformBitmapFactory);
  }

  private AnimatedImageFactory getAnimatedImageFactory() {
    if (mAnimatedImageFactory == null) {
      if (mConfig.getAnimatedImageFactory() != null) {
        mAnimatedImageFactory = mConfig.getAnimatedImageFactory();
      } else {
        mAnimatedImageFactory = buildAnimatedImageFactory(
            getAnimatedDrawableUtil(),
            getPlatformBitmapFactory());
      }
    }
    return mAnimatedImageFactory;
  }

  public CountingMemoryCache<CacheKey, CloseableImage>
      getBitmapCountingMemoryCache() {
    if (mBitmapCountingMemoryCache == null) {
      mBitmapCountingMemoryCache =
          BitmapCountingMemoryCacheFactory.get(
              mConfig.getBitmapMemoryCacheParamsSupplier(),
              mConfig.getMemoryTrimmableRegistry());
    }
    return mBitmapCountingMemoryCache;
  }

  public MemoryCache<CacheKey, CloseableImage> getBitmapMemoryCache() {
    if (mBitmapMemoryCache == null) {
      mBitmapMemoryCache =
          BitmapMemoryCacheFactory.get(
              getBitmapCountingMemoryCache(),
              mConfig.getImageCacheStatsTracker());
    }
    return mBitmapMemoryCache;
  }

  public CountingMemoryCache<CacheKey, PooledByteBuffer> getEncodedCountingMemoryCache() {
    if (mEncodedCountingMemoryCache == null) {
      mEncodedCountingMemoryCache =
          EncodedCountingMemoryCacheFactory.get(
              mConfig.getEncodedMemoryCacheParamsSupplier(),
              mConfig.getMemoryTrimmableRegistry());
    }
    return mEncodedCountingMemoryCache;
  }

  public MemoryCache<CacheKey, PooledByteBuffer> getEncodedMemoryCache() {
    if (mEncodedMemoryCache == null) {
      mEncodedMemoryCache =
          EncodedMemoryCacheFactory.get(
              getEncodedCountingMemoryCache(),
              mConfig.getImageCacheStatsTracker());
    }
    return mEncodedMemoryCache;
  }

  private ImageDecoder getImageDecoder() {
    if (mImageDecoder == null) {
      if (mConfig.getImageDecoder() != null) {
        mImageDecoder = mConfig.getImageDecoder();
      } else {
        mImageDecoder = new ImageDecoder(getAnimatedImageFactory(), getPlatformBitmapFactory());
      }
    }
    return mImageDecoder;
  }

  private BufferedDiskCache getMainBufferedDiskCache() {
    if (mMainBufferedDiskCache == null) {
      mMainBufferedDiskCache =
          new BufferedDiskCache(
              getMainDiskStorageCache(),
              mConfig.getPoolFactory().getPooledByteBufferFactory(),
              mConfig.getPoolFactory().getPooledByteStreams(),
              mConfig.getExecutorSupplier().forLocalStorageRead(),
              mConfig.getExecutorSupplier().forLocalStorageWrite(),
              mConfig.getImageCacheStatsTracker());
    }
    return mMainBufferedDiskCache;
  }

  public DiskStorageCache getMainDiskStorageCache() {
    if (mMainDiskStorageCache == null) {
      mMainDiskStorageCache =
          DiskCacheFactory.newDiskStorageCache(mConfig.getMainDiskCacheConfig());
    }
    return mMainDiskStorageCache;
  }

  public ImagePipeline getImagePipeline() {
    if (mImagePipeline == null) {
      mImagePipeline =
          new ImagePipeline(
              getProducerSequenceFactory(),
              mConfig.getRequestListeners(),
              mConfig.getIsPrefetchEnabledSupplier(),
              getBitmapMemoryCache(),
              getEncodedMemoryCache(),
              getMainDiskStorageCache(),
              getSmallImageDiskStorageCache(),
              mConfig.getCacheKeyFactory());
    }
    return mImagePipeline;
  }

  public static PlatformBitmapFactory buildPlatformBitmapFactory(
      PoolFactory poolFactory,
      boolean isDownsampleEnabled) {
    GingerbreadBitmapFactory factoryGingerbread =
        Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB ?
            new GingerbreadBitmapFactory() : null;
    DalvikBitmapFactory factoryICS = new DalvikBitmapFactory(
        new EmptyJpegGenerator(poolFactory.getPooledByteBufferFactory()),
        poolFactory.getFlexByteArrayPool(),
        isDownsampleEnabled);
    ArtBitmapFactory factoryLollipop = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ?
        new ArtBitmapFactory(
            poolFactory.getBitmapPool(),
            poolFactory.getFlexByteArrayPoolMaxNumThreads(),
            isDownsampleEnabled) :
        null;
    return new PlatformBitmapFactory(factoryGingerbread, factoryICS, factoryLollipop);
  }

  private PlatformBitmapFactory getPlatformBitmapFactory() {
    if (mPlatformBitmapFactory == null) {
      mPlatformBitmapFactory = buildPlatformBitmapFactory(
          mConfig.getPoolFactory(),
          mConfig.isDownsampleEnabled());
    }
    return mPlatformBitmapFactory;
  }

  private ProducerFactory getProducerFactory() {
    if (mProducerFactory == null) {
      mProducerFactory =
          new ProducerFactory(
              mConfig.getContext(),
              mConfig.getPoolFactory().getSmallByteArrayPool(),
              getImageDecoder(),
              mConfig.getProgressiveJpegConfig(),
              mConfig.isDownsampleEnabled(),
              mConfig.getExecutorSupplier(),
              mConfig.getPoolFactory().getPooledByteBufferFactory(),
              getBitmapMemoryCache(),
              getEncodedMemoryCache(),
              getMainBufferedDiskCache(),
              getSmallImageBufferedDiskCache(),
              mConfig.getCacheKeyFactory(),
              getPlatformBitmapFactory());
    }
    return mProducerFactory;
  }

  private ProducerSequenceFactory getProducerSequenceFactory() {
    if (mProducerSequenceFactory == null) {
      mProducerSequenceFactory =
          new ProducerSequenceFactory(
              getProducerFactory(),
              mConfig.getNetworkFetcher(),
              mConfig.isResizeAndRotateEnabledForNetwork());
    }
    return mProducerSequenceFactory;
  }

  public DiskStorageCache getSmallImageDiskStorageCache() {
    if (mSmallImageDiskStorageCache == null) {
      mSmallImageDiskStorageCache =
          DiskCacheFactory.newDiskStorageCache(mConfig.getSmallImageDiskCacheConfig());
    }
    return mSmallImageDiskStorageCache;
  }

  private BufferedDiskCache getSmallImageBufferedDiskCache() {
    if (mSmallImageBufferedDiskCache == null) {
      mSmallImageBufferedDiskCache =
          new BufferedDiskCache(
              getSmallImageDiskStorageCache(),
              mConfig.getPoolFactory().getPooledByteBufferFactory(),
              mConfig.getPoolFactory().getPooledByteStreams(),
              mConfig.getExecutorSupplier().forLocalStorageRead(),
              mConfig.getExecutorSupplier().forLocalStorageWrite(),
              mConfig.getImageCacheStatsTracker());
    }
    return mSmallImageBufferedDiskCache;
  }

  public AnimatedDrawableFactory getAnimatedDrawableFactory() {
    if (mAnimatedDrawableFactory == null) {
      final AnimatedDrawableUtil animatedDrawableUtil = getAnimatedDrawableUtil();
      final MonotonicClock monotonicClock = RealtimeSinceBootClock.get();
      final SerialExecutorService serialExecutorService =
          new DefaultSerialExecutorService(mConfig.getExecutorSupplier().forDecode());
      final ActivityManager activityManager =
          (ActivityManager) mConfig.getContext().getSystemService(Context.ACTIVITY_SERVICE);

      AnimatedDrawableCachingBackendImplProvider animatedDrawableCachingBackendImplProvider =
          new AnimatedDrawableCachingBackendImplProvider() {
            @Override
            public AnimatedDrawableCachingBackendImpl get(
                AnimatedDrawableBackend animatedDrawableBackend,
                AnimatedDrawableOptions options) {
              return new AnimatedDrawableCachingBackendImpl(
                  serialExecutorService,
                  activityManager,
                  animatedDrawableUtil,
                  monotonicClock,
                  animatedDrawableBackend,
                  options);
            }
          };

      AnimatedDrawableBackendProvider backendProvider = new AnimatedDrawableBackendProvider() {
        @Override
        public AnimatedDrawableBackend get(AnimatedImageResult animatedImageResult, Rect bounds) {
          return new AnimatedDrawableBackendImpl(animatedDrawableUtil, animatedImageResult, bounds);
        }
      };

      mAnimatedDrawableFactory = new AnimatedDrawableFactory(
          backendProvider,
          animatedDrawableCachingBackendImplProvider,
          animatedDrawableUtil,
          UiThreadImmediateExecutorService.getInstance(),
          mConfig.getContext().getResources());
    }
    return mAnimatedDrawableFactory;
  }
}


text:
'use strict';

require('../../support/test-helper');

var assert = require('../../support/assert');
var step = require('step');
var cartodbServer = require('../../../lib/server');
var ServerOptions = require('./support/ported-server-options');
var testClient = require('./support/test-client');
var TestClient = require('../../support/test-client');

describe('multilayer error cases', function () {
    var server;

    before(function () {
        server = cartodbServer(ServerOptions);
        server.setMaxListeners(0);
    });

    // var client = null;
    afterEach(function (done) {
        if (this.client) {
            return this.client.drain(done);
        }
        return done();
    });

    it('post layergroup with wrong Content-Type', function (done) {
        assert.response(server, {
            url: '/api/v1/map',
            method: 'POST',
            headers: {
                host: 'localhost',
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        }, {}, function (res) {
            assert.strictEqual(res.statusCode, 400, res.body);
            var parsedBody = JSON.parse(res.body);
            assert.deepStrictEqual(parsedBody.errors, ['POST data must be of type application/json']);
            done();
        });
    });

    it('post layergroup with no layers', function (done) {
        assert.response(server, {
            url: '/api/v1/map',
            method: 'POST',
            headers: {
                host: 'localhost',
                'Content-Type': 'application/json'
            }
        }, {}, function (res) {
            assert.strictEqual(res.statusCode, 400, res.body);
            var parsedBody = JSON.parse(res.body);
            assert.deepStrictEqual(parsedBody.errors, ['Missing layers array from layergroup config']);
            done();
        });
    });

    it('post layergroup jsonp errors are returned with 200 status', function (done) {
        assert.response(server, {
            url: '/api/v1/map?callback=test',
            method: 'POST',
            headers: {
                host: 'localhost',
                'Content-Type': 'application/json'
            }
        }, {}, function (res) {
            assert.strictEqual(res.statusCode, 200);
            assert.strictEqual(
                res.body,
                '/**/ typeof test === \'function\' && ' +
                'test({"errors":["Missing layers array from layergroup config"],' +
                '"errors_with_context":[{"type":"unknown",' +
                '"message":"Missing layers array from layergroup config"}]});'
            );
            done();
        });
    });

    it('layergroup with no cartocss_version', function (done) {
        var layergroup = {
            version: '1.0.0',
            layers: [
                {
                    options: {
                        sql: 'select cartodb_id, ST_Translate(the_geom, 50, 0) as the_geom from test_table limit 2',
                        cartocss: '#layer { marker-fill:red; marker-width:32; marker-allow-overlap:true; }',
                        geom_column: 'the_geom'
                    }
                }
            ]
        };
        assert.response(server, {
            url: '/api/v1/map',
            method: 'POST',
            headers: {
                host: 'localhost',
                'Content-Type': 'application/json'
            },
            data: JSON.stringify(layergroup)
        }, {}, function (res) {
            assert.strictEqual(res.statusCode, 400, res.body);
            var parsedBody = JSON.parse(res.body);
            assert.deepStrictEqual(parsedBody.errors, ['Missing cartocss_version for layer 0 options']);
            done();
        });
    });

    it('sql/cartocss combination errors', function (done) {
        var layergroup = {
            version: '1.0.1',
            layers: [{
                options: {
                    sql: "select 1 as i, 'LINESTRING(0 0, 1 0)'::geometry as the_geom",
                    cartocss_version: '2.0.2',
                    cartocss: '#layer [missing=1] { line-width:16; }',
                    geom_column: 'the_geom'
                }
            }]
        };
        assert.response(server, {
            url: '/api/v1/map',
            method: 'POST',
            headers: {
                host: 'localhost',
                'Content-Type': 'application/json'
            },
            data: JSON.stringify(layergroup)
        }, {}, function (res) {
            try {
                assert.strictEqual(res.statusCode, 400, res.statusCode + ': ' + res.body);
                // See http://github.com/CartoDB/Windshaft/issues/159
                var parsed = JSON.parse(res.body);
                assert.ok(parsed);
                assert.strictEqual(parsed.errors.length, 1);
                var error = parsed.errors[0];
                assert.ok(error.match(/column "missing" does not exist/m), error);
                // cannot check for error starting with style0 until a new enough mapnik
                // is used: https://github.com/mapnik/mapnik/issues/1924
                // assert.ok(error.match(/^style0/), "Error doesn't start with style0: " + error);
                // TODO: check which layer introduced the problem ?
                done();
            } catch (err) { done(err); }
        });
    });

    it('sql/interactivity combination error', function (done) {
        var layergroup = {
            version: '1.0.1',
            layers: [
                {
                    options: {
                        sql: "select 1 as i, st_setsrid('LINESTRING(0 0, 1 0)'::geometry, 4326) as the_geom",
                        cartocss_version: '2.0.2',
                        cartocss: '#layer { line-width:16; }',
                        interactivity: 'i',
                        geom_column: 'the_geom'
                    }
                },
                {
                    options: {
                        sql: "select 1 as i, st_setsrid('LINESTRING(0 0, 1 0)'::geometry, 4326) as the_geom",
                        cartocss_version: '2.0.2',
                        cartocss: '#layer { line-width:16; }',
                        geom_column: 'the_geom'
                    }
                },
                {
                    options: {
                        sql: "select 1 as i, st_setsrid('LINESTRING(0 0, 1 0)'::geometry, 4326) as the_geom",
                        cartocss_version: '2.0.2',
                        cartocss: '#layer { line-width:16; }',
                        interactivity: 'missing',
                        geom_column: 'the_geom'
                    }
                }
            ]
        };
        this.client = new TestClient(layergroup);
        this.client.getLayergroup({ response: { status: 400 } }, function (err, parsed) {
            assert.ok(!err, err);
            assert.ok(parsed);
            assert.strictEqual(parsed.errors.length, 1);
            var error = parsed.errors[0];
            assert.ok(error.match(/column "missing" does not exist/m), error);
            done();
        });
    });

    it('blank CartoCSS error', function (done) {
        var layergroup = {
            version: '1.0.1',
            layers: [
                {
                    options: {
                        sql: "select 1 as i, 'LINESTRING(0 0, 1 0)'::geometry as the_geom",
                        cartocss_version: '2.0.2',
                        cartocss: '#style { line-width:16 }',
                        interactivity: 'i',
                        geom_column: 'the_geom'
                    }
                },
                {
                    options: {
                        sql: "select 1 as i, 'LINESTRING(0 0, 1 0)'::geometry as the_geom",
                        cartocss_version: '2.0.2',
                        cartocss: '',
                        interactivity: 'i',
                        geom_column: 'the_geom'
                    }
                }
            ]
        };
        assert.response(server, {
            url: '/api/v1/map',
            method: 'POST',
            headers: {
                host: 'localhost',
                'Content-Type': 'application/json'
            },
            data: JSON.stringify(layergroup)
        }, {}, function (res) {
            try {
                assert.strictEqual(res.statusCode, 400, res.statusCode + ': ' + res.body);
                var parsed = JSON.parse(res.body);
                assert.ok(parsed);
                assert.strictEqual(parsed.errors.length, 1);
                var error = parsed.errors[0];
                assert.ok(error.match(/^style1: CartoCSS is empty/), error);
                done();
            } catch (err) { done(err); }
        });
    });

    it('Invalid mapnik-geometry-type CartoCSS error', function (done) {
        var layergroup = {
            version: '1.0.1',
            layers: [
                {
                    options: {
                        sql: "select 1 as i, 'LINESTRING(0 0, 1 0)'::geometry as the_geom",
                        cartocss_version: '2.0.2',
                        cartocss: '#style [mapnik-geometry-type=bogus] { line-width:16 }',
                        geom_column: 'the_geom'
                    }
                },
                {
                    options: {
                        sql: "select 1 as i, 'LINESTRING(0 0, 1 0)'::geometry as the_geom",
                        cartocss_version: '2.0.2',
                        cartocss: '#style [mapnik-geometry-type=bogus] { line-width:16 }',
                        geom_column: 'the_geom'
                    }
                }
            ]
        };
        assert.response(server, {
            url: '/api/v1/map',
            method: 'POST',
            headers: {
                host: 'localhost',
                'Content-Type': 'application/json'
            },
            data: JSON.stringify(layergroup)
        }, {}, function (res) {
            try {
                assert.strictEqual(res.statusCode, 400, res.statusCode + ': ' + res.body);
                var parsed = JSON.parse(res.body);
                assert.ok(parsed);
                assert.strictEqual(parsed.errors.length, 1);
                var error = parsed.errors[0];
                // carto-0.9.3 used to say "Failed to parse expression",
                // carto-0.9.5 says "not a valid keyword"
                assert.ok(error.match(/^style0:.*(Failed|not a valid)/), error);
                // TODO: check which layer introduced the problem ?
                done();
            } catch (err) { done(err); }
        });
    });

    it("post'ing style with non existent column in filter returns 400 with error", function (done) {
        var layergroup = {
            version: '1.0.1',
            layers: [
                {
                    options: {
                        sql: 'select * from test_table limit 1',
                        cartocss: '#test_table::outline[address="one"], [address="two"] { marker-fill: red; }',
                        cartocss_version: '2.0.2',
                        interactivity: ['cartodb_id'],
                        geom_column: 'the_geom'
                    }
                },
                {
                    options: {
                        sql: 'select * from test_big_poly limit 1',
                        cartocss: '#test_big_poly { marker-fill:blue }',
                        cartocss_version: '2.0.2',
                        interactivity: ['cartodb_id'],
                        geom_column: 'the_geom'
                    }
                }
            ]
        };

        assert.response(server, {
            url: '/api/v1/map',
            method: 'POST',
            headers: {
                host: 'localhost',
                'Content-Type': 'application/json'
            },
            data: JSON.stringify(layergroup)
        }, {}, function (res) {
            assert.strictEqual(res.statusCode, 400, res.body);
            var parsed = JSON.parse(res.body);
            assert.strictEqual(parsed.errors.length, 1);
            var error = parsed.errors[0];
            assert.ok(error.match(/column "address" does not exist/m), error);
            done();
        });
    });

    // See https://github.com/Vizzuality/Windshaft/issues/31
    it('bogus sql raises 400 status code', function (done) {
        var bogusSqlMapConfig = testClient.singleLayerMapConfig('BOGUS FROM test_table');
        testClient.createLayergroup(bogusSqlMapConfig, { statusCode: 400 }, function (err, res) {
            assert.ifError(err);
            assert.ok(/syntax error/.test(res.body), 'Unexpected error: ' + res.body);
            done();
        });
    });

    it('bogus sql raises 200 status code for jsonp', function (done) {
        var bogusSqlMapConfig = testClient.singleLayerMapConfig('bogus');
        var options = {
            method: 'GET',
            callbackName: 'test',
            headers: {
                'Content-Type': 'text/javascript; charset=utf-8'
            }
        };
        testClient.createLayergroup(bogusSqlMapConfig, options, function (err, res) {
            assert.ifError(err);
            assert.ok(
                /^\/\*\*\/ typeof test === 'function' && test\(/.test(res.body),
                'Body start expected callback name: ' + res.body
            );
            assert.ok(/syntax error/.test(res.body), 'Unexpected error: ' + res.body);
            done();
        });
    });

    it('query not selecting the_geom raises 200 status code for jsonp instead of 404', function (done) {
        var noGeomMapConfig = testClient.singleLayerMapConfig('select null::geometry the_geom_wadus');
        var options = {
            method: 'GET',
            callbackName: 'test',
            headers: {
                'Content-Type': 'text/javascript; charset=utf-8'
            }
        };
        testClient.createLayergroup(noGeomMapConfig, options, function (err, res) {
            assert.ifError(err);
            assert.ok(
                /^\/\*\*\/ typeof test === 'function' && test\(/.test(res.body),
                'Body start expected callback name: ' + res.body
            );
            assert.ok(/column.*does not exist/.test(res.body), 'Unexpected error: ' + res.body);
            done();
        });
    });

    it('query with no geometry field returns 400 status', function (done) {
        var noGeometrySqlMapConfig = testClient.singleLayerMapConfig('SELECT 1');
        testClient.createLayergroup(noGeometrySqlMapConfig, { statusCode: 400 }, function (err, res) {
            assert.ifError(err);
            assert.ok(/column.*does not exist/.test(res.body), 'Unexpected error: ' + res.body);
            done();
        });
    });

    it('bogus style should raise 400 status', function (done) {
        var bogusStyleMapConfig = testClient.defaultTableMapConfig('test_table', '#test_table{xxxxx;}');
        testClient.createLayergroup(bogusStyleMapConfig, { method: 'GET', statusCode: 400 }, done);
    });

    var defaultErrorExpectedResponse = {
        status: 400,
        headers: {
            'Content-Type': 'application/json; charset=utf-8'
        }
    };

    it('should raise 400 error for out of bounds layer index', function (done) {
        var mapConfig = testClient.singleLayerMapConfig('select * from test_table', null, null, 'name');

        testClient.getGrid(mapConfig, 1, 13, 4011, 3088, defaultErrorExpectedResponse, function (err, res) {
            assert.ifError(err);
            assert.deepStrictEqual(JSON.parse(res.body).errors, ["Layer '1' not found in layergroup"]);
            done();
        });
    });

    /// /////////////////////////////////////////////////////////////////
    //
    // OPTIONS LAYERGROUP
    //
    /// /////////////////////////////////////////////////////////////////

    it('nonexistent layergroup token error', function (done) {
        step(
            function doGetTile (err) {
                assert.ifError(err);
                var next = this;
                assert.response(server, {
                    url: '/api/v1/map/deadbeef/0/0/0/0.grid.json',
                    method: 'GET',
                    encoding: 'binary',
                    headers: {
                        host: 'localhost'
                    }
                }, {}, function (res, err) { next(err, res); });
            },
            function checkResponse (err, res) {
                assert.ifError(err);
                // FIXME: should be 404
                assert.strictEqual(res.statusCode, 400, res.statusCode + ':' + res.body);
                var parsed = JSON.parse(res.body);
                assert.deepStrictEqual(parsed.errors, ["Invalid or nonexistent map configuration token 'deadbeef'"]);
                return null;
            },
            function finish (err) {
                done(err);
            }
        );
    });

    it('error 400 on json syntax error', function (done) {
        var layergroup = {
            version: '1.0.1',
            layers: [
                {
                    options: {
                        sql: 'select the_geom from test_table limit 1',
                        cartocss: '#layer { marker-fill:red }'
                    }
                }
            ]
        };
        assert.response(server,
            {
                url: '/api/v1/map',
                method: 'POST',
                headers: { 'Content-Type': 'application/json; charset=utf-8' },
                data: '{' + JSON.stringify(layergroup)
            },
            {
                status: 400
            },
            function (res) {
                var parsedBody = JSON.parse(res.body);
                assert.ok(parsedBody.errors);
                assert.strictEqual(parsedBody.errors.length, 1);
                assert.ok(parsedBody.errors[0].match(/^SyntaxError: Unexpected token {/));
                done();
            }
        );
    });
});


text:
package com.opengamma.strata.product.deposit;

import static com.opengamma.strata.basics.currency.Currency.GBP;
import static com.opengamma.strata.basics.date.DayCounts.ACT_365F;
import static com.opengamma.strata.basics.index.IborIndices.GBP_LIBOR_6M;
import static com.opengamma.strata.collect.TestHelper.assertSerialization;
import static com.opengamma.strata.collect.TestHelper.coverBeanEquals;
import static com.opengamma.strata.collect.TestHelper.coverImmutableBean;
import static com.opengamma.strata.collect.TestHelper.date;
import static org.testng.Assert.assertEquals;

import java.time.LocalDate;

import org.testng.annotations.Test;

import com.opengamma.strata.basics.ReferenceData;
import com.opengamma.strata.product.TradeInfo;
import com.opengamma.strata.product.rate.IborRateComputation;

/**
 * Test {@link ResolvedIborFixingDepositTrade}.
 */
@Test
public class ResolvedIborFixingDepositTradeTest {

  private static final ReferenceData REF_DATA = ReferenceData.standard();
  private static final LocalDate FIXING_DATE = LocalDate.of(2015, 1, 19);
  private static final LocalDate START_DATE = LocalDate.of(2015, 1, 19);
  private static final LocalDate END_DATE = LocalDate.of(2015, 7, 20);
  private static final double YEAR_FRACTION = ACT_365F.yearFraction(START_DATE, END_DATE);
  private static final IborRateComputation RATE_COMP = IborRateComputation.of(GBP_LIBOR_6M, FIXING_DATE, REF_DATA);
  private static final double NOTIONAL = 100000000d;
  private static final double RATE = 0.0250;

  private static final ResolvedIborFixingDeposit DEPOSIT = ResolvedIborFixingDeposit.builder()
      .currency(GBP)
      .notional(NOTIONAL)
      .startDate(START_DATE)
      .endDate(END_DATE)
      .yearFraction(YEAR_FRACTION)
      .floatingRate(RATE_COMP)
      .fixedRate(RATE)
      .build();
  private static final TradeInfo TRADE_INFO = TradeInfo.of(date(2014, 6, 30));

  //-------------------------------------------------------------------------
  public void test_of() {
    ResolvedIborFixingDepositTrade test = ResolvedIborFixingDepositTrade.of(TRADE_INFO, DEPOSIT);
    assertEquals(test.getProduct(), DEPOSIT);
    assertEquals(test.getInfo(), TRADE_INFO);
  }

  public void test_builder() {
    ResolvedIborFixingDepositTrade test = ResolvedIborFixingDepositTrade.builder()
        .product(DEPOSIT)
        .info(TRADE_INFO)
        .build();
    assertEquals(test.getProduct(), DEPOSIT);
    assertEquals(test.getInfo(), TRADE_INFO);
  }

  //-------------------------------------------------------------------------
  public void coverage() {
    ResolvedIborFixingDepositTrade test1 = ResolvedIborFixingDepositTrade.builder()
        .product(DEPOSIT)
        .info(TRADE_INFO)
        .build();
    coverImmutableBean(test1);
    ResolvedIborFixingDepositTrade test2 = ResolvedIborFixingDepositTrade.builder()
        .product(DEPOSIT)
        .build();
    coverBeanEquals(test1, test2);
  }

  public void test_serialization() {
    ResolvedIborFixingDepositTrade test = ResolvedIborFixingDepositTrade.builder()
        .product(DEPOSIT)
        .info(TRADE_INFO)
        .build();
    assertSerialization(test);
  }

}


text:
import jasmine_tss = require('../../jasmine_tss'); var setSpy = jasmine_tss.setSpy, spyOf = jasmine_tss.spyOf;

import WindowProxy = require('../../../src/browser/Record/WindowProxy');

import IAction = require('../../../src/common/Test/IAction');
import IDarwinWindow = require('../../../src/common/IDarwinWindow');

describe('WindowProxy', () => {

  var window: IDarwinWindow;

  var windowProxy: WindowProxy;

  beforeEach(() => {
    window = <IDarwinWindow>{};

    windowProxy = new WindowProxy(window);
  });

  it('initialises the window Darwin object', () => {
    expect(window.__darwin).not.toBeUndefined();
    expect(window.__darwin.actions).toEqual([]);
    expect(window.__darwin.pendingScreenshot).toEqual(false);
  });

  it('adds actions to the actions array', () => {
    var action1 = <IAction>{ type: 1 };
    var action2 = <IAction>{ type: 2 };
    var action3 = <IAction>{ type: 3 };

    windowProxy.addAction(action1);
    windowProxy.addAction(action2);
    windowProxy.addAction(action3);

    expect(window.__darwin.actions[0]).toBe(action1);
    expect(window.__darwin.actions[1]).toBe(action2);
    expect(window.__darwin.actions[2]).toBe(action3);
  });

  it('sets the pendingScreenshot status', () => {
    windowProxy.setPendingScreenshot();

    expect(window.__darwin.pendingScreenshot).toEqual(true);
  });

});


text:
package com.facebook.buck.rules.visibility.parser;

import static com.facebook.buck.core.cell.TestCellBuilder.createCellRoots;

import com.facebook.buck.core.exceptions.HumanReadableException;
import com.facebook.buck.core.model.UnconfiguredBuildTargetFactoryForTests;
import com.facebook.buck.io.filesystem.impl.FakeProjectFilesystem;
import com.google.common.collect.ImmutableList;
import java.nio.file.Paths;
import org.junit.Test;

public class VisibilityPatternsTest {
  @Test(expected = HumanReadableException.class)
  public void bogusVisibilityGivesFriendlyError() {
    VisibilityPatterns.createFromStringList(
        createCellRoots(new FakeProjectFilesystem()),
        "visibility",
        ImmutableList.of(":marmosets"),
        Paths.get("BUCK"),
        () ->
            UnconfiguredBuildTargetFactoryForTests.newInstance("//example/path:three")
                .getData()
                .getFullyQualifiedName());
  }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycologia 85(3): 505 (1993)

#### Original name
Polytolypa hystricis J.A. Scott & Malloch, 1993

### Remarks
null