text:
"""Tests for templates module."""

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

import re
import gast

from tensorflow.python.autograph.pyct import anno
from tensorflow.python.autograph.pyct import origin_info
from tensorflow.python.autograph.pyct import parser
from tensorflow.python.autograph.pyct import transformer
from tensorflow.python.platform import test

class TransformerTest(test.TestCase):

  def _simple_context(self):
    entity_info = transformer.EntityInfo(
        name='Test_fn',
        source_code=None,
        source_file=None,
        future_features=(),
        namespace=None)
    return transformer.Context(entity_info, None, None)

  def assertSameAnno(self, first, second, key):
    self.assertIs(anno.getanno(first, key), anno.getanno(second, key))

  def assertDifferentAnno(self, first, second, key):
    self.assertIsNot(anno.getanno(first, key), anno.getanno(second, key))

  def test_state_tracking(self):

    class LoopState(object):
      pass

    class CondState(object):
      pass

    class TestTransformer(transformer.Base):

      def visit(self, node):
        anno.setanno(node, 'loop_state', self.state[LoopState].value)
        anno.setanno(node, 'cond_state', self.state[CondState].value)
        return super(TestTransformer, self).visit(node)

      def visit_While(self, node):
        self.state[LoopState].enter()
        node = self.generic_visit(node)
        self.state[LoopState].exit()
        return node

      def visit_If(self, node):
        self.state[CondState].enter()
        node = self.generic_visit(node)
        self.state[CondState].exit()
        return node

    tr = TestTransformer(self._simple_context())

    def test_function(a):
      a = 1
      while a:
        _ = 'a'
        if a > 2:
          _ = 'b'
          while True:
            raise '1'
        if a > 3:
          _ = 'c'
          while True:
            raise '1'

    node, _ = parser.parse_entity(test_function, future_features=())
    node = tr.visit(node)

    fn_body = node.body
    outer_while_body = fn_body[1].body
    self.assertSameAnno(fn_body[0], outer_while_body[0], 'cond_state')
    self.assertDifferentAnno(fn_body[0], outer_while_body[0], 'loop_state')

    first_if_body = outer_while_body[1].body
    self.assertDifferentAnno(outer_while_body[0], first_if_body[0],
                             'cond_state')
    self.assertSameAnno(outer_while_body[0], first_if_body[0], 'loop_state')

    first_inner_while_body = first_if_body[1].body
    self.assertSameAnno(first_if_body[0], first_inner_while_body[0],
                        'cond_state')
    self.assertDifferentAnno(first_if_body[0], first_inner_while_body[0],
                             'loop_state')

    second_if_body = outer_while_body[2].body
    self.assertDifferentAnno(first_if_body[0], second_if_body[0], 'cond_state')
    self.assertSameAnno(first_if_body[0], second_if_body[0], 'loop_state')

    second_inner_while_body = second_if_body[1].body
    self.assertDifferentAnno(first_inner_while_body[0],
                             second_inner_while_body[0], 'cond_state')
    self.assertDifferentAnno(first_inner_while_body[0],
                             second_inner_while_body[0], 'loop_state')

  def test_state_tracking_context_manager(self):

    class CondState(object):
      pass

    class TestTransformer(transformer.Base):

      def visit(self, node):
        anno.setanno(node, 'cond_state', self.state[CondState].value)
        return super(TestTransformer, self).visit(node)

      def visit_If(self, node):
        with self.state[CondState]:
          return self.generic_visit(node)

    tr = TestTransformer(self._simple_context())

    def test_function(a):
      a = 1
      if a > 2:
        _ = 'b'
        if a < 5:
          _ = 'c'
        _ = 'd'

    node, _ = parser.parse_entity(test_function, future_features=())
    node = tr.visit(node)

    fn_body = node.body
    outer_if_body = fn_body[1].body
    self.assertDifferentAnno(fn_body[0], outer_if_body[0], 'cond_state')
    self.assertSameAnno(outer_if_body[0], outer_if_body[2], 'cond_state')

    inner_if_body = outer_if_body[1].body
    self.assertDifferentAnno(inner_if_body[0], outer_if_body[0], 'cond_state')

  def test_visit_block_postprocessing(self):

    class TestTransformer(transformer.Base):

      def _process_body_item(self, node):
        if isinstance(node, gast.Assign) and (node.value.id == 'y'):
          if_node = gast.If(
              gast.Name(
                  'x', ctx=gast.Load(), annotation=None, type_comment=None),
              [node], [])
          return if_node, if_node.body
        return node, None

      def visit_FunctionDef(self, node):
        node.body = self.visit_block(
            node.body, after_visit=self._process_body_item)
        return node

    def test_function(x, y):
      z = x
      z = y
      return z

    tr = TestTransformer(self._simple_context())

    node, _ = parser.parse_entity(test_function, future_features=())
    node = tr.visit(node)

    self.assertEqual(len(node.body), 2)
    self.assertIsInstance(node.body[0], gast.Assign)
    self.assertIsInstance(node.body[1], gast.If)
    self.assertIsInstance(node.body[1].body[0], gast.Assign)
    self.assertIsInstance(node.body[1].body[1], gast.Return)

  def test_robust_error_on_list_visit(self):

    class BrokenTransformer(transformer.Base):

      def visit_If(self, node):
        # This is broken because visit expects a single node, not a list, and
        # the body of an if is a list.
        # Importantly, the default error handling in visit also expects a single
        # node.  Therefore, mistakes like this need to trigger a type error
        # before the visit called here installs its error handler.
        # That type error can then be caught by the enclosing call to visit,
        # and correctly blame the If node.
        self.visit(node.body)
        return node

    def test_function(x):
      if x > 0:
        return x

    tr = BrokenTransformer(self._simple_context())

    node, _ = parser.parse_entity(test_function, future_features=())
    with self.assertRaises(ValueError) as cm:
      node = tr.visit(node)
    obtained_message = str(cm.exception)
    expected_message = r'expected "ast.AST", got "\<(type|class) \'list\'\>"'
    self.assertRegex(obtained_message, expected_message)

  def test_robust_error_on_ast_corruption(self):
    # A child class should not be able to be so broken that it causes the error
    # handling in `transformer.Base` to raise an exception.  Why not?  Because
    # then the original error location is dropped, and an error handler higher
    # up in the call stack gives misleading information.

    # Here we test that the error handling in `visit` completes, and blames the
    # correct original exception, even if the AST gets corrupted.

    class NotANode(object):
      pass

    class BrokenTransformer(transformer.Base):

      def visit_If(self, node):
        node.body = NotANode()
        raise ValueError('I blew up')

    def test_function(x):
      if x > 0:
        return x

    tr = BrokenTransformer(self._simple_context())

    node, _ = parser.parse_entity(test_function, future_features=())
    with self.assertRaises(ValueError) as cm:
      node = tr.visit(node)
    obtained_message = str(cm.exception)
    # The message should reference the exception actually raised, not anything
    # from the exception handler.
    expected_substring = 'I blew up'
    self.assertIn(expected_substring, obtained_message)

  def test_origin_info_propagated_to_new_nodes(self):

    class TestTransformer(transformer.Base):

      def visit_If(self, node):
        return gast.Pass()

    tr = TestTransformer(self._simple_context())

    def test_fn():
      x = 1
      if x > 0:
        x = 1
      return x

    node, source = parser.parse_entity(test_fn, future_features=())
    origin_info.resolve(node, source, 'test_file', 100, 0)
    node = tr.visit(node)

    created_pass_node = node.body[1]
    # Takes the line number of the if statement.
    self.assertEqual(
        anno.getanno(created_pass_node, anno.Basic.ORIGIN).loc.lineno, 102)

  def test_origin_info_preserved_in_moved_nodes(self):

    class TestTransformer(transformer.Base):

      def visit_If(self, node):
        return node.body

    tr = TestTransformer(self._simple_context())

    def test_fn():
      x = 1
      if x > 0:
        x = 1
        x += 3
      return x

    node, source = parser.parse_entity(test_fn, future_features=())
    origin_info.resolve(node, source, 'test_file', 100, 0)
    node = tr.visit(node)

    assign_node = node.body[1]
    aug_assign_node = node.body[2]
    # Keep their original line numbers.
    self.assertEqual(
        anno.getanno(assign_node, anno.Basic.ORIGIN).loc.lineno, 103)
    self.assertEqual(
        anno.getanno(aug_assign_node, anno.Basic.ORIGIN).loc.lineno, 104)

class CodeGeneratorTest(test.TestCase):

  def _simple_context(self):
    entity_info = transformer.EntityInfo(
        name='test_fn',
        source_code=None,
        source_file=None,
        future_features=(),
        namespace=None)
    return transformer.Context(entity_info, None, None)

  def test_basic_codegen(self):

    class TestCodegen(transformer.CodeGenerator):

      def visit_Assign(self, node):
        self.emit(parser.unparse(node, include_encoding_marker=False))
        self.emit('\n')

      def visit_Return(self, node):
        self.emit(parser.unparse(node, include_encoding_marker=False))
        self.emit('\n')

      def visit_If(self, node):
        self.emit('if ')
        # This is just for simplifity. A real generator will walk the tree and
        # emit proper code.
        self.emit(parser.unparse(node.test, include_encoding_marker=False))
        self.emit(' {\n')
        self.visit_block(node.body)
        self.emit('} else {\n')
        self.visit_block(node.orelse)
        self.emit('}\n')

    tg = TestCodegen(self._simple_context())

    def test_fn():
      x = 1
      if x > 0:
        x = 2
        if x > 1:
          x = 3
      return x

    node, source = parser.parse_entity(test_fn, future_features=())
    origin_info.resolve(node, source, 'test_file', 100, 0)
    tg.visit(node)

    r = re.compile('.*'.join([
        r'x = 1',
        r'if \(?x > 0\)? {',
        r'x = 2',
        r'if \(?x > 1\)? {',
        r'x = 3',
        r'} else {',
        r'}',
        r'} else {',
        r'}',
        r'return x']), re.DOTALL)

    self.assertRegex(tg.code_buffer, r)
    # TODO(mdan): Test the source map.

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


text:
/**
 * Autogenerated by Thrift Compiler (0.9.2)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
package backtype.storm.generated;

import org.apache.thrift.scheme.IScheme;
import org.apache.thrift.scheme.SchemeFactory;
import org.apache.thrift.scheme.StandardScheme;

import org.apache.thrift.scheme.TupleScheme;
import org.apache.thrift.protocol.TTupleProtocol;
import org.apache.thrift.protocol.TProtocolException;
import org.apache.thrift.EncodingUtils;
import org.apache.thrift.TException;
import org.apache.thrift.async.AsyncMethodCallback;
import org.apache.thrift.server.AbstractNonblockingServer.*;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Set;
import java.util.HashSet;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import java.nio.ByteBuffer;
import java.util.Arrays;
import javax.annotation.Generated;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2017-2-22")
public class SettableBlobMeta implements org.apache.thrift.TBase<SettableBlobMeta, SettableBlobMeta._Fields>, java.io.Serializable, Cloneable, Comparable<SettableBlobMeta> {
  private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("SettableBlobMeta");

  private static final org.apache.thrift.protocol.TField REPLICATION_FACTOR_FIELD_DESC = new org.apache.thrift.protocol.TField("replication_factor", org.apache.thrift.protocol.TType.I32, (short)1);

  private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
  static {
    schemes.put(StandardScheme.class, new SettableBlobMetaStandardSchemeFactory());
    schemes.put(TupleScheme.class, new SettableBlobMetaTupleSchemeFactory());
  }

  private int replication_factor; // optional

  /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
  public enum _Fields implements org.apache.thrift.TFieldIdEnum {
    REPLICATION_FACTOR((short)1, "replication_factor");

    private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();

    static {
      for (_Fields field : EnumSet.allOf(_Fields.class)) {
        byName.put(field.getFieldName(), field);
      }
    }

    /**
     * Find the _Fields constant that matches fieldId, or null if its not found.
     */
    public static _Fields findByThriftId(int fieldId) {
      switch(fieldId) {
        case 1: // REPLICATION_FACTOR
          return REPLICATION_FACTOR;
        default:
          return null;
      }
    }

    /**
     * Find the _Fields constant that matches fieldId, throwing an exception
     * if it is not found.
     */
    public static _Fields findByThriftIdOrThrow(int fieldId) {
      _Fields fields = findByThriftId(fieldId);
      if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
      return fields;
    }

    /**
     * Find the _Fields constant that matches name, or null if its not found.
     */
    public static _Fields findByName(String name) {
      return byName.get(name);
    }

    private final short _thriftId;
    private final String _fieldName;

    _Fields(short thriftId, String fieldName) {
      _thriftId = thriftId;
      _fieldName = fieldName;
    }

    public short getThriftFieldId() {
      return _thriftId;
    }

    public String getFieldName() {
      return _fieldName;
    }
  }

  // isset id assignments
  private static final int __REPLICATION_FACTOR_ISSET_ID = 0;
  private byte __isset_bitfield = 0;
  private static final _Fields optionals[] = {_Fields.REPLICATION_FACTOR};
  public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
  static {
    Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
    tmpMap.put(_Fields.REPLICATION_FACTOR, new org.apache.thrift.meta_data.FieldMetaData("replication_factor", org.apache.thrift.TFieldRequirementType.OPTIONAL,
        new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32)));
    metaDataMap = Collections.unmodifiableMap(tmpMap);
    org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(SettableBlobMeta.class, metaDataMap);
  }

  public SettableBlobMeta() {
  }

  /**
   * Performs a deep copy on <i>other</i>.
   */
  public SettableBlobMeta(SettableBlobMeta other) {
    __isset_bitfield = other.__isset_bitfield;
    this.replication_factor = other.replication_factor;
  }

  public SettableBlobMeta deepCopy() {
    return new SettableBlobMeta(this);
  }

  @Override
  public void clear() {
    set_replication_factor_isSet(false);
    this.replication_factor = 0;
  }

  public int get_replication_factor() {
    return this.replication_factor;
  }

  public void set_replication_factor(int replication_factor) {
    this.replication_factor = replication_factor;
    set_replication_factor_isSet(true);
  }

  public void unset_replication_factor() {
    __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __REPLICATION_FACTOR_ISSET_ID);
  }

  /** Returns true if field replication_factor is set (has been assigned a value) and false otherwise */
  public boolean is_set_replication_factor() {
    return EncodingUtils.testBit(__isset_bitfield, __REPLICATION_FACTOR_ISSET_ID);
  }

  public void set_replication_factor_isSet(boolean value) {
    __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __REPLICATION_FACTOR_ISSET_ID, value);
  }

  public void setFieldValue(_Fields field, Object value) {
    switch (field) {
    case REPLICATION_FACTOR:
      if (value == null) {
        unset_replication_factor();
      } else {
        set_replication_factor((Integer)value);
      }
      break;

    }
  }

  public Object getFieldValue(_Fields field) {
    switch (field) {
    case REPLICATION_FACTOR:
      return Integer.valueOf(get_replication_factor());

    }
    throw new IllegalStateException();
  }

  /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
  public boolean isSet(_Fields field) {
    if (field == null) {
      throw new IllegalArgumentException();
    }

    switch (field) {
    case REPLICATION_FACTOR:
      return is_set_replication_factor();
    }
    throw new IllegalStateException();
  }

  @Override
  public boolean equals(Object that) {
    if (that == null)
      return false;
    if (that instanceof SettableBlobMeta)
      return this.equals((SettableBlobMeta)that);
    return false;
  }

  public boolean equals(SettableBlobMeta that) {
    if (that == null)
      return false;

    boolean this_present_replication_factor = true && this.is_set_replication_factor();
    boolean that_present_replication_factor = true && that.is_set_replication_factor();
    if (this_present_replication_factor || that_present_replication_factor) {
      if (!(this_present_replication_factor && that_present_replication_factor))
        return false;
      if (this.replication_factor != that.replication_factor)
        return false;
    }

    return true;
  }

  @Override
  public int hashCode() {
    List<Object> list = new ArrayList<Object>();

    boolean present_replication_factor = true && (is_set_replication_factor());
    list.add(present_replication_factor);
    if (present_replication_factor)
      list.add(replication_factor);

    return list.hashCode();
  }

  @Override
  public int compareTo(SettableBlobMeta other) {
    if (!getClass().equals(other.getClass())) {
      return getClass().getName().compareTo(other.getClass().getName());
    }

    int lastComparison = 0;

    lastComparison = Boolean.valueOf(is_set_replication_factor()).compareTo(other.is_set_replication_factor());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (is_set_replication_factor()) {
      lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.replication_factor, other.replication_factor);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    return 0;
  }

  public _Fields fieldForId(int fieldId) {
    return _Fields.findByThriftId(fieldId);
  }

  public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
    schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
  }

  public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
    schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder("SettableBlobMeta(");
    boolean first = true;

    if (is_set_replication_factor()) {
      sb.append("replication_factor:");
      sb.append(this.replication_factor);
      first = false;
    }
    sb.append(")");
    return sb.toString();
  }

  public void validate() throws org.apache.thrift.TException {
    // check for required fields
    // check for sub-struct validity
  }

  private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
    try {
      write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
    } catch (org.apache.thrift.TException te) {
      throw new java.io.IOException(te);
    }
  }

  private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
    try {
      // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
      __isset_bitfield = 0;
      read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
    } catch (org.apache.thrift.TException te) {
      throw new java.io.IOException(te);
    }
  }

  private static class SettableBlobMetaStandardSchemeFactory implements SchemeFactory {
    public SettableBlobMetaStandardScheme getScheme() {
      return new SettableBlobMetaStandardScheme();
    }
  }

  private static class SettableBlobMetaStandardScheme extends StandardScheme<SettableBlobMeta> {

    public void read(org.apache.thrift.protocol.TProtocol iprot, SettableBlobMeta struct) throws org.apache.thrift.TException {
      org.apache.thrift.protocol.TField schemeField;
      iprot.readStructBegin();
      while (true)
      {
        schemeField = iprot.readFieldBegin();
        if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
          break;
        }
        switch (schemeField.id) {
          case 1: // REPLICATION_FACTOR
            if (schemeField.type == org.apache.thrift.protocol.TType.I32) {
              struct.replication_factor = iprot.readI32();
              struct.set_replication_factor_isSet(true);
            } else {
              org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
            }
            break;
          default:
            org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
        }
        iprot.readFieldEnd();
      }
      iprot.readStructEnd();
      struct.validate();
    }

    public void write(org.apache.thrift.protocol.TProtocol oprot, SettableBlobMeta struct) throws org.apache.thrift.TException {
      struct.validate();

      oprot.writeStructBegin(STRUCT_DESC);
      if (struct.is_set_replication_factor()) {
        oprot.writeFieldBegin(REPLICATION_FACTOR_FIELD_DESC);
        oprot.writeI32(struct.replication_factor);
        oprot.writeFieldEnd();
      }
      oprot.writeFieldStop();
      oprot.writeStructEnd();
    }

  }

  private static class SettableBlobMetaTupleSchemeFactory implements SchemeFactory {
    public SettableBlobMetaTupleScheme getScheme() {
      return new SettableBlobMetaTupleScheme();
    }
  }

  private static class SettableBlobMetaTupleScheme extends TupleScheme<SettableBlobMeta> {

    @Override
    public void write(org.apache.thrift.protocol.TProtocol prot, SettableBlobMeta struct) throws org.apache.thrift.TException {
      TTupleProtocol oprot = (TTupleProtocol) prot;
      BitSet optionals = new BitSet();
      if (struct.is_set_replication_factor()) {
        optionals.set(0);
      }
      oprot.writeBitSet(optionals, 1);
      if (struct.is_set_replication_factor()) {
        oprot.writeI32(struct.replication_factor);
      }
    }

    @Override
    public void read(org.apache.thrift.protocol.TProtocol prot, SettableBlobMeta struct) throws org.apache.thrift.TException {
      TTupleProtocol iprot = (TTupleProtocol) prot;
      BitSet incoming = iprot.readBitSet(1);
      if (incoming.get(0)) {
        struct.replication_factor = iprot.readI32();
        struct.set_replication_factor_isSet(true);
      }
    }
  }

}

redpajama_set_name: RedPajamaGithub


text:
package com.github.mthizo247.cloud.netflix.zuul.web.socket;

import com.github.mthizo247.cloud.netflix.zuul.web.proxytarget.ProxyTargetResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.util.Assert;
import org.springframework.util.ErrorHandler;
import org.springframework.util.PatternMatchUtils;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.WebSocketHandlerDecorator;
import org.springframework.web.socket.messaging.WebSocketStompClient;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * A {@link WebSocketHandlerDecorator} that adds web socket support to zuul reverse proxy.
 *
 * @author Ronald Mthombeni
 * @author Salman Noor
 */
public class ProxyWebSocketHandler extends WebSocketHandlerDecorator {
    private final Logger logger = LoggerFactory.getLogger(ProxyWebSocketHandler.class);
    private final WebSocketHttpHeadersCallback headersCallback;
    private final SimpMessagingTemplate messagingTemplate;
    private final ProxyTargetResolver proxyTargetResolver;
    private final ZuulWebSocketProperties zuulWebSocketProperties;
    private final WebSocketStompClient stompClient;
    private final Map<WebSocketSession, ProxyWebSocketConnectionManager> managers = new ConcurrentHashMap<>();
    private ErrorHandler errorHandler;

    public ProxyWebSocketHandler(WebSocketHandler delegate,
                                 WebSocketStompClient stompClient,
                                 WebSocketHttpHeadersCallback headersCallback,
                                 SimpMessagingTemplate messagingTemplate,
                                 ProxyTargetResolver proxyTargetResolver,
                                 ZuulWebSocketProperties zuulWebSocketProperties) {
        super(delegate);
        this.stompClient = stompClient;
        this.headersCallback = headersCallback;
        this.messagingTemplate = messagingTemplate;
        this.proxyTargetResolver = proxyTargetResolver;
        this.zuulWebSocketProperties = zuulWebSocketProperties;
    }

    public void errorHandler(ErrorHandler errorHandler) {
        this.errorHandler = errorHandler;
    }

    private String getWebSocketServerPath(ZuulWebSocketProperties.WsBrokerage wsBrokerage,
                                          URI uri) {
        String path = uri.toString();
        if (path.contains(":")) {
            path = UriComponentsBuilder.fromUriString(path).build().getPath();
        }

        for (String endPoint : wsBrokerage.getEndPoints()) {
            if (PatternMatchUtils.simpleMatch(toPattern(endPoint), path + "/")) {
                return endPoint;
            }
        }

        return null;
    }

    private ZuulWebSocketProperties.WsBrokerage getWebSocketBrokarage(URI uri) {
        String path = uri.toString();
        if (path.contains(":")) {
            path = UriComponentsBuilder.fromUriString(path).build().getPath();
        }

        for (Map.Entry<String, ZuulWebSocketProperties.WsBrokerage> entry : zuulWebSocketProperties
                .getBrokerages().entrySet()) {
            ZuulWebSocketProperties.WsBrokerage wsBrokerage = entry.getValue();
            if (wsBrokerage.isEnabled()) {
                for (String endPoint : wsBrokerage.getEndPoints()) {
                    if (PatternMatchUtils.simpleMatch(toPattern(endPoint), path + "/")) {
                        return wsBrokerage;
                    }
                }
            }
        }

        return null;
    }

    private String toPattern(String path) {
        path = path.startsWith("/") ? "**" + path : "**/" + path;
        return path.endsWith("/") ? path + "**" : path + "/**";
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus)
            throws Exception {
        disconnectFromProxiedTarget(session);
        super.afterConnectionClosed(session, closeStatus);
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message)
            throws Exception {
        super.handleMessage(session, message);
        handleMessageFromClient(session, message);
    }

    private void handleMessageFromClient(WebSocketSession session,
                                         WebSocketMessage<?> message) throws Exception {
        boolean handled = false;
        WebSocketMessageAccessor accessor = WebSocketMessageAccessor.create(message);
        if (StompCommand.SEND.toString().equalsIgnoreCase(accessor.getCommand())) {
            handled = true;
            sendMessageToProxiedTarget(session, accessor);
        }

        if (StompCommand.SUBSCRIBE.toString().equalsIgnoreCase(accessor.getCommand())) {
            handled = true;
            subscribeToProxiedTarget(session, accessor);
        }

        if (StompCommand.UNSUBSCRIBE.toString().equalsIgnoreCase(accessor.getCommand())) {
            handled = true;
            unsubscribeFromProxiedTarget(session, accessor);
        }

        if (StompCommand.CONNECT.toString().equalsIgnoreCase(accessor.getCommand())) {
            handled = true;
            connectToProxiedTarget(session);
        }

        if (!handled) {
            if (logger.isDebugEnabled()) {
                logger.debug("STOMP COMMAND " + accessor.getCommand()
                        + " was not explicitly handled");
            }
        }
    }

    private void connectToProxiedTarget(WebSocketSession session) {
        URI sessionUri = session.getUri();
        ZuulWebSocketProperties.WsBrokerage wsBrokerage = getWebSocketBrokarage(
                sessionUri);

        Assert.notNull(wsBrokerage, "wsBrokerage must not be null");

        String path = getWebSocketServerPath(wsBrokerage, sessionUri);
        Assert.notNull(path, "Web socket uri path must be null");

        URI routeTarget = proxyTargetResolver.resolveTarget(wsBrokerage);

        Assert.notNull(routeTarget, "routeTarget must not be null");

        String uri = ServletUriComponentsBuilder
                .fromUri(routeTarget)
                .path(path)
                .replaceQuery(sessionUri.getQuery())
                .toUriString();

        ProxyWebSocketConnectionManager connectionManager = new ProxyWebSocketConnectionManager(
                messagingTemplate, stompClient, session, headersCallback, uri);
        connectionManager.errorHandler(this.errorHandler);
        managers.put(session, connectionManager);
        connectionManager.start();
    }

    private void disconnectFromProxiedTarget(WebSocketSession session) {
        disconnectProxyManager(managers.remove(session));
    }

    private void disconnectProxyManager(ProxyWebSocketConnectionManager proxyManager) {
        if (proxyManager != null) {
            try {
                proxyManager.disconnect();
            } catch (Throwable ignored) {
                // nothing
            }
        }
    }

    private void unsubscribeFromProxiedTarget(WebSocketSession session,
                                              WebSocketMessageAccessor accessor) {
        ProxyWebSocketConnectionManager manager = managers.get(session);
        if (manager != null) {
            manager.unsubscribe(accessor.getDestination());
        }
    }

    private void sendMessageToProxiedTarget(WebSocketSession session,
                                            WebSocketMessageAccessor accessor) {
        ProxyWebSocketConnectionManager manager = managers.get(session);
        manager.sendMessage(accessor.getDestination(), accessor.getPayload());
    }

    private void subscribeToProxiedTarget(WebSocketSession session,
                                          WebSocketMessageAccessor accessor) throws Exception {
        ProxyWebSocketConnectionManager manager = managers.get(session);
        manager.subscribe(accessor.getDestination());
    }
}


text:
<FEED xmlns="" NAME="EventResults" DESCRIPTION="The event results of all events during the last 10 days displayed in the language '@LANGUAGE'. You can specify a list of sport kinds, a list of leagues, or both." LAST_REFRESH="2013-02-06T12:56:16" NEXT_REFRESH="2013-02-06T13:06:16" DOMAIN="www.interwetten.com" LANGUAGE="EN">
<KINDOFSPORT NAME="Football">
<LEAGUE NAME="African Cup of Nations (South Africa) (90´)">
<EVENT NAME="Burkina Faso - Togo" ID="9754897" RESULT="0:0" START_FROM="2013-02-03T19:30:00"/>
</EVENT>
</LEAGUE>
</KINDOFSPORT>
</FEED>


text:
void PerformanceTests(int loopCount);
void DecodePerformanceTests(int loopCount);

#endif


text:
import os
import json
import hashlib
import codecs
from shutil import copyfile
import sys

stage = "stage1"
if len(sys.argv) > 1:
    stage = sys.argv[1]

curr_path = os.path.dirname(os.path.realpath(__file__))
parent_path = os.path.realpath(os.path.join(curr_path, ".."))

to_remove = None

def md5sum(full_path):
    with open(full_path, 'rb') as rf:
        return hashlib.md5(rf.read()).hexdigest()

def work_paths_by_walk():
    index = 0
    for root,subdirs,files in os.walk(parent_path):
        index += 1
        for filepath in files:
            print os.path.join(root,filepath)
        for sub in subdirs:
            print os.path.join(root,sub)

def work_parent():
    ignore_paths = frozenset(["maintain_files", "softcenter", "appledns", "ngrok", "koolproxy", "koolss", "ssrserver"])
    for fname in os.listdir(parent_path):

        if fname[0] == "." or fname in ignore_paths:
            continue

        path = os.path.join(parent_path, fname)
        if os.path.isdir(path):
            #print fname
            #print path
            yield fname, path

def work_files(parent, ext):
    for fname in os.listdir(parent):
        path = os.path.join(parent, fname)
        if os.path.isfile(path):
            yield path

def check_subdir(module, path, name, ext, target_path):
    script_path = os.path.join(path, module, name)
    if os.path.isdir(script_path):
        for f in work_files(script_path, ext):
            target_file = os.path.join(target_path, os.path.basename(f))
            #print "copy", f, "-->", target_file
            copyfile(f, target_file)
            if not target_file.endswith(".png") and to_remove:
                to_remove.write(target_file+"\n")

def check_and_cp():
    for module, path in work_parent():
        #check_subdir(module, path, "scripts", ".sh", os.path.join(curr_path, "softcenter", "scripts"))
        #check_subdir(module, path, "webs", ".asp", os.path.join(curr_path, "softcenter", "webs"))
        #check_subdir(module, path, "scripts", ".sh", os.path.join(curr_path, "softcenter", "scripts"))
        check_subdir(module, path, "webs/res", "*", os.path.join(curr_path, "softcenter", "webs/res"))

def gen_modules(modules):
    for module, path in work_parent():
        conf = os.path.join(path, "config.json.js")

        m = None
        try:
            with codecs.open(conf, "r", "utf-8") as fc:
                m = json.loads(fc.read())
                if m:
                    m["name"] = module
                    if "tar_url" not in m:
                        m["tar_url"] = module + "/" + module + ".tar.gz"
                    if "home_url" not in m:
                        m["home_url"] = "Module_" + module + ".asp"
        except:
            pass

        if not m:
            m = {"name":module, "title":module, "tar_url": module + "/" + module + ".tar.gz"}
        modules.append(m)

if stage == "stage1":
    to_remove = open(os.path.join(curr_path, "to_remove.txt"), "w")
    check_and_cp()
    to_remove.close()
else:
    check_and_cp()
    gmodules = None
    with codecs.open(os.path.join(curr_path, "app.template.json.js"), "r", "utf-8") as fg:
        gmodules = json.loads(fg.read())
        gmodules["apps"] = []
    gen_modules(gmodules["apps"])

    with codecs.open(os.path.join(curr_path, "config.json.js"), "r", "utf-8") as fc:
        conf = json.loads(fc.read())
        gmodules["version"] = conf["version"]
        gmodules["md5"] = conf["md5"]

        with codecs.open(os.path.join(curr_path, "app.json.js"), "w", "utf-8") as fw:
            json.dump(gmodules, fw, sort_keys = True, indent = 4, ensure_ascii=False, encoding='utf8')


text:
package org.wayfair.wiff.queue;

import java.util.concurrent.LinkedBlockingQueue;

public class WiffLinkedBlockingQueue<T> implements WiffQueue<T> {

  private LinkedBlockingQueue<T> queue;

  public WiffLinkedBlockingQueue() {
    this.queue = new LinkedBlockingQueue<T>();
  }

  /*
   * (non-Javadoc)
   *
   * @see org.wayfair.wiff.queue.WiffQueue#add(java.lang.Object)
   */
  public boolean add(T element) throws WiffQueueAdditionException {
    boolean success = false;
    try {
      queue.put(element);
      success = true;
    } catch (InterruptedException e) {
      throw new WiffQueueAdditionException(e.getMessage(), e);
    }
    return success;
  }

  /*
   * (non-Javadoc)
   *
   * @see org.wayfair.wiff.queue.WiffQueue#remove()
   */
  public T remove() throws WiffQueueRemovalException {
    try {
      return queue.take();
    } catch (InterruptedException e) {
      throw new WiffQueueRemovalException(e.getMessage(), e);
    }
  }

  /*
   * (non-Javadoc)
   *
   * @see org.wayfair.wiff.queue.WiffQueue#size()
   */
  public int size() {
    return queue.size();
  }

  /*
   * (non-Javadoc)
   *
   * @see org.wayfair.wiff.queue.WiffQueue#teardown()
   */
  public void teardown() {
  }
}


text:
// is used only for debugging tests

module.exports = function (grunt) {

  grunt.initConfig({

    mochaTest: {
      test: {
        options: {
          reporter: 'spec'
        },
        src: ['test/**/*.js']
      }
    }

  });

  grunt.loadNpmTasks('grunt-mocha-test');

  grunt.registerTask('test', ['mochaTest']);

};


text:
from gigs.gig_registry.models import Gig
from haystack.indexes import RealTimeSearchIndex, \
    CharField, DateField, FloatField, MultiValueField, \
    EdgeNgramField
from haystack import site

class GigIndex(RealTimeSearchIndex):
    text = EdgeNgramField(document=True, use_template=True)
    tmp = CharField()
    start = DateField(model_attr='start', faceted=True)
    venue_name = CharField(model_attr='venue__name', faceted=True)
    bands = MultiValueField(faceted=True)
    cost = FloatField(model_attr='cost', default=0)
    name = CharField(model_attr='name', default=0, faceted=True)
    venue_location = CharField(faceted=True)
    location_lat = FloatField(model_attr='venue__location__lat', stored=True, null=True)
    location_lon = FloatField(model_attr='venue__location__lon', stored=True, null=True)

    def prepare_bands(self, obj):
        return [band.name for band in obj.bands.all()]

    def prepare_location(self, obj):
        return str(obj.venue.location)

    def prepare_tmp(self, obj):
        return 'tmp'

    def index_queryset(self):
        return Gig.objects.all()

site.register(Gig, GigIndex)


text:
;(function(global) {
  "use strict";

  var hasOwnProp = Object.hasOwnProperty;

  var Klass = function(instanceProps) {
    var addInstanceProps,
        F;

    addInstanceProps = function(object) {
      var prop;
      for (prop in instanceProps) {
        if (hasOwnProp.call(instanceProps, prop)) {
          object[prop] = instanceProps[prop];
        }
      }
    };

    F = function() {
      if (!(this instanceof F)) {
        throw 'Invalid call to class function, please use the `new Class` to instantiate an object';
      }
      addInstanceProps(this);
      return this;
    };
    F.extends = function(parentProps) {
      if (typeof parentProps !== 'object') {
        throw 'ArgumentTypeError in .extends: expected object, got ' + (typeof parentProps);
      }
      if (parentProps === null) {
        throw 'ArgumentTypeError in .extends: expected object, got null';
      }
      var Parent = function() {};
      Parent.prototype = parentProps;
      F.prototype = new Parent();
      F.prototype.constructor = F;

      return F;
    };
    F.implements = function(methodsArr) {
      if (methodsArr === null) {
        throw 'ArgumentTypeError in .implements: expected array, got null';
      }
      if (toString.call(methodsArr) !== '[object Array]') {
        throw 'ArgumentTypeError in .implements: expected array, got ' + (typeof methodsArr);
      }
      var i = 0,
          methodsLength = methodsArr.length,
          f = new F();
      for (; i < methodsLength; i++) {
        if (typeof methodsArr[i] !== 'string') {
          throw 'ArgumentTypeError in .implements: expected an array of strings';
        }
        if (typeof f[methodsArr[i]] !== 'function') {
          throw 'ImplementsError: Klass does not implement ' + methodsArr[i];
        }
      }
      return F;
    };

    // finally return F
    return F;
  };

  global.Klass = global.Klass || Klass;
}(window));


text:
In this directory you will find instructions and examples to start your first
Ada_Drivers_Library project.

The goals of the examples are:
 - Offer a simple way to start a project
 - Demonstrate the supported features of the boards
 - Demonstrate the supported drivers of a micro-controller family

The examples are sorted by boards but some of them are working on multiple
boards, in that case the code is stored in the [shared](shared/) directory.

# Getting started

## Download and install the tools

### Compiler and IDE

Most of the boards/micro-controller supported are based on the ARM Cortex-M
architecture. If you have a GNAT Pro subscription, you can download the
compiler (GNAT) and IDE (GNAT Programming Studio) from your account. Otherwise,
AdaCore provides a community version of GNAT that you can download
[here](http://adacore.com/download). We recomend to download the cross compiler
and also the native one because it contains the GNAT Programming Studio IDE.

Follow the instructions to install GNAT and GPS.

### stlink

For the STM32 board we recommend to use the open-source probe interface
[stlink](https://github.com/texane/stlink).

On Windows, stlink should be included with your cross-compiler installation.

On Linux, you have to download the source and compile the tool:

```Shell
$ git clone https://github.com/texane/stlink.git
$ cd stlink
$ make release
```

### Miscellaneous

Some boards require a specific tool or configuration, in that case you will
find the additional instructions in the example directory dedicated to this
board (for instance [Micro:bit](MicroBit/)).

## Clone the repository

If you are on Windows, we recommend to use the
[GitHub Desktop application](https://desktop.github.com/).

Otherwise, from the command line:
```shell
git clone --recursive https://github.com/AdaCore/Ada_Drivers_Library.git
```

## Build and install the run-times

Not all the GNAT run-times used in the Ada_Drivers_Library are packaged with
the compiler.

To build and install the missing run-times, use the `install_dependencies.py`
script:

```shell
python ./scripts/install_dependencies.py
```

## Open an example project

Start GNAT Programming Studio and open one of the project supported by the
board you have:

 - [HiFive1](HiFive1)
 - [MicroBit](MicroBit)
 - [OpenMV2 ](OpenMV2)
 - [STM32F429_Discovery](STM32F429_Discovery)
 - [STM32F469_Discovery](STM32F469_Discovery)
 - [STM32F4_DISCO](STM32F4_DISCO)
 - [STM32F746_Discovery](STM32F746_Discovery)
 - [STM32F769_Discovery](STM32F769_Discovery)

## Compile the project

Use the "Build all" button in GNAT Programming Studio tool bar.

##  Run the project

For the STM32 board, use the "Flash to board" button in the tool bar.

#
### We need your help

If you notice an error in these instructions, or if you want to improve them,
please go to [Ada_Drivers_Library GitHub
repository](https://github.com/AdaCore/Ada_Drivers_Library). Thank you in
advance.


text:
namespace lutop {

class Manager {
    public:
        Manager(unsigned int pool_size, unsigned int max_count);
        ~Manager() throw();

        void loadFiles(std::vector<std::string> const &files);
        void run();

    private:
        Context c_;
        ProcessPool pp_;
        std::vector<Module> modules_;
        std::multimap<std::string, std::string> dependencies_;

        // Boost::Asio staff
        boost::asio::io_service io_service_;
        boost::asio::deadline_timer scheduler_timer_;

    private:
        void runIter(const boost::system::error_code& error);
        void prepareModules();
        time_t startSomething();
        void startModule(const Module &m);
        void moduleCallback(const Module &m, std::shared_ptr<Response> r, const boost::system::error_code &err);
};

}


text:
FOUNDATION_EXPORT double Pods_EYSnapAlert_ExampleVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_EYSnapAlert_ExampleVersionString[];


text:
<?php

namespace jubianchi\PhpSwitch\PHP\Option;

use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputInterface;
use jubianchi\PhpSwitch\PHP\Version;
use jubianchi\PhpSwitch\Console\Command\Command;

interface OptionInterface
{
    public function preInstall(Version $version, InputInterface $input, OutputInterface $output);
    public function postInstall(Version $version, InputInterface $input, OutputInterface $output);
    public function setCommand(Command $command);
    public function __toString();
}


text:
import AssistDbEntry from 'ko/components/assist/assistDbEntry';
import AssistDbSource from 'ko/components/assist/assistDbSource';

// TODO: Get rid of
window.AssistDbEntry = AssistDbEntry;
window.AssistDbSource = AssistDbSource;


text:
package com.xlythe.textmanager.text.smil;

import org.w3c.dom.DOMException;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

import java.util.Vector;

public class NamedNodeMapImpl implements NamedNodeMap {

    private Vector<Node> mNodes = new Vector<>();

    public int getLength() {
        return mNodes.size();
    }

    public Node getNamedItem(String name) {
        Node node = null;
        for (int i = 0; i < mNodes.size(); i++) {
            if (name.equals(mNodes.elementAt(i).getNodeName())) {
                node = mNodes.elementAt(i);
                break;
            }
        }
        return node;
    }

    public Node getNamedItemNS(String namespaceURI, String localName) {
        // TODO Auto-generated method stub
        return null;
    }

    public Node item(int index) {
        if (index < mNodes.size()) {
            return mNodes.elementAt(index);
        }
        return null;
    }

    public Node removeNamedItem(String name) throws DOMException {
        Node node = getNamedItem(name);
        if (node == null) {
            throw new DOMException(DOMException.NOT_FOUND_ERR, "Not found");
        } else {
            mNodes.remove(node);
        }
        return node;
    }

    public Node removeNamedItemNS(String namespaceURI, String localName)
            throws DOMException {
        // TODO Auto-generated method stub
        return null;
    }

    public Node setNamedItem(Node arg) throws DOMException {
        Node existing = getNamedItem(arg.getNodeName());
        if (existing != null) {
            mNodes.remove(existing);
        }
        mNodes.add(arg);
        return existing;
    }

    public Node setNamedItemNS(Node arg) throws DOMException {
        // TODO Auto-generated method stub
        return null;
    }

}


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

namespace Kairos.Net
{
    /// <summary>
    ///     The response to the facial recognition detect method
    /// </summary>
    public class DetectResponse
    {
        /// <summary>
        ///     Default constructor
        /// </summary>
        public DetectResponse()
        {
            Images = new List<DetectImage>();
            Errors = new List<Errors>();
        }

        /// <summary>
        ///     Images detected
        /// </summary>
        public List<DetectImage> Images { get; set; }

        public List<Errors> Errors { get; set; }

        public bool HasFaces()
        {
            return Images.Any();
        }
    }
}


text:
<bill session="110" type="h" number="291" updated="2009-01-08T17:20:17-05:00">
	<status><introduced date="1167973200" datetime="2007-01-05"/></status>

	<introduced date="1167973200" datetime="2007-01-05"/>
	<titles>
		<title type="short" as="introduced">Safe NOW Act of 2007</title>
		<title type="official" as="introduced">To establish a National Sex Offender Risk Classification Task Force to create guidelines for the establishment of a risk-based sex offender classification system for use in sex offender registries.</title>
	</titles>
	<sponsor id="400150"/>
	<cosponsors>

	</cosponsors>
	<actions>
		<action date="1167973200" datetime="2007-01-05"><text>Referred to the House Committee on the Judiciary.</text></action>
		<action date="1170392400" datetime="2007-02-02"><text>Referred to the Subcommittee on Crime, Terrorism, and Homeland Security.</text></action>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>

	1/5/2007--Introduced.
Safe NOW Act of 2007 - Establishes the National Sex Offender Risk Classification Task Force to create guidelines for a risk-based sex offender classification system. Authorizes the Task Force to carry out demonstration programs in five selected jurisdictions to: (1) use the Task Force's preliminary guidelines to implement such a system for their sex offender registries; and (2) identify ways to improve such guidelines. Expresses the sense of Congress that each participating jurisdiction should use final Task Force guidelines to implement such a system for its registry.

</bill>


text:
Indba Node Logger
=================

Standardized logging module. Uses winston.


text:
<?php

namespace ZfModule\View\Model\Comment;

use Zend\View\Model\ViewModel;
/**
 *
 *
 * @author gerard
 */
class Reply extends ViewModel
{

}

?>


text:
package org.apache.hadoop.hive.metastore;

import java.util.concurrent.TimeUnit;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.metastore.annotation.MetastoreCheckinTest;
import org.apache.hadoop.hive.metastore.client.builder.DatabaseBuilder;
import org.apache.hadoop.hive.metastore.client.builder.TableBuilder;
import org.apache.hadoop.hive.metastore.conf.MetastoreConf;
import org.apache.hadoop.hive.metastore.conf.MetastoreConf.ConfVars;
import org.apache.hadoop.hive.metastore.security.HadoopThriftAuthBridge;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;

/**
 * TestRetryingHMSHandler. Test case for
 * {@link org.apache.hadoop.hive.metastore.RetryingHMSHandler}
 */
@Category(MetastoreCheckinTest.class)
public class TestRetryingHMSHandler {
  private Configuration conf;
  private HiveMetaStoreClient msc;

  @Before
  public void setUp() throws Exception {
    System.setProperty("hive.metastore.pre.event.listeners",
        AlternateFailurePreListener.class.getName());
    conf = MetastoreConf.newMetastoreConf();
    MetastoreConf.setLongVar(conf, ConfVars.THRIFT_CONNECTION_RETRIES, 3);
    MetastoreConf.setLongVar(conf, ConfVars.HMS_HANDLER_ATTEMPTS, 2);
    MetastoreConf.setTimeVar(conf, ConfVars.HMS_HANDLER_INTERVAL, 0, TimeUnit.MILLISECONDS);
    MetastoreConf.setBoolVar(conf, ConfVars.HMS_HANDLER_FORCE_RELOAD_CONF, false);
    MetaStoreTestUtils.setConfForStandloneMode(conf);
    MetaStoreTestUtils.startMetaStoreWithRetry(HadoopThriftAuthBridge.getBridge(), conf);
    msc = new HiveMetaStoreClient(conf);
  }

  // Create a database and a table in that database.  Because the AlternateFailurePreListener is
  // being used each attempt to create something should require two calls by the RetryingHMSHandler
  @Test
  public void testRetryingHMSHandler() throws Exception {
    String dbName = "hive4159";
    String tblName = "tmptbl";

    new DatabaseBuilder()
        .setName(dbName)
        .create(msc, conf);

    Assert.assertEquals(2, AlternateFailurePreListener.getCallCount());

    new TableBuilder()
        .setDbName(dbName)
        .setTableName(tblName)
        .addCol("c1", ColumnType.STRING_TYPE_NAME)
        .create(msc, conf);

    Assert.assertEquals(4, AlternateFailurePreListener.getCallCount());
  }

}


text:
import { AbstractTestCase, moduleFor } from 'internal-test-helpers';
import { cached, tracked } from '../..';

moduleFor(
  '@cached decorator: get',
  class extends AbstractTestCase {
    '@test it works'() {
      let assert = this.assert;

      class Person {
        @tracked firstName = 'Jen';
        @tracked lastName = 'Weber';

        @cached
        get fullName() {
          let fullName = `${this.firstName} ${this.lastName}`;

          assert.step(fullName);
          return fullName;
        }
      }

      let person = new Person();

      assert.verifySteps([], 'getter is not called after class initialization');

      assert.strictEqual(person.fullName, 'Jen Weber');
      assert.verifySteps(['Jen Weber'], 'getter was called after property access');

      assert.strictEqual(person.fullName, 'Jen Weber');
      assert.verifySteps([], 'getter was not called again after repeated property access');

      person.firstName = 'Kenneth';
      assert.verifySteps([], 'changing a property does not trigger an eager re-computation');

      assert.strictEqual(person.fullName, 'Kenneth Weber');
      assert.verifySteps(['Kenneth Weber'], 'accessing the property triggers a re-computation');

      assert.strictEqual(person.fullName, 'Kenneth Weber');
      assert.verifySteps([], 'getter was not called again after repeated property access');

      person.lastName = 'Larsen';
      assert.verifySteps([], 'changing a property does not trigger an eager re-computation');

      assert.strictEqual(person.fullName, 'Kenneth Larsen');
      assert.verifySteps(['Kenneth Larsen'], 'accessing the property triggers a re-computation');
    }

    '@test it has a separate cache per class instance'() {
      let assert = this.assert;

      class Person {
        @tracked firstName;
        @tracked lastName;

        constructor(firstName, lastName) {
          this.firstName = firstName;
          this.lastName = lastName;
        }

        @cached
        get fullName() {
          let fullName = `${this.firstName} ${this.lastName}`;
          assert.step(fullName);
          return fullName;
        }
      }

      let jen = new Person('Jen', 'Weber');
      let chris = new Person('Chris', 'Garrett');

      assert.verifySteps([], 'getter is not called after class initialization');

      assert.strictEqual(jen.fullName, 'Jen Weber');
      assert.verifySteps(['Jen Weber'], 'getter was called after property access');

      assert.strictEqual(jen.fullName, 'Jen Weber');
      assert.verifySteps([], 'getter was not called again after repeated property access');

      assert.strictEqual(chris.fullName, 'Chris Garrett', 'other instance has a different value');
      assert.verifySteps(['Chris Garrett'], 'getter was called after property access');

      assert.strictEqual(chris.fullName, 'Chris Garrett');
      assert.verifySteps([], 'getter was not called again after repeated property access');

      chris.lastName = 'Manson';
      assert.verifySteps([], 'changing a property does not trigger an eager re-computation');

      assert.strictEqual(jen.fullName, 'Jen Weber', 'other instance is unaffected');
      assert.verifySteps([], 'getter was not called again after repeated property access');

      assert.strictEqual(chris.fullName, 'Chris Manson');
      assert.verifySteps(['Chris Manson'], 'getter was called after property access');

      assert.strictEqual(jen.fullName, 'Jen Weber', 'other instance is unaffected');
      assert.verifySteps([], 'getter was not called again after repeated property access');
    }
  }
);


text:
package net.lifeinvader.app.view;

import java.util.Observable;
import java.util.Observer;
import javax.swing.JFrame;
import net.lifeinvader.app.controller.Controller;
import net.lifeinvader.app.model.Model;

/**
 * Represents an Abstract view of the game
 *
 * @author Christophe Van Waesberghe
 * (contact@chrisv.be)
 * @author Danielle Delfosse
 * (delfosse.da@gmail.com)
 */
public abstract class View extends javax.swing.JFrame implements Observer {

    /**
     * The controller of the view
     */
    protected Controller controller;

    /**
     * The model of the view
     */
    protected Model model;

    /**
     * Full constructor of the View
     *
     * @param controller Controller of the view
     * @param model Model of the view
     */
    public View(Controller controller, Model model) {
        this.controller = controller;
        this.model = model;

    }

    public View(){

    }

    /**
     * Add a model to observe
     *
     * @param model Observable model to observe
     */
    public void addModel(Observable model) {
        model.addObserver(this);
    }

    /**
     * Add an observable object
     *
     * @param observable Observable object
     */
    public void addObservable(Observable observable) {
        observable.addObserver(this);
    }

    /**
     * Set the controller of the view
     *
     * @param controller Controller
     */
    public void setController(Controller controller) {
        this.controller = controller;
    }

    /**
     * Show the gameMenu and ask the user if they want to start a game, load or
     * quit
     *
     */
    public abstract void gameMenu();

    /**
     * Ask the user if the instance is a server or a client
     *
     */
    public abstract void isServer();

    public abstract void connectionSetUp();

    /**
     * Ask the user to enter the name of his SocialNetwork
     *
     */
    public abstract void socialNetworkCreation();

    /**
     * Draw a win screen
     */
    public abstract void winScreen();

    /**
     * Draw a game over screen
     */
    public abstract void gameOverScreen();

}


text:
package pl.grzeslowski.jsupla.protocoljava.impl.serializers.sdc;

import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import pl.grzeslowski.jsupla.protocoljava.api.entities.sdc.GetVersionResult;
import pl.grzeslowski.jsupla.protocoljava.api.entities.sdc.PingServerResultClient;
import pl.grzeslowski.jsupla.protocoljava.api.entities.sdc.ServerDeviceClientEntity;
import pl.grzeslowski.jsupla.protocoljava.api.entities.sdc.SetActivityTimeoutResult;
import pl.grzeslowski.jsupla.protocoljava.api.entities.sdc.VersionError;
import pl.grzeslowski.jsupla.protocoljava.api.serializers.Serializer;
import pl.grzeslowski.jsupla.protocoljava.api.serializers.sdc.GetVersionResultSerializer;
import pl.grzeslowski.jsupla.protocoljava.api.serializers.sdc.PingServerResultClientSerializer;
import pl.grzeslowski.jsupla.protocoljava.api.serializers.sdc.SetActivityTimeoutResultSerializer;
import pl.grzeslowski.jsupla.protocoljava.api.serializers.sdc.VersionErrorSerializer;
import pl.grzeslowski.jsupla.protocoljava.impl.serializers.AbstractSerializerFactoryTest;

import java.util.Arrays;
import java.util.Collection;

@SuppressWarnings({"WeakerAccess", "unused"})
@RunWith(Parameterized.class)
public class ServerDeviceClientSerializerImplTest extends AbstractSerializerFactoryTest<ServerDeviceClientEntity> {

    @Parameterized.Parameters(name = "{0}")
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][]{
                {GetVersionResult.class},
                {VersionError.class},
                {SetActivityTimeoutResult.class},
                {PingServerResultClient.class}
        });
    }

    @InjectMocks ServerDeviceClientSerializerImpl serializer;

    @Mock GetVersionResultSerializer getVersionResultSerializer;
    @Mock PingServerResultClientSerializer pingServerResultClientSerializer;
    @Mock SetActivityTimeoutResultSerializer setActivityTimeoutResultSerializer;
    @Mock VersionErrorSerializer versionErrorSerializer;

    public ServerDeviceClientSerializerImplTest(final Class<ServerDeviceClientEntity> entityClass) {
        super(entityClass);
    }

    @Override
    protected Serializer<ServerDeviceClientEntity, ?> getSerializer() {
        return serializer;
    }

    @Override
    protected Class<ServerDeviceClientEntity> superInterface() {
        return ServerDeviceClientEntity.class;
    }
}


text:
package ein

import (
	"fmt"
	"os"

	"github.com/veandco/go-sdl2/sdl"
	"github.com/veandco/go-sdl2/sdl_ttf"
)

type Label struct {
	text string
	rect *sdl.Rect
	font *ttf.Font
}

func NewLabel(text string, x, y int32, font *ttf.Font) *Label {
	// TODO is is nice to pass fonts about like this
	// introduce font manager similar to texture and simply
	// take the font name
	return &Label{text, &sdl.Rect{x, y, 0, 0}, font}
}

func LoadFont(name string, size int) *ttf.Font {
	font, err := ttf.OpenFont(name, size)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Failed to load font: %s\n", sdl.GetError())
		os.Exit(3)
	}

	return font
}

func (t *Label) SetText(text string) {
	t.text = text
}

func (t *Label) Draw(renderer *sdl.Renderer) {
	surface, err := t.font.RenderUTF8_Solid(t.text, sdl.Color{255, 255, 255, 255})
	if err != nil {
		fmt.Fprintf(os.Stderr, "Failed to create surface: %s\n", err)
		os.Exit(1)
	}

	texture, err := renderer.CreateTextureFromSurface(surface)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Failed to create texture: %s\n", err)
		os.Exit(1)
	}

	src := &sdl.Rect{0, 0, surface.W, surface.H}
	dst := &sdl.Rect{t.rect.X, t.rect.Y, src.W, src.H}

	renderer.Copy(texture, src, dst)
	surface.Free()
}

func (t *Label) Position() (int32, int32) {
	return t.rect.X, t.rect.Y
}

func (t *Label) Size() (int32, int32) {
	return t.rect.W, t.rect.H
}


text:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <winpr/windows.h>

#include <freerdp/utils/time.h>

UINT64 freerdp_windows_gmtime()
{
	time_t unix_time;
	UINT64 windows_time;

	time(&unix_time);
	windows_time = freerdp_get_windows_time_from_unix_time(unix_time);

	return windows_time;
}

UINT64 freerdp_get_windows_time_from_unix_time(time_t unix_time)
{
	UINT64 windows_time;
	windows_time = (unix_time * 10000000) + 621355968000000000ULL;
	return windows_time;
}

time_t freerdp_get_unix_time_from_windows_time(UINT64 windows_time)
{
	time_t unix_time;
	unix_time = (windows_time - 621355968000000000ULL) / 10000000;
	return unix_time;
}


text:
using namespace centauri::appctl::common;
using centauri::appctl::common::commands::reloadOpts_t;

namespace centauri {
    namespace appctl {
        namespace reload {
            int command::run(commandOptions_t *_options) {
                reloadOpts_t *options = (reloadOpts_t *) _options;
                return ENOSYS;
            }
        }
    }
}


text:
package com.craftmend.openaudiomc.generic.networking.payloads.client.ui;

import com.craftmend.openaudiomc.generic.networking.abstracts.AbstractPacketPayload;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class ClientVersionPayload extends AbstractPacketPayload {

    private int protocolRevision = 4;

}


text:
#include <windows.h>

namespace Afx {
namespace BinUtils {

struct MemRange
{
	static MemRange FromSize(DWORD address, DWORD size);

	// inclusive
	DWORD Start;

	// exclusive
	DWORD End;

	MemRange();
	MemRange(DWORD start, DWORD end);

	bool IsEmpty(void) const;

	MemRange And(const MemRange & range) const;
};

class ImageSectionsReader
{
public:
	ImageSectionsReader(HMODULE hModule);

	bool Eof(void);

	void Next(void);

	/// <param name="characteristicsFilter">Minium bit mask that must be matched, should be a combination of IMAGE_SCN_*</param>
	void Next(DWORD characteristicsFilter);

	PIMAGE_SECTION_HEADER Get(void);
	MemRange GetMemRange(void);
	DWORD GetStartAddress(void);
	DWORD GetSize(void);

private:
	HMODULE m_hModule;
	PIMAGE_SECTION_HEADER m_Section;
	DWORD m_SectionsLeft;
};

/// <remarks>The memory specified by memRange must be readable.</remarks>
MemRange FindBytes(MemRange memRange, char const * pattern, DWORD patternSize);

/// <remarks>The memory specified by memRange must be readable.</remarks>
MemRange FindCString(MemRange memRange, char const * pattern);

/// <remarks>The memory specified by memRange must be readable.</remarks>
MemRange FindWCString(MemRange memRange, wchar_t const * pattern);

/// <remarks>The memory specified by memRange must be readable.</remarks>
/// <param name="hexBytePattern">
/// A pattern like "00 de ?? be ef"
/// Pattern is assumed to be valid, if it's not nothing will crash, but results
/// can be unexpected.
/// </param>
MemRange FindPatternString(MemRange memRange, char const * hexBytePattern);

/// <returns>0 if not found, otherwise address of vtable</returns>
DWORD FindClassVtable(HMODULE hModule, const char * name, DWORD rttiBaseClassArrayOffset, DWORD completeObjectLocatorOffset);

} // namespace Afx {
} // namespace BinUtils {


text:
Try it out!

      In the I Ching, it's all about hexagrams (64 in total). Each hexagram in the I Ching represents a specific set of wisdom (think of cards in a Tarot deck). Press the button to "flip a coin" six times, which will return a random hexagram from the I Ching. Read and ponder, as you apply it to your question.

    <button type="submit" name="hex-button" ng-click="landcontrol.castHexagram()" href="#/results">Press here</button>

what is it?

      The I Ching is one of the five fundamental books of Confucianism. It is over 3000 years old, making it one of the oldest surviving books in the world and one of the oldest forms of divination.

      The Book of Changes is the most popular spiritual resource and oracle in Asia. It is also growing in popularity in Europe and the Americas, due perhaps to its ability to yield deep insight to those who ponder it carefully.


text:
package mongo

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/scritch007/ShareMinatorApiGenerator/api"
	"github.com/scritch007/go-tools"
	"github.com/scritch007/shareit/types"
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
	"strconv"
	"strings"
	"sync"
)

const (
	Name string = "MongoDb"
)

type pathAccesses struct {
	Accesses map[string]api.AccessType `json:"access" bson:"access"`
	UserId   string                    `json:"user_id" bson:"user_id"`
}

type MongoDatabase struct {
	Ip      string `json:"ip"`
	session *mgo.Session
	lock    sync.RWMutex
}

func NewMongoDatase(config *json.RawMessage) (d *MongoDatabase, err error) {
	d = new(MongoDatabase)
	if err = json.Unmarshal(*config, d); nil != err {
		return nil, err
	}
	session, err := mgo.Dial(d.Ip)
	if err != nil {
		fmt.Println("Unable to connect to local mongo instance!")
		return nil, err
	}
	d.session = session
	d.session.SetMode(mgo.Monotonic, true)
	return d, nil
}

func (d *MongoDatabase) Name() string {
	return Name
}

type LogLevel int

const (
	DEBUG LogLevel = iota
	INFO
	WARNING
	ERROR
)

func (d *MongoDatabase) Log(level LogLevel, message string) {
	switch level {
	case DEBUG:
		tools.LOG_DEBUG.Println("MongoDb: ", message)
	case INFO:
		tools.LOG_INFO.Println("MongoDb: ", message)
	case WARNING:
		tools.LOG_WARNING.Println("MongoDb: ", message)
	case ERROR:
		tools.LOG_ERROR.Println("MongoDb: ", message)
	}
}

func (d *MongoDatabase) SaveCommand(command *types.Command) (err error) {
	d.lock.Lock()
	defer d.lock.Unlock()
	c := d.session.DB("mongo").C("commands")

	if 0 == len(command.ApiCommand.CommandId) {
		index, err := c.Find(nil).Count()
		if err != nil {
			return errors.New("Register error")
		}
		command.ApiCommand.CommandId = strconv.Itoa(index + 1)
		command.CommandId = command.ApiCommand.CommandId
		err = c.Insert(command)
		if err != nil {
			return errors.New("Register error")
		}
	}

	err = c.Update(bson.M{"command_id": command.ApiCommand.CommandId}, command)
	if nil != err {
		return errors.New("Update error")
	}
	d.Log(DEBUG, fmt.Sprintf("%s : %s", "Saved new Command", command.ApiCommand.Name))
	return nil
}

func (d *MongoDatabase) ListCommands(user *string, offset int, limit int, search_parameters *api.CommandsSearchParameters) ([]*types.Command, int, error) {
	d.lock.RLock()
	defer d.lock.RUnlock()
	var results []*types.Command
	c := d.session.DB("mongo").C("commands")
	// TODO: use search parameters?
	err := c.Find(bson.M{"user": user}).All(&results)
	if err != nil {
		return nil, 0, errors.New("I/O error in database")
	}

	return results, len(results), nil
}

func (d *MongoDatabase) GetCommand(ref string) (command *types.Command, err error) {
	d.lock.RLock()
	defer d.lock.RUnlock()
	c := d.session.DB("mongo").C("commands")

	command_id, err := strconv.ParseInt(ref, 0, 0)
	if nil != err {
		return nil, err
	}

	var result *types.Command

	err = c.Find(bson.M{"command_id": command_id}).One(&result)
	if err != nil {
		return nil, err
	}

	return result, nil
}

func (d *MongoDatabase) DeleteCommand(ref *string) error {
	d.lock.Lock()
	defer d.lock.Unlock()
	c := d.session.DB("mongo").C("commands")

	command_id, err := strconv.ParseInt(*ref, 0, 0)
	if nil != err {
		return err
	}
	err = c.Remove(bson.M{"command_id": command_id})
	if err != nil {
		return err
	}

	return nil
}

func (d *MongoDatabase) AddDownloadLink(link *types.DownloadLink) (err error) {
	d.lock.Lock()
	defer d.lock.Unlock()
	c := d.session.DB("mongo").C("download_links")

	err = c.Insert(link)
	if err != nil {
		return errors.New("Register error")
	}

	d.Log(DEBUG, fmt.Sprintf("%s: %s", "Saving download link", link))
	return nil
}

func (d *MongoDatabase) GetDownloadLink(ref string) (link *types.DownloadLink, err error) {
	d.lock.RLock()
	defer d.lock.RUnlock()
	c := d.session.DB("mongo").C("download_links")

	var result *types.DownloadLink
	err = c.Find(bson.M{"link": ref}).One(&result)
	if (err != nil) || (result == nil) {
		d.Log(ERROR, fmt.Sprintf("%s, %s", "Couldn't find download link", ref))
		return nil, errors.New(fmt.Sprintf("%s: %s", "Couldn't find this downloadLink", ref))
	}

	return result, nil
}

func (d *MongoDatabase) AddAccount(account *types.Account) (err error) {
	d.lock.Lock()
	defer d.lock.Unlock()
	c := d.session.DB("mongo").C("accounts")
	//Check if same user already exists
	result, err := c.Find(bson.M{"$or": []bson.M{{"login": account.Login}, {"email": account.Email}}}).Count()
	if (err != nil) || (result != 0) {
		return errors.New("Account already exists")
	}
	index, err := c.Find(nil).Count()

	account.Id = strconv.Itoa(index + 1)
	err = c.Insert(account)
	if err != nil {
		return errors.New("Register error")
	}
	d.Log(DEBUG, fmt.Sprintf("%s : %s", "Saved new Account", account))

	return nil
}

func (d *MongoDatabase) GetAccount(authType string, ref string) (account *types.Account, id string, err error) {
	d.lock.RLock()
	defer d.lock.RUnlock()
	return d.getAccount(authType, ref)
}

func (d *MongoDatabase) getAccount(authType string, ref string) (account *types.Account, id string, err error) {
	c := d.session.DB("mongo").C("accounts")

	var result *types.Account
	err = c.Find(bson.M{"$or": []bson.M{{"login": ref}, {"email": ref}}}).One(&result)
	if err != nil {
		message := fmt.Sprintf("GetAccount: Couldn't find the desired account %s:%s", authType, ref)
		d.Log(ERROR, message)
		fmt.Println(err)
		return nil, "", errors.New(message)
	}

	if 0 == len(authType) {
		return result, result.Id, nil
	}
	_, found := result.Auths[authType]
	if !found {
		message := fmt.Sprintf("Couldn't find this kind of authentication %s for %s", authType, ref)
		d.Log(ERROR, message)
		return nil, "", errors.New(message)
	}

	return result, result.Id, nil
}

func (d *MongoDatabase) UpdateAccount(id string, account *types.Account) (err error) {
	d.lock.Lock()
	defer d.lock.Unlock()
	c := d.session.DB("mongo").C("accounts")
	account_id, err := strconv.ParseInt(id, 0, 0)
	if nil != err {
		return err
	}

	err = c.Update(bson.M{"id": account_id}, account)
	if nil != err {
		return err
	}
	return nil
}

func (d *MongoDatabase) GetUserAccount(id string) (account *types.Account, err error) {
	d.lock.RLock()
	defer d.lock.RUnlock()
	c := d.session.DB("mongo").C("accounts")

	var result *types.Account
	err = c.Find(bson.M{"id": id}).One(&result)
	if nil != err {
		message := fmt.Sprintf("GetUserAccount: Couldn't find the desired account %s", id)
		d.Log(ERROR, message)
		return nil, errors.New(message)
	}
	return result, nil
}

func (d *MongoDatabase) ListAccounts(searchDict map[string]string) (accounts []*types.Account, err error) {
	d.lock.RLock()
	defer d.lock.RUnlock()
	c := d.session.DB("mongo").C("accounts")
	var results []*types.Account

	err = c.Find(nil).All(&results)

	if 0 == len(searchDict) {
		d.Log(DEBUG, "No search parameters")
		return results, nil
	}

	d.Log(DEBUG, fmt.Sprintf("We had some search parameters ", searchDict))
	accounts = make([]*types.Account, len(results))
	i := 0
	for _, account := range results {
		for k, v := range searchDict {
			switch k {
			case "login":
				if strings.Contains(account.Login, v) {
					accounts[i] = account
					i += 1
					break
				}
			case "email":
				if strings.Contains(account.Email, v) {
					accounts[i] = account
					i += 1
					break
				}
			case "id":
				if strings.Contains(account.Id, v) {
					accounts[i] = account
					i += 1
					break
				}
			}
		}
	}
	return accounts[0:i], nil
}

func (d *MongoDatabase) StoreSession(session *types.Session) (err error) {
	d.lock.Lock()
	defer d.lock.Unlock()
	c := d.session.DB("mongo").C("sessions")
	count, err := c.Find(bson.M{"user_id": session.UserId}).Count()
	if err != nil {
		return errors.New("Register error")
	}
	if count != 0 {
		return nil
	}
	err = c.Insert(session)
	if err != nil {
		return errors.New("Register error")
	}
	return nil
}

func (d *MongoDatabase) GetSession(ref string) (session *types.Session, err error) {
	d.lock.RLock()
	defer d.lock.RUnlock()
	c := d.session.DB("mongo").C("sessions")
	var result *types.Session
	err = c.Find(bson.M{"authentication_header": ref}).One(&result)
	if err != nil {
		return nil, errors.New("Couldn't find session")
	}
	return result, nil
}

func (d *MongoDatabase) RemoveSession(ref string) (err error) {
	d.lock.Lock()
	defer d.lock.Unlock()
	c := d.session.DB("mongo").C("sessions")
	err = c.Remove(bson.M{"authentication_header": ref})
	if err != nil {
		return err
	}
	return nil
}

func (d *MongoDatabase) SaveShareLink(shareLink *types.ShareLink) (err error) {
	d.lock.Lock()
	defer d.lock.Unlock()
	//TODO check if there is already a sharelink with this name and user
	c := d.session.DB("mongo").C("shares_link")
	shareLink.Id = *shareLink.ShareLink.Key
	err = c.Insert(shareLink)
	if err != nil {
		return errors.New("Register SaveShareLink error")
	}
	return nil
}

func (d *MongoDatabase) UpdateShareLink(shareLink *types.ShareLink) (err error) {
	d.lock.Lock()
	defer d.lock.Unlock()
	c := d.session.DB("mongo").C("shares_link")
	err = c.Update(bson.M{"path": *shareLink.ShareLink.Path}, shareLink)
	if err != nil {
		return errors.New("Update SaveShareLink error")
	}
	return nil
}

func (d *MongoDatabase) GetShareLink(key string) (shareLink *types.ShareLink, err error) {
	d.lock.RLock()
	defer d.lock.RUnlock()
	c := d.session.DB("mongo").C("shares_link")
	var result *types.ShareLink
	err = c.Find(bson.M{"id": key}).One(&result)
	if err != nil {
		message := fmt.Sprintf("Couldn't find share link %s", key)
		d.Log(ERROR, message)
		return nil, errors.New(message)
	}
	return result, nil
}

func (d *MongoDatabase) RemoveShareLink(key string) (err error) {
	d.lock.Lock()
	defer d.lock.Unlock()
	c := d.session.DB("mongo").C("shares_link")
	err = c.Remove(bson.M{"id": key})
	if err != nil {
		return err
	}
	return nil
}

func (d *MongoDatabase) ListShareLinks(user string) (shareLinks []*types.ShareLink, err error) {
	d.lock.RLock()
	defer d.lock.RUnlock()
	c := d.session.DB("mongo").C("shares_link")
	var results []*types.ShareLink
	err = c.Find(bson.M{"user": user}).All(&results)
	if err != nil {
		message := fmt.Sprintf("Couldn't find share link for user %s", user)
		d.Log(ERROR, message)
		return nil, errors.New(message)
	}
	return results, nil
}

func (d *MongoDatabase) GetShareLinksFromPath(path string, user string) (shareLink []*types.ShareLink, err error) {
	d.lock.RLock()
	defer d.lock.RUnlock()
	return d.getShareLinksFromPath(path, user)
}

func (d *MongoDatabase) getShareLinksFromPath(path string, user string) (shareLinks []*types.ShareLink, err error) {
	c := d.session.DB("mongo").C("shares_link")
	var results []*types.ShareLink
	err = c.Find(nil).All(&results)
	// TODO optimize it with and expression, pb: access to shareLink.ShareLink.Path in find request
	if err != nil {
		message := fmt.Sprintf("Couldn't find share link for user %s path %s", user, path)
		d.Log(ERROR, message)
		return nil, errors.New(message)
	}
	shareLinks = make([]*types.ShareLink, 0, 10)
	var count = 0
	for _, shareLink := range results {
		if *shareLink.ShareLink.Path == path && shareLink.User == user {
			shareLinks = shareLinks[0 : count+1]
			shareLinks[count] = shareLink
			count += 1
			if count == cap(shareLinks) {
				newSlice := make([]*types.ShareLink, len(shareLinks), 2*cap(shareLinks))
				for i := range shareLinks {
					newSlice[i] = shareLinks[i]
				}
				shareLinks = newSlice
			}
		}
	}
	return shareLinks, nil
}

func (d *MongoDatabase) GetAccess(user *string, path string) (api.AccessType, error) {
	d.lock.RLock()
	defer d.lock.RUnlock()
	return d.getAccess(user, path)
}

func (d *MongoDatabase) getAccess(user *string, path string) (api.AccessType, error) {
	c := d.session.DB("mongo").C("accesses")
	var access pathAccesses
	var user_id string
	if nil == user {
		user_id = ""
	} else {
		user_id = *user
	}

	message := fmt.Sprintf("GetAccess: %s path %s", user_id, path)
	d.Log(ERROR, message)
	err := c.Find(bson.M{"user_id": user_id}).One(&access)
	if err != nil {
		// If user is not Nil then look for the public accesses
		if nil == user {
			return api.NONE, nil
		}
		err = c.Find(bson.M{"user_id": ""}).One(&access)
		if err != nil {
			return api.NONE, nil
		}
	}

	// Now check for the path
	splittedPath := strings.Split(path, "/")
	finalAccessType := api.NONE
	for i := len(splittedPath); i > 0; i-- {
		accessType, found := access.Accesses[strings.Join(splittedPath[:i], "/")]
		tools.LOG_DEBUG.Println("Looking for access to ", strings.Join(splittedPath[:i], "/"))
		if found {
			finalAccessType = accessType
			break
		}
	}
	if api.NONE == finalAccessType && nil != user {
		return d.getAccess(nil, path)
	}

	return finalAccessType, nil
}

func (d *MongoDatabase) SetAccess(user *string, path string, access api.AccessType) error {
	d.lock.Lock()
	defer d.lock.Unlock()

	var user_id string
	if nil == user {
		user_id = ""
	} else {
		user_id = *user
	}

	c := d.session.DB("mongo").C("accesses")
	var path_access pathAccesses
	err := c.Find(bson.M{"user_id": user_id}).One(&path_access)
	if err != nil {
		//Create accessPath dict
		accesses := new(pathAccesses)
		accesses.Accesses = make(map[string]api.AccessType)
		accesses.UserId = user_id
		accesses.Accesses[path] = access
		err = c.Insert(accesses)
		if err != nil {
			message := fmt.Sprintf("Couldn't insert access %s path %s", user_id, path)
			d.Log(ERROR, message)
			return errors.New(message)
		}
		return nil
	}
	path_access.Accesses[path] = access
	err = c.Update(bson.M{"user_id": user_id}, path_access)
	if err != nil {
		message := fmt.Sprintf("Couldn't update access %s path %s", user_id, path)
		d.Log(ERROR, message)
		return errors.New(message)
	}
	return nil
}

func (d *MongoDatabase) ClearAccesses() error {
	d.lock.Lock()
	defer d.lock.Unlock()
	c := d.session.DB("mongo").C("accesses")
	err := c.DropCollection()
	if err != nil {
		// No entry in the database
		return nil
	}
	return nil
}


text:
{% extends 'layout.html' %}

{% block title %} {{post['title']}} {% endblock %}

{% block body %}

{{post['title']}}

Posted {{post['date']|date('d-m-Y')}} By {% if post['author'] %} {{ post['author'].username }} {% else %} undefined {% endif %}
{% if user %}
   - [edit]
  {% if post['deleted'] %}
  <form action="/post/{{post.permalink}}" method="POST" style="display:inline">
    <input type="hidden" value="delete" name="_method" />
    <button type="submit" class="submitlink">[delete]</button>
  </form>
  {% endif %}
{% endif %}

{% autoescape false %}
{{post['body']}}
{% endautoescape %}

{% if post.tags %}
  Tags:
{% endif %}
{% for tag in post.tags %}
    {% if loop.first %}
        {{tag}}
    {% else %}
        , {{tag}}
    {% endif %}
{% endfor %}

       Share on Facebook

       Share on Twitter

       Share on Google+

{% endblock %}


text:
// Copyright 2017 Jeremy Letang.
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use chrono;
use chrono::offset::utc::UTC;
use flickr_api::License as RawLicense;
use self::schema::{
    licenses,
    monuments,
    pictures,
    last_updates
};
use std::str::FromStr;
use time::Duration;
use uuid::Uuid;

pub mod schema;
pub mod dao;

fn now() -> chrono::NaiveDateTime {
    chrono::NaiveDateTime::from_timestamp(UTC::now().timestamp(), 0)
}

#[derive(Clone, PartialEq, Debug, Queryable, Insertable)]
#[table_name="monuments"]
pub struct Monument {
    pub id: String,
    pub category: Option<String>,
    pub criteria_txt: Option<String>,
    pub danger: Option<String>,
    pub date_inscribed: Option<String>,
    pub extension: Option<i32>,
    pub historical_description: Option<String>,
    pub http_url: Option<String>,
    pub id_number: Option<i32>,
    pub image_url: Option<String>,
    pub iso_code: Option<String>,
    pub justification: Option<String>,
    pub latitude: Option<f32>,
    pub longitude: Option<f32>,
    pub location: Option<String>,
    pub long_description: Option<String>,
    pub region: Option<String>,
    pub revision: Option<i32>,
    pub secondary_dates: Option<String>,
    pub short_description: Option<String>,
    pub site: Option<String>,
    pub states: Option<String>,
    pub transboundary: Option<i32>,
    pub unique_number: Option<i32>,

    pub created_at: chrono::NaiveDateTime,
    pub updated_at: chrono::NaiveDateTime,
}

impl Monument {
    pub fn new() -> Monument {
        Monument {
            id: String::new(),
            category: None,
            criteria_txt: None,
            danger: None,
            date_inscribed: None,
            extension: None,
            historical_description: None,
            http_url: None,
            id_number: None,
            image_url: None,
            iso_code: None,
            justification: None,
            latitude: None,
            longitude: None,
            location: None,
            long_description: None,
            region: None,
            revision: None,
            secondary_dates: None,
            short_description: None,
            site: None,
            states: None,
            transboundary: None,
            unique_number: None,

            created_at: now(),
            updated_at: now()
        }
    }

    pub fn set(&mut self, field: &str, value: &str) {
        match field {
            "category" => self.category = FromStr::from_str(value).ok(),
            "criteria_txt" => self.criteria_txt = FromStr::from_str(value).ok(),
            "danger" => self.danger = FromStr::from_str(value).ok(),
            "date_inscribed" => self.date_inscribed = FromStr::from_str(value).ok(),
            "extension" => self.extension = FromStr::from_str(value).ok(),
            "historical_description" => self.historical_description = FromStr::from_str(value).ok(),
            "http_url" => self.http_url = FromStr::from_str(value).ok(),
            "id_number" => self.id_number = FromStr::from_str(value).ok(),
            "image_url" => self.image_url = FromStr::from_str(value).ok(),
            "iso_code" => self.iso_code = FromStr::from_str(value).ok(),
            "justification" => self.justification = FromStr::from_str(value).ok(),
            "latitude" => self.latitude = FromStr::from_str(value).ok(),
            "longitude" => self.longitude = FromStr::from_str(value).ok(),
            "location" => self.location = FromStr::from_str(value).ok(),
            "long_description" => self.long_description = FromStr::from_str(value).ok(),
            "region" => self.region = FromStr::from_str(value).ok(),
            "revision" => self.revision = FromStr::from_str(value).ok(),
            "secondary_dates" => self.secondary_dates = FromStr::from_str(value).ok(),
            "short_description" => self.short_description = FromStr::from_str(value).ok(),
            "site" => self.site = FromStr::from_str(value).ok(),
            "states" => self.states = FromStr::from_str(value).ok(),
            "transboundary" => self.transboundary = FromStr::from_str(value).ok(),
            "unique_number" => self.unique_number = FromStr::from_str(value).ok(),
            _ => {/* unknown name */}
        }
    }
}

#[derive(Clone, PartialEq, Debug, Queryable, Insertable)]
#[table_name="licenses"]
pub struct License {
    pub id: String,
    pub flickr_id: i32,
    pub name: String,
    pub url: Option<String>,

    pub created_at: chrono::NaiveDateTime,
    pub updated_at: chrono::NaiveDateTime,
}

impl From<RawLicense> for License {
    fn from(rl: RawLicense) -> Self {
        License {
            id: String::new(),
            flickr_id: rl.id,
            name: rl.name,
            url: rl.url,
            created_at: now(),
            updated_at: now()
        }
    }
}

#[derive(Clone, PartialEq, Debug, Queryable, Insertable)]
#[table_name="pictures"]
pub struct Picture {
    pub id: String,
    pub flickr_id: String,
    pub monument_id: String,
    pub license_id: String,
    pub author: String,
    pub url: String,

    pub created_at: chrono::NaiveDateTime,
    pub updated_at: chrono::NaiveDateTime,
}

impl Picture {
    pub fn new(flickr_id: String,
               monument_id: String,
               license_id: String,
               author: String,
               url: String) -> Picture {
        Picture {
            id: Uuid::new_v4().to_string(),
            flickr_id: flickr_id,
            monument_id: monument_id,
            license_id: license_id,
            author: author,
            url: url,

            created_at: now(),
            updated_at: now()
        }
    }
}

#[derive(Clone, PartialEq, Debug, Queryable, Insertable, Identifiable)]
#[table_name="last_updates"]
pub struct LastUpdate {
    pub id: String,
    pub monument_id: String,
    pub created_at: chrono::NaiveDateTime,
    pub updated_at: chrono::NaiveDateTime,
}

impl LastUpdate {
    pub fn new<S: Into<String>>(monument_id: S) -> LastUpdate {
        LastUpdate {
            id: Uuid::new_v4().to_string(),
            monument_id: monument_id.into(),
            created_at: now(),
            updated_at: now() - Duration::days(365),
        }
    }

    pub fn need_refresh(&self) -> bool {
        // reupdate if last update is more than a week ago
        let a_week_ago = now() - Duration::days(7);
        self.updated_at < a_week_ago
    }

    pub fn set_fresh(&mut self) {
        self.updated_at = now();
    }
}


text:
package v1

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"time"
)

import (
	"github.com/ertgl/croncache"
	"github.com/ertgl/croncache/lib"
	"github.com/ertgl/croncache/models"
	"github.com/ertgl/croncache/utils"
)

var (
	TaskTimeoutError error = errors.New("Task is timed out")
)

type TaskManager struct {
	lib.TaskManager
	moduleName string
	ioc        lib.IoC
	config     *Config
}

func NewTaskManager() lib.TaskManager {
	tm := &TaskManager{
		moduleName: MODULE_NAME,
		config:     NewConfig(),
	}
	return tm
}

func (tm *TaskManager) ModuleName() string {
	return tm.moduleName
}

func (tm *TaskManager) Initialize() error {
	var err error = nil
	return err
}

func (tm *TaskManager) IoC() lib.IoC {
	return tm.ioc
}

func (tm *TaskManager) SetIoC(ioc lib.IoC) {
	tm.ioc = ioc
	if tm.IoC().TaskManager() != tm {
		tm.IoC().SetTaskManager(tm)
	}
}

func (tm *TaskManager) ImportConfig(raw []byte) error {
	err := json.Unmarshal(raw, &tm.config)
	return err
}

func (tm *TaskManager) ExportConfig() ([]byte, error) {
	raw, err := json.MarshalIndent(&tm.config, "", "\t")
	return raw, err
}

func (tm *TaskManager) runTask(task *models.Task) error {
	ch := make(chan models.Cache, 1)
	errChan := make(chan error, 1)
	go func(ch chan models.Cache, errChan chan error) {
		cache, err := tm.IoC().Executer().Execute(
			task.Command,
			task.Timeout,
			task.Args...,
		)
		if err != nil {
			errChan <- err
			return
		}
		ch <- cache
	}(ch, errChan)
	select {
	case cache := <-ch:
		cacheEngineGenerator, err := croncache.CacheEngineRepository().Resolve(
			task.CacheEngineModuleName,
		)
		if err != nil {
			return err
		}
		cacheEngine := cacheEngineGenerator()
		err = cacheEngine.ImportConfig(*task.CacheEngineCredentials)
		if err != nil {
			return err
		}
		err = cacheEngine.Initialize()
		if err != nil {
			return err
		}
		defer cacheEngine.Close()
		err = cacheEngine.Upsert(cache)
		if err != nil {
			return err
		}
	case <-time.After(task.Timeout.Duration):
		return TaskTimeoutError
	case <-tm.IoC().Node().HaltSignal():
		return nil
	}
	return nil
}

func (tm *TaskManager) Process(task *models.Task) {
	for !tm.IoC().Node().IsHalted() {
		tm.IoC().Node().WaitGroup().Add(1)
		go func(task *models.Task) {
			defer tm.IoC().Node().WaitGroup().Done()
			iter := 0
			for !tm.IoC().Node().IsHalted() {
				err := tm.runTask(task)
				if err != nil {
					task.Log().Println(err)
					iter++
					if iter <= task.IterationOnFail {
						task.Log().Println(fmt.Sprintf(
							"Failover is enabled for %d times",
							iter,
						))
						continue
					}
				}
				break
			}
		}(task)
		time.Sleep(task.Interval.Duration)
	}
}

func (tm *TaskManager) Run() {
	for _, taskFilePath := range tm.config.Tasks {
		taskFilePath = utils.ReplaceOSVariables(taskFilePath)
		select {
		case <-tm.IoC().Node().HaltSignal():
			return
		default:
			var task *models.Task
			raw, err := ioutil.ReadFile(taskFilePath)
			if err != nil {
				tm.IoC().Node().Log().Println(taskFilePath, err)
				continue
			}
			err = json.Unmarshal(raw, &task)
			if err != nil {
				tm.IoC().Node().Log().Println(taskFilePath, err)
				continue
			}
			err = task.Initialize()
			if err != nil {
				tm.IoC().Node().Log().Println(taskFilePath, err)
				continue
			}
			tm.IoC().Node().WaitGroup().Add(1)
			go func(task *models.Task) {
				defer tm.IoC().Node().WaitGroup().Done()
				tm.Process(task)
			}(task)
		}
	}
}


text:
from colour import Color

class DeviceInfo(object):

	def __init__(self):
		self.on = False
		self.colour = Color("black")
		self.thread = None

	def IsOn(self):
		return self.on

	def SetIsOn(self, isOn):
		self.on = isOn

	def Colour(self):
		return self.colour

	def Thread(self):
		return self.thread


text:
// <copyright file="HandleParallelMessageOptions.cs" company="nett">
//      Copyright (c) 2015 All Right Reserved, http://q.nett.gr
//      Please see the License.txt file for more information. All other rights reserved.
// </copyright>
// <author>James Kavakopoulos</author>
// <email>ofthetimelords@gmail.com</email>
// <date>2015/02/06</date>
// <summary>
//
// </summary>

using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

using TheQ.Utilities.CloudTools.Storage.ExtendedQueue;
using TheQ.Utilities.CloudTools.Storage.Internal;

namespace TheQ.Utilities.CloudTools.Storage.Models
{
	/// <summary>
	///     <para>Input arguments for the ExtendedQueue framework.</para>
	/// </summary>
	public class HandleMessagesParallelOptions : HandleMessagesSerialOptions
	{
		/// <summary>
		///     <para>Initializes a new instance of the <see cref="HandleMessagesParallelOptions" /></para>
		///     <para>class.</para>
		/// </summary>
		/// <param name="timeWindow">
		///     <para>The time window within which a message is still valid for processing (older messages will be discarded). Use <see cref="System.TimeSpan.Zero" /></para>
		///     <para>to ignore this check.</para>
		/// </param>
		/// <param name="messageLeaseTime">The amount of time between periodic refreshes on the lease of a message.</param>
		/// <param name="pollFrequency">The frequency with which the queue is being polled for new messages.</param>
		/// <param name="poisonMessageThreshold">The amount of times a message can be enqueued.</param>
		/// <param name="maximumCurrentMessages">The maximum amount of messages that can be processed at the same batch.</param>
		/// <param name="cancelToken">A cancellation token to allow cancellation of this process.</param>
		/// <param name="messageHandler">An action that specifies how a message should be handled. Returns a value indicating whether the message has been handled successfully and should be removed.</param>
		/// <param name="poisonHandler">
		///     <para>An action that specifies how a poison message should be handled, which fires before <see cref="TheQ.Utilities.CloudTools.Storage.Models.HandleSerialOptions.MessageHandler" /></para>
		///     <para>. Returns a value indicating whether the message has been handled successfully and should be removed.</para>
		/// </param>
		/// <param name="exceptionHandler">An action that specifies how an exception should be handled.</param>
		/// <exception cref="ArgumentException">Parameter <paramref name="maximumCurrentMessages" /> exceeded 32 which is the maximum allowed value by Azure</exception>
		/// <exception cref="ArgumentNullException">cancelToken;The Cancellation Token parameter is required or messageHandler;The Message Handler <see langword="delegate" /> is required</exception>
		/// <exception cref="ArgumentException">
		///     Message Lease Time cannot be lower than 30 seconds! or Poll Frequency cannot be lower than 1 second! or Poison Message Threshold cannot be lower than 1.
		/// </exception>
		public HandleMessagesParallelOptions(
			TimeSpan timeWindow,
			TimeSpan messageLeaseTime,
			TimeSpan pollFrequency,
			int poisonMessageThreshold,
			int maximumCurrentMessages,
			CancellationToken cancelToken,
			[NotNull] Func<QueueMessageWrapper, Task<bool>> messageHandler,
			[CanBeNull] Func<QueueMessageWrapper, Task<bool>> poisonHandler = null,
			[CanBeNull] Action<Exception> exceptionHandler = null)
			: base(timeWindow, messageLeaseTime, pollFrequency, poisonMessageThreshold, cancelToken, messageHandler, poisonHandler, exceptionHandler)
		{
				this.MaximumCurrentMessages = maximumCurrentMessages;
		}

		/// <summary>
		///     Gets the maximum amount of messages that can be processed at the same batch.
		/// </summary>
		public int MaximumCurrentMessages { get; private set; }
	}
}


text:
package distribution;

import java.io.Serializable;

public class ReplyBody implements Serializable{
	/**
	 *
	 */
	private static final long serialVersionUID = 8600466569258190248L;
	private Object operationResult;

	public ReplyBody(Object opResult){
		this.operationResult = opResult;

	}
	public Object getOperationResult() {
		return operationResult;
	}

	public void setOperationResult(Object operationResult) {
		this.operationResult = operationResult;
	}
}


text:
"""Make TaskInstance.pool not nullable

Revision ID: 6e96a59344a4
Revises: 939bb1e647c8
Create Date: 2019-06-13 21:51:32.878437

"""

import dill
import sqlalchemy as sa
from alembic import op
from sqlalchemy import Column, Float, Integer, PickleType, String
from sqlalchemy.ext.declarative import declarative_base

from airflow.models.base import COLLATION_ARGS
from airflow.utils.session import create_session
from airflow.utils.sqlalchemy import UtcDateTime

# revision identifiers, used by Alembic.
revision = '6e96a59344a4'
down_revision = '939bb1e647c8'
branch_labels = None
depends_on = None

Base = declarative_base()
ID_LEN = 250

class TaskInstance(Base):  # type: ignore
    """
    Task instances store the state of a task instance. This table is the
    authority and single source of truth around what tasks have run and the
    state they are in.

    The SqlAlchemy model doesn't have a SqlAlchemy foreign key to the task or
    dag model deliberately to have more control over transactions.

    Database transactions on this table should insure double triggers and
    any confusion around what task instances are or aren't ready to run
    even while multiple schedulers may be firing task instances.
    """

    __tablename__ = "task_instance"

    task_id = Column(String(ID_LEN, **COLLATION_ARGS), primary_key=True)
    dag_id = Column(String(ID_LEN, **COLLATION_ARGS), primary_key=True)
    execution_date = Column(UtcDateTime, primary_key=True)
    start_date = Column(UtcDateTime)
    end_date = Column(UtcDateTime)
    duration = Column(Float)
    state = Column(String(20))
    _try_number = Column('try_number', Integer, default=0)
    max_tries = Column(Integer)
    hostname = Column(String(1000))
    unixname = Column(String(1000))
    job_id = Column(Integer)
    pool = Column(String(50), nullable=False)
    queue = Column(String(256))
    priority_weight = Column(Integer)
    operator = Column(String(1000))
    queued_dttm = Column(UtcDateTime)
    pid = Column(Integer)
    executor_config = Column(PickleType(pickler=dill))

def upgrade():
    """Make TaskInstance.pool field not nullable."""
    with create_session() as session:
        session.query(TaskInstance).filter(TaskInstance.pool.is_(None)).update(
            {TaskInstance.pool: 'default_pool'}, synchronize_session=False
        )  # Avoid select updated rows
        session.commit()

    conn = op.get_bind()
    if conn.dialect.name == "mssql":
        op.drop_index('ti_pool', table_name='task_instance')

    # use batch_alter_table to support SQLite workaround
    with op.batch_alter_table('task_instance') as batch_op:
        batch_op.alter_column(
            column_name='pool',
            type_=sa.String(50),
            nullable=False,
        )

    if conn.dialect.name == "mssql":
        op.create_index('ti_pool', 'task_instance', ['pool', 'state', 'priority_weight'])

def downgrade():
    """Make TaskInstance.pool field nullable."""
    conn = op.get_bind()
    if conn.dialect.name == "mssql":
        op.drop_index('ti_pool', table_name='task_instance')

    # use batch_alter_table to support SQLite workaround
    with op.batch_alter_table('task_instance') as batch_op:
        batch_op.alter_column(
            column_name='pool',
            type_=sa.String(50),
            nullable=True,
        )

    if conn.dialect.name == "mssql":
        op.create_index('ti_pool', 'task_instance', ['pool', 'state', 'priority_weight'])

    with create_session() as session:
        session.query(TaskInstance).filter(TaskInstance.pool == 'default_pool').update(
            {TaskInstance.pool: None}, synchronize_session=False
        )  # Avoid select updated rows
        session.commit()