text:
package org.auraframework.impl.system;

import java.util.Map;

import org.auraframework.impl.AuraImplTestCase;
import org.auraframework.system.Client;
import org.auraframework.system.Client.Type;
import org.auraframework.test.client.UserAgent;

import com.google.common.collect.Maps;

public class ClientTest extends AuraImplTestCase {
    public ClientTest(String name) {
        super(name);
    }

    /**
     * Verify that User Agent string is parsed out to obtain right ClientType
     */
    public void testGetType() {
        Map<String, Type> pairs = Maps.newHashMap();
        pairs.put(UserAgent.IE6.getUserAgentString(), Type.IE6);
        pairs.put(UserAgent.IE7.getUserAgentString(), Type.IE7);
        pairs.put(UserAgent.IE8.getUserAgentString(), Type.IE8);
        pairs.put(UserAgent.IE9.getUserAgentString(), Type.IE9);
        pairs.put(UserAgent.IE10.getUserAgentString(), Type.IE10);
        pairs.put(UserAgent.IE10_WINDOWS_PHONE_8.getUserAgentString(), Type.IE10);
        pairs.put(UserAgent.IE10_WINDOWS_RT_8.getUserAgentString(), Type.IE10);
        pairs.put(UserAgent.IE11_WINDOWS_PHONE_8_1.getUserAgentString(), Type.IE11);
        pairs.put(UserAgent.IE11_WINDOWS_RT_8_1.getUserAgentString(), Type.IE11);
        pairs.put(UserAgent.IE11_WINDOWS_PHONE_8_1_SDK.getUserAgentString(), Type.IE11);
        pairs.put(UserAgent.LUMIA_928.getUserAgentString(), Type.IE11);
        pairs.put(UserAgent.IE11.getUserAgentString(), Type.IE11);
        pairs.put(UserAgent.IE11_NET_FRAMEWORK.getUserAgentString(), Type.IE11);
        pairs.put(UserAgent.FIREFOX.getUserAgentString(), Type.FIREFOX);
        pairs.put(UserAgent.GOOGLE_CHROME.getUserAgentString(), Type.WEBKIT);
        pairs.put(UserAgent.SAFARI5_MAC.getUserAgentString(), Type.WEBKIT);
        pairs.put(UserAgent.SAFARI5_WINDOWS.getUserAgentString(), Type.WEBKIT);
        pairs.put(UserAgent.SAFARI6.getUserAgentString(), Type.WEBKIT);
        pairs.put(UserAgent.IPAD.getUserAgentString(), Type.WEBKIT);
        pairs.put(UserAgent.IPAD_7.getUserAgentString(), Type.WEBKIT);
        pairs.put(UserAgent.IPAD_WEBVIEW.getUserAgentString(), Type.WEBKIT);
        pairs.put(UserAgent.IPHONE4.getUserAgentString(), Type.WEBKIT);
        pairs.put(UserAgent.ANDROID4_2.getUserAgentString(), Type.WEBKIT);
        pairs.put(UserAgent.BLACKBERRY_7.getUserAgentString(), Type.WEBKIT);
        pairs.put(UserAgent.BLACKBERRY_10.getUserAgentString(), Type.WEBKIT);
        pairs.put(UserAgent.GOOD_IPHONE.getUserAgentString(), Type.WEBKIT);
        pairs.put(UserAgent.GOOD_ANDROID.getUserAgentString(), Type.WEBKIT);
        pairs.put(UserAgent.NEXUS_10.getUserAgentString(), Type.WEBKIT);
        pairs.put(UserAgent.NEXUS_9_CHROME.getUserAgentString(), Type.WEBKIT);
        pairs.put(UserAgent.NEXUS_9_SFDC_CONTAINER.getUserAgentString(), Type.WEBKIT);
        pairs.put(UserAgent.NEXUS_7_SFDC_CONTAINER.getUserAgentString(), Type.WEBKIT);
        pairs.put(UserAgent.OPERA12.getUserAgentString(), Type.OTHER);
        pairs.put(UserAgent.OPERA_MINI.getUserAgentString(), Type.OTHER);
        pairs.put(UserAgent.NETSCAPE.getUserAgentString(), Type.OTHER);
        pairs.put("", Type.OTHER);

        for (String userAgent : pairs.keySet()) {
            assertEquals("Unexpected ClientType from userAgent string:",
                    pairs.get(userAgent), new Client(userAgent).getType());
        }
        assertEquals("Unexpected ClientType from userAgent string:", Type.OTHER, new Client().getType());
        assertEquals("Unexpected ClientType from userAgent string:", Type.OTHER, new Client(null).getType());
    }

    public void testDefaultClientType() throws Exception {
        Client client = new Client();
        assertEquals("Incorrect default client type.", client.getType().name(), "OTHER");
    }
}


text:
require 'digest/sha1'
class User < ActiveRecord::Base
  has_many :tasks, :dependent => :destroy
  has_many :categories, :dependent => :destroy

  # Virtual attribute for the unencrypted password
  attr_accessor :password

  validates_presence_of     :login
  validates_presence_of     :password,                   :if => :password_required?
  validates_presence_of     :password_confirmation,      :if => :password_required?
  validates_length_of       :password, :within => 4..40, :if => :password_required?
  validates_confirmation_of :password,                   :if => :password_required?
  validates_length_of       :login,    :within => 2..40
  validates_uniqueness_of   :login, :case_sensitive => false
  before_save  :encrypt_password
  after_create :create_sample_task

  # Authenticates a user by their login name and unencrypted password.  Returns the user or nil.
  def self.authenticate(login, password)
    u = find_by_login(login) # need to get the salt
    u && u.authenticated?(password) ? u : nil
  end

  # Encrypts some data with the salt.
  def self.encrypt(password, salt)
    Digest::SHA1.hexdigest("--#{salt}--#{password}--")
  end

  # Encrypts the password with the user salt
  def encrypt(password)
    self.class.encrypt(password, salt)
  end

  def authenticated?(password)
    crypted_password == encrypt(password)
  end

  def remember_token?
    remember_token_expires_at && Time.now.utc < remember_token_expires_at
  end

  # These create and unset the fields required for remembering users between browser closes
  def remember_me
    remember_me_for 2.weeks
  end

  def remember_me_for(time)
    remember_me_until time.from_now.utc
  end

  def remember_me_until(time)
    self.remember_token_expires_at = time
    self.remember_token            = encrypt("#{email}--#{remember_token_expires_at}")
    save(false)
  end

  def forget_me
    self.remember_token_expires_at = nil
    self.remember_token            = nil
    save(false)
  end

  def categories_values
    categories.collect(&:name).sort
  end

  protected
    # before filter
    def encrypt_password
      return if password.blank?
      self.salt = Digest::SHA1.hexdigest("--#{Time.now.to_s}--#{login}--") if new_record?
      self.crypted_password = encrypt(password)
    end

    def password_required?
      crypted_password.blank? || !password.blank?
    end

    def create_sample_task
      self.tasks.create :name     => 'Try Donebox and be more productive than David Allen himself',
                        :due_on   => Date.today,
                        :category => Category.find_or_create_by_name_and_user_id('donebox', self.id)
    end
end

redpajama_set_name: RedPajamaGithub


text:
(function($){

var gf_placeholder = function() {

	$('.gform_wrapper .gf-add-placeholder')
		.find('input, textarea').filter(function(i){
			var $field = $(this);

			if (this.nodeName == 'INPUT') {
				var type = this.type;
				return !(type == 'hidden' || type == 'file' || type == 'radio' || type == 'checkbox');
			}

			return true;
		})
		.each(function(){
			var $field = $(this);

			var id = this.id;
			var $labels = $('label[for=' + id + ']').hide();
			var label = $labels.last().text();

			if (label.length > 0 && label[ label.length-1 ] == '*') {
				label = label.substring(0, label.length-1) + ' *';
			}

			$field[0].setAttribute('placeholder', label);
		});

	var support = (!('placeholder' in document.createElement('input')));
	if ( support && jquery_placeholder_url )
		$.ajax({
			cache: true,
			dataType: 'script',
			url: jquery_placeholder_url,
			success: function() {
				$('input[placeholder], textarea[placeholder]').placeholder({
					blankSubmit: true
				});
			},
			type: 'get'
		});

    $('.gform_wrapper .gf-add-placeholder').find('select').filter(function(i){
        var $theSelect = $(this);

       $theSelect.each(function(){
           var elementID = this.id;
           var inIdFormat = "#" + elementID;
           var theLabel = $('label[for=' + elementID + ']').text();
           console.log('The id for this field is '+ elementID + ' the label for this field is ' + theLabel);
           $(inIdFormat).prepend("<option class='placeholder' selected disabled value=" + "'" + theLabel + "'" + ">" + theLabel + "</option>" );
            $('label[for=' + elementID + ']').hide();

       })
    });

};

$(document).ready(function(){
	gf_placeholder();
	$(document).bind('gform_post_render', gf_placeholder);
});

})(jQuery);


text: /* truncate64 is the same as truncate. */


text:
package main

import (
  "fmt"
  "github.com/nlopes/slack"
  "log"
)

// Produce slice of all emoji from messages within HistoryParameters
// on all public channels.
func ChannelMessageEmoji(api *slack.Client, params slack.HistoryParameters) []string {
  var reactions []string
  channels, err := api.GetChannels(true)

  if err != nil {
    log.Fatal(err)
  }

  for _, channel := range channels {
    fmt.Println(channel.Name)
    history, err := api.GetChannelHistory(channel.ID, params)

    if err != nil {
      log.Fatal(err)
    }

    for _, message := range history.Messages {
      fmt.Println(message.Text)
    }
  }
  return reactions
}
/*
func main() {
  var TOKEN string = os.Getenv("SLACK_TOKEN")
  api := slack.New(TOKEN)
  params := slack.HistoryParameters {"", "0", 100, false, false}

  channels, err := api.GetChannels(false)
  groups, err := api.GetGroups(true)

  var reactions []string

  if err != nil {
    fmt.Printf("%s\n", err)
    return
  }
  for _, group := range groups {
    fmt.Println(group.Name)
    history, err := api.GetGroupHistory(group.ID, params)
    if err != nil {
      fmt.Printf("%s\n", err)
    }
    for _, message := range history.Messages {
      if len(message.Reactions) != 0 {
        for _, reaction := range message.Reactions {
          reactions = append(reactions, reaction.Name)
        }
      }
    }
    for _, channel := range channels {
      if ! channel.IsArchived {
        fmt.Println(channel.Name)
        history, err := api.GetChannelHistory(channel.ID, params)
        if err != nil {
          fmt.Printf("%s\n", err)
          return
        }
        for _, message := range history.Messages {
          if len(message.Reactions) != 0 {
            for _, reaction := range message.Reactions {
              reactions = append(reactions, reaction.Name)
            }
          }
        }
      }
    }
  }
  return reactions
}
*/


text:
namespace mediapipe {
namespace api2 {
namespace {

using mediapipe::Detection;
using mediapipe::InferenceCalculatorOptions_Delegate;
using testing::ElementsAre;
using testing::EqualsProto;
using testing::proto::Approximately;

struct Param {
  std::string name;         // Appended to the test name.
  std::string impl_suffix;  // Expected InferenceCalculator backend.
  InferenceCalculatorOptions_Delegate delegate;
};

const std::vector<Param>& GetParams() {
  static auto all_params = [] {
    static std::vector<Param> p;
    p.push_back({"TfLite", "Cpu"});
    p.back().delegate.mutable_tflite();
#if TARGET_OS_IPHONE && !TARGET_IPHONE_SIMULATOR
    // Metal is not available on the iOS simulator.
    p.push_back({"Metal", "Metal"});
    p.back().delegate.mutable_gpu();
#endif                // TARGET_IPHONE_SIMULATOR
#if __ANDROID__ && 0  // Disabled for now since emulator can't go GLESv3
    p.push_back({"Gl", "Gl"});
    p.back().delegate.mutable_gpu();
    // This requires API level 27
    p.push_back({"NnApi", "Cpu"});
    p.back().delegate.mutable_nnapi();
#endif  // __ANDROID__
    p.push_back({"XnnPack", "Cpu"});
    p.back().delegate.mutable_xnnpack();
    return p;
  }();
  return all_params;
}

class InferenceCalculatorTest : public testing::TestWithParam<Param> {
 protected:
  void SetDelegateForParam(mediapipe::CalculatorGraphConfig_Node* node) {
    auto options_map = tool::MutableOptionsMap().Initialize(*node);
    auto options = options_map.Get<mediapipe::InferenceCalculatorOptions>();
    *options.mutable_delegate() = GetParam().delegate;
    options_map.Set(options);
  }
};

TEST_P(InferenceCalculatorTest, TestBackendSelection) {
  CalculatorGraphConfig config;
  auto node = config.add_node();
  node->set_calculator("InferenceCalculator");
  SetDelegateForParam(node);
  MP_ASSERT_OK(tool::ExpandSubgraphs(&config));
  EXPECT_EQ(config.node(0).calculator(),
            absl::StrCat("InferenceCalculator", GetParam().impl_suffix));
}

TEST_P(InferenceCalculatorTest, TestFaceDetection) {
  CalculatorGraphConfig config;
  ASSERT_TRUE(LoadTestGraph(
      &config, file::JoinPath(GetTestRootDir(),
                              "mediapipe/calculators/tensor/"
                              "testdata/face_detection_test.binarypb")));

  // Expand subgraphs to find any nested instances of InferenceCalculator.
  MP_ASSERT_OK(tool::ExpandSubgraphs(&config));
  int found = 0;
  for (auto& node : *config.mutable_node()) {
    // The InferenceCalculator subgraph itself will have expanded to a specific
    // implementation. Replace it.
    // TODO: make it possible to exclude it from expansion above.
    if (absl::StartsWith(node.calculator(), "InferenceCalculator")) {
      ++found;
      node.set_calculator("InferenceCalculator");
      SetDelegateForParam(&node);
    }
  }
  ASSERT_EQ(found, 1);

  std::vector<mediapipe::Packet> detection_packets;
  tool::AddVectorSink("detections", &config, &detection_packets);
  std::vector<mediapipe::Packet> rendering_packets;
  tool::AddVectorSink("rendering", &config, &rendering_packets);

  // Load test image.
  std::unique_ptr<ImageFrame> input_image = LoadTestPng(
      file::JoinPath(GetTestRootDir(), "mediapipe/objc/testdata/sergey.png"));
  ASSERT_THAT(input_image, testing::NotNull());

  std::unique_ptr<ImageFrame> expected_image =
      LoadTestPng(file::JoinPath(GetTestRootDir(),
                                 "mediapipe/calculators/tensor/"
                                 "testdata/face_detection_expected.png"));
  ASSERT_THAT(expected_image, testing::NotNull());

  std::string binary;
  Detection expected_detection;
  MP_ASSERT_OK(
      file::GetContents(file::JoinPath(GetTestRootDir(),
                                       "mediapipe/calculators/tensor/"
                                       "testdata/expected_detection.binarypb"),
                        &binary));
  expected_detection.ParseFromArray(binary.data(), binary.size());

  // Prepare test inputs.
  std::unordered_map<std::string, std::unique_ptr<ImageFrame>> input_streams;
  input_streams.insert(std::make_pair("image", std::move(input_image)));
  std::string output_stream = "rendering";

  // Test graph with relaxed color difference tolerance.
  // Compare with CPU generated image.
  Timestamp ts0 = Timestamp(0);
  TestGraphConfig(config, input_streams, output_stream, expected_image, {}, ts0,
                  2.0, 2.0, 1.0);

  ASSERT_EQ(detection_packets.size(), 1);
  std::vector<Detection> dets =
      detection_packets[0].Get<std::vector<Detection>>();
#if !defined(MEDIAPIPE_PROTO_LITE)
  // Approximately is not available with lite protos (b/178137094).
  constexpr float kEpison = 0.001;
  EXPECT_THAT(dets, ElementsAre(Approximately(EqualsProto(expected_detection),
                                              kEpison)));
#endif
}

INSTANTIATE_TEST_SUITE_P(Implementation, InferenceCalculatorTest,
                         testing::ValuesIn(GetParams()),
                         [](const testing::TestParamInfo<Param>& info) {
                           return info.param.name;
                         });

}  // namespace
}  // namespace api2
}  // namespace mediapipe


text:
package tianma.learn.ds.lineartable;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * 顺序存储式的循环队列(预留一个空闲单元)
 *
 * @author Tianma
 *
 */
public class MyArrayCircleQueue<E> implements MyQueue<E> {

	private static final int DEFAULT_CAPACITY = 5;
	private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

	private Object[] elementData;
	private int front; // 队首元素index
	private int rear; // 队尾元素的下一个位置

	public MyArrayCircleQueue() {
		this(DEFAULT_CAPACITY);
	}

	public MyArrayCircleQueue(int initialCapacity) {
		if (initialCapacity < 0)
			throw new IllegalArgumentException("Illegal capacity : " + initialCapacity);
		int capacity = Math.max(initialCapacity, DEFAULT_CAPACITY);
		elementData = new Object[capacity];
		front = rear = 0;
	}

	@Override
	public Iterator<E> iterator() {
		return new Iter();
	}

	private class Iter implements Iterator<E> {

		private int cursor;
		private int counter;

		public Iter() {
			cursor = front;
			counter = 0;
		}

		@Override
		public boolean hasNext() {
			return counter < size();
		}

		@Override
		public E next() {
			E value = elementData(cursor);
			cursor = (cursor + 1) % elementData.length;
			counter++;
			return value;
		}

	}

	@Override
	public void clear() {
		// 方案一,分段考虑
		// if (front < rear) {
		// // 分成一段, [front, rear - 1]
		// for (int i = front; i < rear; i++) {
		// elementData[i] = null;
		// }
		// } else if (front == rear) {
		// // isEmpty() = true
		// // do nothing
		// } else {
		// // 分为两段,[0, rear-1] [front, elementData.length - 1]
		// for (int i = 0; i < rear; i++) {
		// elementData[i] = null;
		// }
		// for (int i = front; i < elementData.length; i++) {
		// elementData[i] = null;
		// }
		// }
		// 方案二,亦或是这样
		for (int i = 0; i < size(); i++) {
			elementData[(i + front) % elementData.length] = null;
		}
		front = rear = 0;
	}

	@SuppressWarnings("unchecked")
	private E elementData(int index) {
		return (E) elementData[index];
	}

	@Override
	public E element() {
		if (isEmpty())
			throw new NoSuchElementException();
		return elementData(front);
	}

	@Override
	public boolean isEmpty() {
		return size() == 0;
	}

	@Override
	public boolean offer(E e) {
		ensureCapacity(size() + 1);
		elementData[rear] = e;
		rear = (rear + 1) % elementData.length;
		return true;
	}

	private void ensureCapacity(int minCapacity) {
		if (minCapacity >= elementData.length) {
			grow(minCapacity);
		}
	}

	private void grow(int minCapacity) {
		int oldCapacity = elementData.length;
		// + 优先级大于 >>
		int newCapacity = oldCapacity + (oldCapacity >> 1);
		newCapacity = Math.max(minCapacity, newCapacity);
		if (newCapacity > MAX_ARRAY_SIZE) {
			if (minCapacity < 0)
				throw new OutOfMemoryError();
			newCapacity = minCapacity > MAX_ARRAY_SIZE ? Integer.MAX_VALUE : MAX_ARRAY_SIZE;
		}

		Object[] newArray = new Object[newCapacity];
		if (front < rear) {
			// Array中的元素是连续一整块的
			System.arraycopy(elementData, front, newArray, 0, rear - front);
		} else {
			// Array中的元素是左边和右边各一部分 [0, rear -1], [front, elementData.length-1]
			int rightLen = oldCapacity - front;
			// int leftLen = oldCapacity - rightLen - 1;
			int leftLen = rear;
			System.arraycopy(elementData, front, newArray, 0, rightLen);
			System.arraycopy(elementData, 0, newArray, rightLen, leftLen);
		}
		elementData = newArray;
		front = 0;
		rear = oldCapacity - 1;
	}

	@Override
	public E remove() {
		if (isEmpty())
			throw new NoSuchElementException();
		E value = elementData(front);
		elementData[front] = null;
		front = (front + 1) % elementData.length;
		return value;
	}

	@Override
	public int size() {
		return (rear - front + elementData.length) % elementData.length;
	}

	@Override
	public String toString() {
		Iterator<E> it = iterator();
		if (!it.hasNext())
			return "[]";
		StringBuilder sb = new StringBuilder();
		sb.append('[');
		for (;;) {
			E e = it.next();
			sb.append(e == this ? "(this Collection)" : e);
			if (!it.hasNext())
				return sb.append(']').toString();
			sb.append(',').append(' ');
		}
	}

}


text:
"""
PyCOMPSs Util - Object properties
=================================
    Offers some functions that check properties about objects.
    For example, check if an object belongs to a module and so on.
"""

import os
import imp
import inspect

def get_defining_class(meth):
    """
    Given a method

    :param meth: Method to check its defining class
    :return: Class which meth belongs. None if not found.
    """
    if inspect.ismethod(meth):
        for cls in inspect.getmro(meth.__self__.__class__):
            if cls.__dict__.get(meth.__name__) is meth:
                return cls
    if inspect.isfunction(meth):
        return getattr(inspect.getmodule(meth),
                       meth.__qualname__.split('.<locals>',
                                               1)[0].rsplit('.', 1)[0])
    # Return not required since None would have been implicitly returned anyway
    return None

def get_module_name(path, file_name):
    """
    Get the module name considering its path and filename.

    Example: runcompss -d src/kmeans.py
             path = "test/kmeans.py"
             file_name = "kmeans" (without py extension)
             return mod_name = "test.kmeans"

    :param path: relative path until the file.py from where the runcompss has
                 been executed
    :param file_name: python file to be executed name
                      (without the py extension)
    :return: the module name
    """
    dirs = path.split(os.path.sep)
    mod_name = file_name
    i = len(dirs) - 1
    while i > 0:
        new_l = len(path) - (len(dirs[i]) + 1)
        path = path[0:new_l]
        if '__init__.py' in os.listdir(path):
            # directory is a package
            i -= 1
            mod_name = dirs[i] + '.' + mod_name
        else:
            break
    return mod_name

def get_top_decorator(code, decorator_keys):
    """
    Retrieves the decorator which is on top of the current task decorators
    stack.

    :param code: Tuple which contains the task code to analyse and the number
                 of lines of the code.
    :param decorator_keys: Typle which contains the available decorator keys
    :return: the decorator name in the form "pycompss.api.__name__"
    """
    # Code has two fields:
    # code[0] = the entire function code.
    # code[1] = the number of lines of the function code.
    func_code = code[0]
    decorators = [l.strip() for l in func_code if l.strip().startswith('@')]
    # Could be improved if it stops when the first line without @ is found,
    # but we have to be care if a decorator is commented (# before @)
    # The strip is due to the spaces that appear before functions definitions,
    # such as class methods.
    for dk in decorator_keys:
        for d in decorators:
            if d.startswith('@' + dk):
                return 'pycompss.api.' + dk.lower()  # each decorator __name__
    # If no decorator is found, the current decorator is the one to register
    return __name__

def get_wrapped_source(f):
    """
    Gets the text of the source code for the given function.

    :param f: Input function
    :return: Source
    """

    if hasattr(f, "__wrapped__"):
        # has __wrapped__, going deep
        return get_wrapped_source(f.__wrapped__)
    else:
        # Returning getsource
        try:
            source = inspect.getsource(f)
        except TypeError:
            # This is a numba jit declared task
            source = inspect.getsource(f.py_func)
        return source

def get_wrapped_sourcelines(f):
    """
    Gets a list of source lines and starting line number for the given function

    :param f: Input function
    :return: Source lines
    """
    if hasattr(f, '__wrapped__'):
        # has __wrapped__, apply the same function to the wrapped content
        return _get_wrapped_sourcelines(f.__wrapped__)
    else:
        # Returning getsourcelines
        try:
            sourcelines = inspect.getsourcelines(f)
        except TypeError:
            # This is a numba jit declared task
            sourcelines = inspect.getsourcelines(f.py_func)
        return sourcelines

def _get_wrapped_sourcelines(f):
    """
    [PRIVATE] Recursive function which gets a list of source lines and starting
    line number for the given function.

    :param f: Input function
    :return: Source lines
    """
    if hasattr(f, "__wrapped__"):
        # has __wrapped__, going deep
        return _get_wrapped_sourcelines(f.__wrapped__)
    else:
        # Returning getsourcelines
        try:
            sourcelines = inspect.getsourcelines(f)
        except TypeError:
            # This is a numba jit declared task
            sourcelines = inspect.getsourcelines(f.py_func)
        return sourcelines

def is_module_available(module_name):
    """
    Checks if a module is available in the current Python installation.

    :param module_name: Name of the module
    :return: Boolean -> True if the module is available, False otherwise
    """
    try:
        imp.find_module(module_name)
        return True
    except ImportError:
        return False

def is_basic_iterable(obj):
    """
    Checks if an object is a basic iterable. By basic iterable we want to
    mean objects that are iterable and from a basic type.

    :param obj: Object to be analysed
    :return: Boolean -> True if obj is a basic iterable (see list below),
                        False otherwise
    """
    return isinstance(obj, (list, tuple, bytearray, set, frozenset, dict))

def object_belongs_to_module(obj, module_name):
    """
    Checks if a given object belongs to a given module (or some sub-module).

    :param obj: Object to be analysed
    :param module_name: Name of the module we want to check
    :return: Boolean -> True if obj belongs to the given module,
                        False otherwise
    """
    return any(module_name == x for x in type(obj).__module__.split('.'))


text:
package com.google.javascript.jscomp;

import static com.google.common.base.Preconditions.checkNotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * An ordered set that moves values to the front when added (even if already contained) and which
 * allows for the marking of named points in time in the series from which point an accumulation of
 * all following values can be (efficiently) requested.
 */
// TODO(stalcup): save memory by unlinking events older than the oldest marked time.
final class Timeline<T> {

  private static class Event<T> {
    Event<?> nextEvent;
    Event<?> previousEvent;
    final T value;

    Event(T value) {
      checkNotNull(value);
      this.value = value;
    }
  }

  private static class Time {
    final String name;

    Time(String name) {
      checkNotNull(name);
      this.name = name;
    }

    @Override
    public boolean equals(Object anObject) {
      if (anObject instanceof Time) {
        return name.equals(((Time) anObject).name);
      }
      return false;
    }

    @Override
    public int hashCode() {
      return name.hashCode();
    }
  }

  private final Map<Time, Event<Time>> eventsByTime = new HashMap<>();
  private final Map<T, Event<T>> eventsByValue = new HashMap<>();
  // In practice headEvent is Event<Time> or Event<T>
  private Event<?> headEvent = new Event<>(new Time("-beginning-"));

  void add(T value) {
    addEvent(value, eventsByValue);
  }

  void remove(T value) {
    Event<T> event = eventsByValue.remove(value);

    // If the event already exists somewhere else in the history then...
    if (event != null) {
      // make the rest of the list not reference it...
      if (event.nextEvent != null) {
        event.nextEvent.previousEvent = event.previousEvent;
      } else {
        // if it was the head element then back the head reference up one node.
        headEvent = event.previousEvent;
      }
      event.previousEvent.nextEvent = event.nextEvent;

      // make it not reference the rest of the list.
      event.nextEvent = null;
      event.previousEvent = null;
    }
  }

  void mark(String timeName) {
    addEvent(new Time(timeName), eventsByTime);
  }

  @SuppressWarnings("unchecked")
  List<T> getSince(String timeName) {
    List<T> values = new ArrayList<>();

    Event<?> firstEvent = eventsByTime.get(new Time(timeName));
    if (firstEvent == null) {
      return null;
    }

    for (Event<?> event = firstEvent; event != null; event = event.nextEvent) {
      // If the event contains a user provided value, accumulate it.
      if (!(event.value instanceof Time)) {
        values.add((T) event.value);
      }
    }

    return values;
  }

  // In practice V is either T or Time.
  private <V> void addEvent(V value, Map<V, Event<V>> eventsByKey) {
    Event<V> event = eventsByKey.get(value);

    // If the event already exists and is already at the front, do nothing.
    if (this.headEvent == event) {
      return;
    }

    // If the event already exists somewhere else in the history then...
    if (event != null) {
      // cut it out of the linked list...
      event.previousEvent.nextEvent = event.nextEvent;
      event.nextEvent.previousEvent = event.previousEvent;
      event.nextEvent = null;
    } else {
      // Otherwise create and track an event for the given value.
      event = new Event<V>(value);
      eventsByKey.put(value, event);
    }

    // Regardless, stick the event at the front.
    event.previousEvent = this.headEvent;
    this.headEvent.nextEvent = event;
    this.headEvent = event;
  }
}


text:
using System;

namespace LibGit2Sharp
{
    /// <summary>
    /// Strategy used for blaming.
    /// </summary>
    public enum BlameStrategy
    {
        /// <summary>
        /// Track renames of the file, but no block movement.
        /// </summary>
        Default,

        // Track copies within the same file. (NOT SUPPORTED IN LIBGIT2 YET)
        //TrackCopiesSameFile,

        // Track movement across files within the same commit. (NOT SUPPORTED IN LIBGIT2 YET)
        //TrackCopiesSameCommitMoves,

        // Track copies across files within the same commit. (NOT SUPPORTED IN LIBGIT2 YET)
        //TrackCopiesSameCommitCopies,

        // Track copies across all files in all commits. (NOT SUPPORTED IN LIBGIT2 YET)
        //TrackCopiesAnyCommitCopies
    }

    /// <summary>
    /// Optional adjustments to the behavior of blame.
    /// </summary>
    public sealed class BlameOptions
    {
        /// <summary>
        /// Strategy to use to determine the blame for each line.
        /// The default is <see cref="BlameStrategy.Default"/>.
        /// </summary>
        public BlameStrategy Strategy { get; set; }

        /// <summary>
        /// Latest commitish to consider (the starting point).
        /// If null, blame will use HEAD.
        /// </summary>
        public object StartingAt { get; set; }

        /// <summary>
        /// Oldest commitish to consider (the stopping point).
        /// If null, blame will continue until all the lines have been blamed,
        /// or until a commit with no parents is reached.
        /// </summary>
        public object StoppingAt { get; set; }

        /// <summary>
        /// First text line in the file to blame (lines start at 1).
        /// If this is set to 0, the blame begins at line 1.
        /// </summary>
        public int MinLine { get; set; }

        /// <summary>
        /// Last text line in the file to blame (lines start at 1).
        /// If this is set to 0, blame ends with the last line in the file.
        /// </summary>
        public int MaxLine { get; set; }
    }
}


text:
package de.starwit.innovationlab.ejb;

import org.jboss.arquillian.junit.Arquillian;
import org.junit.Assert;
import org.junit.runner.RunWith;

import de.starwit.innovationlab.entity.IdeaEntity;

@RunWith(Arquillian.class)
public class IdeaServiceTest extends AbstractServiceTest<IdeaService, IdeaEntity> {

	@Override
	public void setService(IdeaService service) {
		this.service = service;
	}

	@Override
	public void testCreate() {
		entity = new IdeaEntity();
		entity = getService().create(entity);
		ID = entity.getId();
		Assert.assertNotNull(entity.getId());
		Assert.fail("Not yet implemented");

	}

	@Override
	public void testUpdate() {
		entity = getService().findById(ID);
		entity = getService().update(entity);
		Assert.fail("Not yet implemented");
	}

}


text:
package org.killbill.billing.server.notifications;

import java.io.IOException;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import org.killbill.billing.jaxrs.json.NotificationJson;
import org.killbill.billing.notification.plugin.api.ExtBusEvent;
import org.killbill.billing.tenant.api.TenantApiException;
import org.killbill.billing.tenant.api.TenantKV.TenantKey;
import org.killbill.billing.tenant.api.TenantUserApi;
import org.killbill.billing.util.callcontext.CallContextFactory;
import org.killbill.billing.util.callcontext.TenantContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ning.http.client.AsyncCompletionHandler;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.AsyncHttpClient.BoundRequestBuilder;
import com.ning.http.client.AsyncHttpClientConfig;
import com.ning.http.client.ListenableFuture;
import com.ning.http.client.Response;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.eventbus.AllowConcurrentEvents;
import com.google.common.eventbus.Subscribe;

public class PushNotificationListener {

    private static final Logger log = LoggerFactory.getLogger(PushNotificationListener.class);

    @VisibleForTesting
    public static final String HTTP_HEADER_CONTENT_TYPE = "Content-Type";
    @VisibleForTesting
    public static final String CONTENT_TYPE_JSON = "application/json; charset=UTF-8";

    private static final int TIMEOUT_NOTIFICATION = 15; // 15 seconds

    private final TenantUserApi tenantApi;
    private final CallContextFactory contextFactory;
    private final AsyncHttpClient httpClient;
    private final ObjectMapper mapper;

    @Inject
    public PushNotificationListener(final ObjectMapper mapper, final TenantUserApi tenantApi, final CallContextFactory contextFactory) {
        this.httpClient = new AsyncHttpClient(new AsyncHttpClientConfig.Builder().setRequestTimeout(TIMEOUT_NOTIFICATION * 1000).build());
        this.tenantApi = tenantApi;
        this.contextFactory = contextFactory;
        this.mapper = mapper;
    }

    @AllowConcurrentEvents
    @Subscribe
    public void triggerPushNotifications(final ExtBusEvent event) {
        final TenantContext context = contextFactory.createTenantContext(event.getTenantId());
        try {
            final List<String> callbacks = getCallbacksForTenant(context);
            if (callbacks.isEmpty()) {
                // Optimization - see https://github.com/killbill/killbill/issues/297
                return;
            }
            dispatchCallback(event.getTenantId(), event, callbacks);
        } catch (final TenantApiException e) {
            log.warn("Failed to retrieve push notification callback for tenant {}", event.getTenantId());
        } catch (final IOException e) {
            log.warn("Failed to retrieve push notification callback for tenant {}", event.getTenantId());
        }
    }

    private void dispatchCallback(final UUID tenantId, final ExtBusEvent event, final Iterable<String> callbacks) throws IOException {
        final NotificationJson notification = new NotificationJson(event);
        final String body = mapper.writeValueAsString(notification);
        for (final String cur : callbacks) {
            doPost(tenantId, cur, body, TIMEOUT_NOTIFICATION);
        }
    }

    private boolean doPost(final UUID tenantId, final String url, final String body, final int timeoutSec) {
        final BoundRequestBuilder builder = httpClient.preparePost(url);
        builder.setBody(body == null ? "{}" : body);
        builder.addHeader(HTTP_HEADER_CONTENT_TYPE, CONTENT_TYPE_JSON);

        final Response response;
        try {
            final ListenableFuture<Response> futureStatus =
                    builder.execute(new AsyncCompletionHandler<Response>() {
                        @Override
                        public Response onCompleted(final Response response) throws Exception {
                            return response;
                        }
                    });
            response = futureStatus.get(timeoutSec, TimeUnit.SECONDS);
        } catch (final Exception e) {
            log.warn(String.format("Failed to push notification %s for the tenant %s", url, tenantId), e);
            return false;
        }
        return response.getStatusCode() >= 200 && response.getStatusCode() < 300;
    }

    private List<String> getCallbacksForTenant(final TenantContext context) throws TenantApiException {
        return tenantApi.getTenantValuesForKey(TenantKey.PUSH_NOTIFICATION_CB.toString(), context);
    }
}


text:
class ActiveRecordSchemaScrapper
  VERSION = "0.9.0".freeze
end


text:
/* */
"use strict";
var _core = require("../core-js")["default"];
exports["default"] = _core.Object.assign || function(target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];
    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }
  return target;
};
exports.__esModule = true;


text:
namespace remoting {
namespace protocol {

extern const char kTestJid[];

class FakeAuthenticator;

class FakeSession : public Session {
 public:
  FakeSession();
  ~FakeSession() override;

  void SimulateConnection(FakeSession* peer);

  EventHandler* event_handler() { return event_handler_; }
  void set_error(ErrorCode error) { error_ = error; }
  bool is_closed() const { return closed_; }

  // Sets delay for signaling message deliver when connected to a peer.
  void set_signaling_delay(base::TimeDelta signaling_delay) {
    signaling_delay_ = signaling_delay;
  }

  // Session interface.
  void SetEventHandler(EventHandler* event_handler) override;
  ErrorCode error() override;
  const std::string& jid() override;
  const SessionConfig& config() override;
  void SetTransport(Transport* transport) override;
  void Close(ErrorCode error) override;
  void AddPlugin(SessionPlugin* plugin) override;

 private:
  // Callback provided to the |transport_|.
  void SendTransportInfo(std::unique_ptr<buzz::XmlElement> transport_info);

  // Called by the |peer_| to deliver incoming |transport_info|.
  void ProcessTransportInfo(std::unique_ptr<buzz::XmlElement> transport_info);

  EventHandler* event_handler_ = nullptr;
  std::unique_ptr<SessionConfig> config_;

  std::string jid_;

  std::unique_ptr<FakeAuthenticator> authenticator_;
  Transport* transport_;

  ErrorCode error_ = OK;
  bool closed_ = false;

  base::WeakPtr<FakeSession> peer_;
  base::TimeDelta signaling_delay_;

  base::WeakPtrFactory<FakeSession> weak_factory_;

  DISALLOW_COPY_AND_ASSIGN(FakeSession);
};

}  // namespace protocol
}  // namespace remoting

#endif  // REMOTING_PROTOCOL_FAKE_SESSION_H_


text:
FactoryBot.define do
  factory :taxon_count, class: TaxonCount do
    transient do
      # The taxon name for the taxon count entry.
      # Will be loaded or created using species (taxon_lineages) factory.
      taxon_name { nil }
      # NT or NR counts. NT will be used if defined. Otherwise, will use NR value.
      # Count type will be filled automaticlaly.
      nt { nil }
      nr { nil }
    end

    initialize_with do
      if taxon_name
        # If taxon name is passed, the taxa must exist
        taxon_lineage = TaxonLineage.find_by!(tax_name: taxon_name)
        # Unable to edit the original hash for some reason
        new(**attributes.dup.merge(tax_id: taxon_lineage.taxid,
                                   name: taxon_lineage.tax_name,
                                   genus_taxid: taxon_lineage.genus_taxid,
                                   superkingdom_taxid: taxon_lineage.superkingdom_taxid))

      else
        new(attributes)
      end
    end

    tax_level { 1 }
    count { nt || nr || 1 }
    count_type { nt ? "NT" : "NR" }
    percent_identity { 95.65 }
    alignment_length { 149.75 }
    e_value { 1.31 }
  end
end


text:
module SimpleCataloger

  class CmdServer < OptParseCommand::Command

    CliCat.register_command(self)

    def self.command
      'server'
    end

    def self.description
      'start server'
    end

    def self.usage
      "#{command}  <catalog name>\n" +
      "launch a webs server to browse the content of <catalog name>\n"
    end

    def defaults(options)
      options.force = false
      options
    end

    def option_parser(options)
      super(options)
    end

    def exec(main, options, rest)
      if rest.length < 1
        puts 'too few arguments'
        puts '-h to print help'
        return 0
      end

      catalog_name = rest[0]
      cat_opts     = { }

      #
      # option verbose
      #

#    if options.has_key?(:verbose)
#      if options[:verbose]
#        cat_opts[:verbose_level] = 1
#      end
#    end

      #
      # main
      #

      catalog = SimpleCataloger::CatOnSqlite.new(catalog_name).open
      SimpleCataloger::WebServer.run! :host => 'localhost', :port => 9091, :catalog => catalog

      0
    end

  end
end


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.labservices.implementation;

import com.azure.core.annotation.ServiceClient;
import com.azure.core.http.HttpHeaders;
import com.azure.core.http.HttpPipeline;
import com.azure.core.http.HttpResponse;
import com.azure.core.http.rest.Response;
import com.azure.core.management.AzureEnvironment;
import com.azure.core.management.exception.ManagementError;
import com.azure.core.management.exception.ManagementException;
import com.azure.core.management.polling.PollResult;
import com.azure.core.management.polling.PollerFactory;
import com.azure.core.util.Context;
import com.azure.core.util.CoreUtils;
import com.azure.core.util.logging.ClientLogger;
import com.azure.core.util.polling.AsyncPollResponse;
import com.azure.core.util.polling.LongRunningOperationStatus;
import com.azure.core.util.polling.PollerFlux;
import com.azure.core.util.serializer.SerializerAdapter;
import com.azure.core.util.serializer.SerializerEncoding;
import com.azure.resourcemanager.labservices.fluent.ImagesClient;
import com.azure.resourcemanager.labservices.fluent.LabPlansClient;
import com.azure.resourcemanager.labservices.fluent.LabServicesClient;
import com.azure.resourcemanager.labservices.fluent.LabsClient;
import com.azure.resourcemanager.labservices.fluent.OperationResultsClient;
import com.azure.resourcemanager.labservices.fluent.OperationsClient;
import com.azure.resourcemanager.labservices.fluent.SchedulesClient;
import com.azure.resourcemanager.labservices.fluent.SkusClient;
import com.azure.resourcemanager.labservices.fluent.UsagesClient;
import com.azure.resourcemanager.labservices.fluent.UsersClient;
import com.azure.resourcemanager.labservices.fluent.VirtualMachinesClient;
import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/** Initializes a new instance of the LabServicesClientImpl type. */
@ServiceClient(builder = LabServicesClientBuilder.class)
public final class LabServicesClientImpl implements LabServicesClient {
    /** The ID of the target subscription. */
    private final String subscriptionId;

    /**
     * Gets The ID of the target subscription.
     *
     * @return the subscriptionId value.
     */
    public String getSubscriptionId() {
        return this.subscriptionId;
    }

    /** server parameter. */
    private final String endpoint;

    /**
     * Gets server parameter.
     *
     * @return the endpoint value.
     */
    public String getEndpoint() {
        return this.endpoint;
    }

    /** Api Version. */
    private final String apiVersion;

    /**
     * Gets Api Version.
     *
     * @return the apiVersion value.
     */
    public String getApiVersion() {
        return this.apiVersion;
    }

    /** The HTTP pipeline to send requests through. */
    private final HttpPipeline httpPipeline;

    /**
     * Gets The HTTP pipeline to send requests through.
     *
     * @return the httpPipeline value.
     */
    public HttpPipeline getHttpPipeline() {
        return this.httpPipeline;
    }

    /** The serializer to serialize an object into a string. */
    private final SerializerAdapter serializerAdapter;

    /**
     * Gets The serializer to serialize an object into a string.
     *
     * @return the serializerAdapter value.
     */
    SerializerAdapter getSerializerAdapter() {
        return this.serializerAdapter;
    }

    /** The default poll interval for long-running operation. */
    private final Duration defaultPollInterval;

    /**
     * Gets The default poll interval for long-running operation.
     *
     * @return the defaultPollInterval value.
     */
    public Duration getDefaultPollInterval() {
        return this.defaultPollInterval;
    }

    /** The ImagesClient object to access its operations. */
    private final ImagesClient images;

    /**
     * Gets the ImagesClient object to access its operations.
     *
     * @return the ImagesClient object.
     */
    public ImagesClient getImages() {
        return this.images;
    }

    /** The LabPlansClient object to access its operations. */
    private final LabPlansClient labPlans;

    /**
     * Gets the LabPlansClient object to access its operations.
     *
     * @return the LabPlansClient object.
     */
    public LabPlansClient getLabPlans() {
        return this.labPlans;
    }

    /** The OperationsClient object to access its operations. */
    private final OperationsClient operations;

    /**
     * Gets the OperationsClient object to access its operations.
     *
     * @return the OperationsClient object.
     */
    public OperationsClient getOperations() {
        return this.operations;
    }

    /** The LabsClient object to access its operations. */
    private final LabsClient labs;

    /**
     * Gets the LabsClient object to access its operations.
     *
     * @return the LabsClient object.
     */
    public LabsClient getLabs() {
        return this.labs;
    }

    /** The OperationResultsClient object to access its operations. */
    private final OperationResultsClient operationResults;

    /**
     * Gets the OperationResultsClient object to access its operations.
     *
     * @return the OperationResultsClient object.
     */
    public OperationResultsClient getOperationResults() {
        return this.operationResults;
    }

    /** The SchedulesClient object to access its operations. */
    private final SchedulesClient schedules;

    /**
     * Gets the SchedulesClient object to access its operations.
     *
     * @return the SchedulesClient object.
     */
    public SchedulesClient getSchedules() {
        return this.schedules;
    }

    /** The SkusClient object to access its operations. */
    private final SkusClient skus;

    /**
     * Gets the SkusClient object to access its operations.
     *
     * @return the SkusClient object.
     */
    public SkusClient getSkus() {
        return this.skus;
    }

    /** The UsagesClient object to access its operations. */
    private final UsagesClient usages;

    /**
     * Gets the UsagesClient object to access its operations.
     *
     * @return the UsagesClient object.
     */
    public UsagesClient getUsages() {
        return this.usages;
    }

    /** The UsersClient object to access its operations. */
    private final UsersClient users;

    /**
     * Gets the UsersClient object to access its operations.
     *
     * @return the UsersClient object.
     */
    public UsersClient getUsers() {
        return this.users;
    }

    /** The VirtualMachinesClient object to access its operations. */
    private final VirtualMachinesClient virtualMachines;

    /**
     * Gets the VirtualMachinesClient object to access its operations.
     *
     * @return the VirtualMachinesClient object.
     */
    public VirtualMachinesClient getVirtualMachines() {
        return this.virtualMachines;
    }

    /**
     * Initializes an instance of LabServicesClient client.
     *
     * @param httpPipeline The HTTP pipeline to send requests through.
     * @param serializerAdapter The serializer to serialize an object into a string.
     * @param defaultPollInterval The default poll interval for long-running operation.
     * @param environment The Azure environment.
     * @param subscriptionId The ID of the target subscription.
     * @param endpoint server parameter.
     */
    LabServicesClientImpl(
        HttpPipeline httpPipeline,
        SerializerAdapter serializerAdapter,
        Duration defaultPollInterval,
        AzureEnvironment environment,
        String subscriptionId,
        String endpoint) {
        this.httpPipeline = httpPipeline;
        this.serializerAdapter = serializerAdapter;
        this.defaultPollInterval = defaultPollInterval;
        this.subscriptionId = subscriptionId;
        this.endpoint = endpoint;
        this.apiVersion = "2022-08-01";
        this.images = new ImagesClientImpl(this);
        this.labPlans = new LabPlansClientImpl(this);
        this.operations = new OperationsClientImpl(this);
        this.labs = new LabsClientImpl(this);
        this.operationResults = new OperationResultsClientImpl(this);
        this.schedules = new SchedulesClientImpl(this);
        this.skus = new SkusClientImpl(this);
        this.usages = new UsagesClientImpl(this);
        this.users = new UsersClientImpl(this);
        this.virtualMachines = new VirtualMachinesClientImpl(this);
    }

    /**
     * Gets default client context.
     *
     * @return the default client context.
     */
    public Context getContext() {
        return Context.NONE;
    }

    /**
     * Merges default client context with provided context.
     *
     * @param context the context to be merged with default client context.
     * @return the merged context.
     */
    public Context mergeContext(Context context) {
        return CoreUtils.mergeContexts(this.getContext(), context);
    }

    /**
     * Gets long running operation result.
     *
     * @param activationResponse the response of activation operation.
     * @param httpPipeline the http pipeline.
     * @param pollResultType type of poll result.
     * @param finalResultType type of final result.
     * @param context the context shared by all requests.
     * @param <T> type of poll result.
     * @param <U> type of final result.
     * @return poller flux for poll result and final result.
     */
    public <T, U> PollerFlux<PollResult<T>, U> getLroResult(
        Mono<Response<Flux<ByteBuffer>>> activationResponse,
        HttpPipeline httpPipeline,
        Type pollResultType,
        Type finalResultType,
        Context context) {
        return PollerFactory
            .create(
                serializerAdapter,
                httpPipeline,
                pollResultType,
                finalResultType,
                defaultPollInterval,
                activationResponse,
                context);
    }

    /**
     * Gets the final result, or an error, based on last async poll response.
     *
     * @param response the last async poll response.
     * @param <T> type of poll result.
     * @param <U> type of final result.
     * @return the final result, or an error.
     */
    public <T, U> Mono<U> getLroFinalResultOrError(AsyncPollResponse<PollResult<T>, U> response) {
        if (response.getStatus() != LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) {
            String errorMessage;
            ManagementError managementError = null;
            HttpResponse errorResponse = null;
            PollResult.Error lroError = response.getValue().getError();
            if (lroError != null) {
                errorResponse =
                    new HttpResponseImpl(
                        lroError.getResponseStatusCode(), lroError.getResponseHeaders(), lroError.getResponseBody());

                errorMessage = response.getValue().getError().getMessage();
                String errorBody = response.getValue().getError().getResponseBody();
                if (errorBody != null) {
                    // try to deserialize error body to ManagementError
                    try {
                        managementError =
                            this
                                .getSerializerAdapter()
                                .deserialize(errorBody, ManagementError.class, SerializerEncoding.JSON);
                        if (managementError.getCode() == null || managementError.getMessage() == null) {
                            managementError = null;
                        }
                    } catch (IOException | RuntimeException ioe) {
                        LOGGER.logThrowableAsWarning(ioe);
                    }
                }
            } else {
                // fallback to default error message
                errorMessage = "Long running operation failed.";
            }
            if (managementError == null) {
                // fallback to default ManagementError
                managementError = new ManagementError(response.getStatus().toString(), errorMessage);
            }
            return Mono.error(new ManagementException(errorMessage, errorResponse, managementError));
        } else {
            return response.getFinalResult();
        }
    }

    private static final class HttpResponseImpl extends HttpResponse {
        private final int statusCode;

        private final byte[] responseBody;

        private final HttpHeaders httpHeaders;

        HttpResponseImpl(int statusCode, HttpHeaders httpHeaders, String responseBody) {
            super(null);
            this.statusCode = statusCode;
            this.httpHeaders = httpHeaders;
            this.responseBody = responseBody == null ? null : responseBody.getBytes(StandardCharsets.UTF_8);
        }

        public int getStatusCode() {
            return statusCode;
        }

        public String getHeaderValue(String s) {
            return httpHeaders.getValue(s);
        }

        public HttpHeaders getHeaders() {
            return httpHeaders;
        }

        public Flux<ByteBuffer> getBody() {
            return Flux.just(ByteBuffer.wrap(responseBody));
        }

        public Mono<byte[]> getBodyAsByteArray() {
            return Mono.just(responseBody);
        }

        public Mono<String> getBodyAsString() {
            return Mono.just(new String(responseBody, StandardCharsets.UTF_8));
        }

        public Mono<String> getBodyAsString(Charset charset) {
            return Mono.just(new String(responseBody, charset));
        }
    }

    private static final ClientLogger LOGGER = new ClientLogger(LabServicesClientImpl.class);
}


text:
(function($) {
    $.fn.rescon = function(options) {
        var self = this;
        this.settings = $.extend({                                      // Default options
            complete : null,                                            // Function to run at the end.
            sizes : { "xs" : 0, "sm" : 768, "md" : 992, "lg" : 1200 },  // Default Bootstrap sizes.
            action : "run"                                              // Action: "run" to apply or "reset" to reset.
        }, options);

        var el = this;                                                  // The elements this was called on. This is a list.
        this.sizes = ["xs", "sm", "md", "lg"];                          // Pre-existing sizes. Do not delete those, you can change them with the settings.

        this.runRescon = function (index, element){

            /* SET MODE BASED ON WIDTH  */
            var currentMode = "md";
            var size = self.settings.sizes;
            var width = $(element).width();                             // get container width and set the current mode. Change these sizes to your own threshold.
            if(width >= size.xs && width < size.sm ){
                currentMode = "xs"
            }
            if(width >= size.sm && width < size.md ){
                currentMode = "sm"
            }
            if(width >= size.md && width < size.lg ){
                currentMode = "md"
            }
            if(width >= size.lg ){
                currentMode = "lg"
            }

            /* CREATE DATA ATTRIBUTES  */
            $(element).find('div').each(function(i, e){                 // Find child elements that may have these classes
                var classString = $(e).attr('class');                   // Get existing classes
                if(classString){                                        // If there is no class attribute don't bother
                    var rescon_exists = $(e).attr('data-rescon');       // Check if there is already data-rescon attribute
                    var visible_exists = $(e).attr('data-visible');     // Check if there is already data-visible attribute
                    if(!rescon_exists || !visible_exists) {             // If either one of them is missing continue
                        var rescon_string = "";                         // Set variable for collecting rescon classes
                        var visible_string = "";                        // Set variable for collecting visible classes
                        var classList = classString.split(' ');         // split classes into array
                        for (var i = 0; i < classList.length; i++) {    // loop through classes
                            var o = classList[i];
                            if (!rescon_exists) {                       // if data-rescon attribute does not exist, generate it
                                if (o.indexOf('col-') !== -1) {         // if this class includes 'col-' add it to rescon
                                    rescon_string += " " + o;
                                }
                            }
                            if (!visible_exists) {                      // check if data-visible attribute does not exits, generate it
                                if (o.indexOf('visible-') !== -1 || o.indexOf('hidden-') !== -1) {
                                    visible_string += " " + o;          // if this class includes visible att it to visible attribute
                                }
                            }
                        }
                        if(rescon_string){ $(e).attr('data-rescon', rescon_string.trim()) } ;     // set data-rescon attribute with classes we collected
                        if( visible_string) { $(e).attr('data-visible', visible_string.trim()) } ; // set visible attribute with classes we collected
                    }
                    var newclass = classString.replace(/\bcol-\S*/g, "").replace(/\bvisible-\S*/g, "").replace(/\hidden-\S*/g, "");      // Remove all classes related to column resizing so we are left with original classes
                    $(e).attr('class', newclass);                       // set visible attribute with classes we collected
                }

            })

            /* SET WIDTHS  */
            $(element).find('[data-rescon*="col-"]').each(function(i, e){  // Look at each column element within this div. You can change .find() to other selectors for more refined control.
                var dataString = $(e).attr('data-rescon');              // existing column related classes
                var newCols = "";                                       // the column classes we wil assign to this element
                var currentSize = self.sizes.indexOf(currentMode); // Index for the current size in the sizes table, returns 0, 1 etc.
                var dataList = dataString.split(" ");                   // split colum related classes into class names
                var before = self.recurseDown(currentSize, dataString); // If there are no column identifiers at this level move down, because bootstrap cascades upwards.
                if(before !== -1){                                      // before shouldn't be -1, this is to avoid errors.
                    for(var i = 0; i < dataList.length; i++) {          // Loop through colum relevant classes
                        var o = dataList[i];
                        if(o.indexOf(self.sizes[before])  !== -1 ){     // if this class is pertinent to current size add it to the new column related classes
                            newCols += " "+o;
                        }
                    }
                }
                if(newCols == ""){                                      // If we still don't have anything set default of 12 width
                    var newCols = "col-"+currentMode+"-"+"12";
                }
                $(e).addClass(newCols.trim());                          // Rewrite the classes for the element
            })

            /* SET VISIBILITY */
            $(element).find('[data-visible*="visible"],[data-visible*="hidden"]:not(".hidden-print")').each(function(i, e) {
                var dataString = $(e).attr('data-visible');             // Get existing visibility. This data attribute should have been generated already.
                var dataArray = dataString.split(" ");
                for(var i = 0; i < dataArray.length; i++) {             // Loop through visibility options to apply classes. In cases of conflict the last class applies.
                    var c = dataArray[i];
                    var classArray = c.split('-')
                    var classView =  classArray[1];                     // Get the size of the class i.e. xs, sm etc.
                    if (c.indexOf("visible-") !== -1) {
                        if(classView == currentMode) {                  // If the class applies to the current more show display option
                            if(classArray.length > 2){
                                var classDisplay =  classArray[3] ? classArray[2]+"-"+classArray[3] : classArray[2];
                                $(e).css("display", classDisplay);
                            } else {
                                $(e).css("display", "block");
                            }
                        }
                        else {
                            $(e).css("display", "none");                // If class doesn't apply to the current hide.
                        }
                    }
                    if (c.indexOf("hidden-") !== -1) {                  // If class is hidden do opposite.
                        if(classView == currentMode) {
                            if(classArray[0] === 'hidden'){
                                $(e).css("display", "none");
                            }
                        } else {
                            if(classArray[0] === 'hidden'){
                                $(e).css("display", "block");
                            }
                        }
                    }

                }
            });
        }

        this.recurseDown = function recur (index, dataString){          // Helper function to recursively check if lower widhts are set, for instance for mode md, check if sm or xs is set.
            if(index >= 0){
                if(dataString.indexOf(self.sizes[index])){
                    return index;
                } else {
                    recur(index-1, dataString)
                }
            } else {
                return -1;
            }
        }

        this.reset = function (index, element){                         // Clear the effects of the plugin by restoring to original classes.
            $(element).find('div[data-rescon*="col-"]').each(function(i, e){
                var dataString = $(e).attr('data-rescon');
                var classString = $(e).attr('class');
                var newclass = classString.replace(/^col.*/g, "");
                $(e).attr('class', newclass+" "+dataString);
            })
            el.find('[class*=visible],[class*=hidden]:not(".hidden-print")').each(function(i, e){
                $(this).addClass($(this).attr('data-visible'))
            })
        }

        if(this.settings.action === "run"){
            el.each(self.runRescon);
        }
        if(this.settings.action === "reset"){
            el.each(self.reset);
        }

        // Run the complete function if there is one
        if ( $.isFunction( self.settings.complete ) ) {
            self.settings.complete.call( this );
        }

        // Return the element so jquery can chain it
        return this;

    }

}(jQuery));


text:
/**
	@file GadgetAreaReload.cpp

	(c)2009 Palestar Inc
	@author Richard Lyle @date 6/13/2011 9:49:40 PM
*/

//---------------------------------------------------------------------------------------------------

#include "Debug/Assert.h"
#include "Math/Helpers.h"
#include "NounPlanet.h"
#include "GadgetAreaReload.h"
#include "GadgetWeapon.h"
#include "GadgetArmor.h"
#include "GadgetJumpDrive.h"
#include "GameContext.h"
#include "resource.h"
#include "StructureDefense.h"
#include "ShipPlatform.h"
#include "VerbGadgetOff.h"

//----------------------------------------------------------------------------

static Constant GADGET_REPAIR_POINTS( "GADGET_REPAIR_POINTS", 0.03f );
static Constant GADGET_REPAIR_MAX_DRONES( "GADGET_REPAIR_MAX_DRONES", 5 );

//----------------------------------------------------------------------------

IMPLEMENT_ABSTRACT_FACTORY( GadgetAreaReload, NounGadget );

BEGIN_ABSTRACT_PROPERTY_LIST( GadgetAreaReload, NounGadget );
	ADD_REPLICATED_PROPERTY( m_Flags, TICKS_PER_SECOND );
	ADD_REPLICATED_PROPERTY( m_Reloads, TICKS_PER_SECOND * 10 );
END_PROPERTY_LIST();

GadgetAreaReload::GadgetAreaReload() :
	m_nReloadTick( 0 ),
	m_nNextReloadIndex( 0 ),
	m_Reloads( 0 ),
	m_DroneCount( 0 )
{}

//----------------------------------------------------------------------------

void GadgetAreaReload::render( RenderContext & context, const Matrix33 & frame, const Vector3 & position )
{
	if ( useActive() )
	{
		Scene * pUseEffect = useEffect();
		if ( pUseEffect != NULL )
			pUseEffect->render( context, frame, position );
	}
}

//----------------------------------------------------------------------------

void GadgetAreaReload::setup()
{
	NounGadget::setup();
	m_Reloads = maxReloads();
}

void GadgetAreaReload::release()
{
	NounGadget::release();
	m_Reloading.release();
}

static int ReloadSort( GadgetAreaReload::NounCollision e1, GadgetAreaReload::NounCollision e2 )
{
	return ((int)e1.pNoun->key()) - ((int)e2.pNoun->key());
}

void GadgetAreaReload::simulate( dword nTick )
{
	if ( nTick >= m_nReloadTick && useActive() )
	{
		m_nReloadTick = nTick + (TICKS_PER_SECOND * calculateModifier( MT_RELOAD, true ));

		// get our parent ship (might not be attached to a ship)
		NounBody * pParent = parentBody();

		bool bValid = true;
		if ( WidgetCast<NounShip>( pParent )
			&& ((NounShip *)pParent)->testFlags( NounShip::FLAG_CLOAKED ) )
			bValid = false;			// can't reload while cloaked
		else if ( m_Reloads <= 0 || destroyed() )
			bValid = false;			// out of reloads or this device is destroyed

		if ( bValid )
		{
			m_Reloading.release();
			context()->proximityCheck( worldPosition(), reloadRange(), m_Reloading, CLASS_KEY(NounShip) );

			// sort collisions by ID, so we process them in the same order if possible..
			m_Reloading.qsort( ReloadSort );

			bool bReloadedShip = false;
			for(int i=0;i<m_Reloading.size() && !bReloadedShip;++i)
			{
				// reload the next ship...
				if ( m_nNextReloadIndex >= m_Reloading.size() )
					m_nNextReloadIndex = 0;

				if ( m_nNextReloadIndex < m_Reloading.size() )
				{
					NounShip * pReload = WidgetCast<NounShip>( m_Reloading[ m_nNextReloadIndex++ ].pNoun );
					if ( pReload != NULL && pReload != pParent
						&& pReload->isFriend( pParent )
						&& ( pReload->needReload( pParent ) || pReload->needRepair( pParent ) ) )
					{
						if ( pReload != pParent )
							pReload->reload( pParent );

						if ( pReload->isOutOfCombat() )
						{
							// increase repair by 50% if out of combat
							pReload->repair( pParent, gadgetRepairRate() * 1.5, true );
							pReload->repair( pParent, hullRepairRate() * 1.5, false );
						}
						else
						{
							pReload->repair( pParent, gadgetRepairRate(), true );
							pReload->repair( pParent, hullRepairRate(), false );
						}
						--m_Reloads;

						if ( isClient() && m_DroneCount < GADGET_REPAIR_MAX_DRONES )
						{
							m_DroneCount++;

							Vector3 offset( RandomVector( -1.0f, 1.0f ) );
							offset.normalize();

							NounDrone * pDrone = new NounDrone;
							pDrone->setHome( this, Vector3( 0.0f ) );
							pDrone->setPosition( worldPosition() );
							pDrone->setTarget( pReload, offset * pReload->radius() );
							pDrone->setSpeed( 10.0f );
							pDrone->setVelocity( 0.0f );
							pDrone->setDuration( TICKS_PER_SECOND * 2 );

							context()->attachNoun( pDrone );
						}

						if ( pReload != pParent )
							gameContext()->gameUser()->onRepair( pParent, GADGET_REPAIR_POINTS );

						// set flag to true, we only reload/repair one ship per second.. as more ships enter the AOI
						// the longer it will take to repair them.
						bReloadedShip = true;
					}
				}
			}
		}
	}

	NounGadget::simulate( nTick );
}

//----------------------------------------------------------------------------

NounGadget::Type GadgetAreaReload::type() const
{
	return DRONE_REPAIR;
}

dword GadgetAreaReload::hotkey() const
{
	return 'I';
}

CharString GadgetAreaReload::status() const
{
	return CharString().format("%d", reloads());
}

bool GadgetAreaReload::usable( Noun * pTarget, bool shift ) const
{
	if ( useActive() )
		return true;		// allow stop reloading
	if (! NounGadget::usable( pTarget, shift ) )
		return false;

	return true;
}

bool GadgetAreaReload::useActive() const
{
	return (flags() & FLAG_ACTIVE) != 0;
}

bool GadgetAreaReload::needReload( Noun * pWhom ) const
{
	if ( WidgetCast<NounPlanet>( pWhom ) != NULL
		|| WidgetCast<ShipPlatform>( pWhom ) )
	{
		return reloads() < maxReloads();
	}

	return false;
}

bool GadgetAreaReload::reload( Noun * pWhom )
{
	if ( WidgetCast<NounPlanet>( pWhom ) != NULL
		|| WidgetCast<ShipPlatform>( pWhom ) )
	{
		m_Reloads = Clamp( m_Reloads + 100, 0, maxReloads() );
		return m_Reloads < maxReloads();
	}

	// only planets can reload this device!
	return false;
}

void GadgetAreaReload::use( dword when, Noun * pTarget, bool shift)
{
	if ( useActive() )
		NounGadget::use( when, pTarget, shift );

	if ( isServer() )
	{
		// set the device active
		setFlags( FLAG_ACTIVE, !useActive() );
		message( CharString().format( "<color;ffffff>Engineering: %s %s.", name(), useActive() ? "Active" : "Inactive" ), true );
	}
}

bool GadgetAreaReload::updateLogic()
{
	if ( WidgetCast<NounShip>( parent() ) )
	{
		NounShip * pShip = (NounShip *)parent();

		bool bUsable = false;
		for(int i=0;i<pShip->contactCount() && !bUsable;++i)
		{
			NounShip * pContact = WidgetCast<NounShip>( pShip->contact(i) );
			if ( pContact == NULL )
				continue;		// not a ship
			if (! isFriend( pContact ) )
				continue;		// not a friend
			bUsable = pContact->needReload( pShip ) || pContact->needRepair( pShip );
		}

		if ( bUsable )
		{
			if (! useActive() )
				pShip->useGadget( this, NULL, false );
		}
		else
		{
			if ( useActive() )
				pShip->useGadget( this, NULL, false );
		}

		return true;
	}
	else if ( WidgetCast<StructureDefense>( parent() ) )
	{
		StructureDefense * pStructure = (StructureDefense *)parent();
		if ( pStructure->active() && !useActive() )
			pStructure->useGadget( NULL, this );		// turn on this device
		else if ( !pStructure->active() && useActive() )
			pStructure->useGadget( NULL, this );		// turn off this device

		return true;
	}

	return false;
}

//----------------------------------------------------------------------------

GadgetAreaReload * GadgetAreaReload::getGadgetReload( NounShip * pShip, bool bUsable /*= false*/ )
{
	for(int i=0;i<pShip->childCount();i++)
	{
		GadgetAreaReload * pReload = WidgetCast<GadgetAreaReload>( pShip->child(i) );
		if (! pReload )
			continue;
		if ( bUsable && (pReload->useActive() || pReload->reloads() <= 0) )
			continue;

		return pReload;
	}

	return NULL;
}

//----------------------------------------------------------------------------

void GadgetAreaReload::droneUpdate( NounDrone * pDrone )
{
	ASSERT( pDrone != NULL );
	ASSERT( pDrone->context() != NULL );

	float distance = (pDrone->worldPosition() - worldPosition()).magnitude();
	if ( context() == NULL || distance > (reloadRange() * 2) )
	{
		pDrone->setDetach();
		return;
	}
}

void GadgetAreaReload::droneAction( NounDrone * pDrone )
{}

void GadgetAreaReload::droneHome( NounDrone * pDrone )
{
	m_DroneCount--;
}

//---------------------------------------------------------------------------------------------------
//EOF


text:
Stored Procedures Used in T-SQL for eDiscovery, AKA Legal Discovery, dtSearching.

The following stored procedures were developed specificially to interface with Microsoft SQL Server 2008 R2 LAW PreDiscovery for use in Full-Text Searching using a Full-Text Index.

These T-SQL scripts are provided here for anyone's use under the MIT License. Please provide appropriate attribution if these scripts are used.

http://www.dtsearch.com/

<a href="http://lawpractice.lexisnexis.com/LAW-PreDiscovery-A?gclid=Cj0KEQjw0tCuBRDIjJ_Mlb6zzpQBEiQAyjCoBh8Zlw8WAoj20xIkA6RzRoq1Y0nCVdIxhvjjX6rFliAaAtmH8P8HAQ">LAW PreDiscovery<a/>


text:
package com.epam.ta.reportportal.core.integration.util.property;

import com.epam.ta.reportportal.entity.integration.IntegrationParams;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

import static java.util.Optional.ofNullable;

/**
 * @author Ihar Kahadouski
 */
public enum SauceLabsProperties {
	USERNAME("username"),
	ACCESS_TOKEN("accessToken");

	private String name;

	SauceLabsProperties(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public Optional<String> getParameter(Map<String, Object> parameters) {
		return ofNullable(parameters.get(this.name)).map(String::valueOf);
	}

	public void setParameter(IntegrationParams params, String value) {
		if (null == params.getParams()) {
			params.setParams(new HashMap<>());
		}
		params.getParams().put(this.name, value);
	}
}


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

using System;
using PetShop.Model;
using System.Collections.Generic;

namespace PetShop.IDAL
{
    /// <summary>
    /// Interface for the Category DAL
    /// </summary>
    public interface ICategory
    {
        /// <summary>
        /// Method to get all categories
        /// </summary>
        /// <returns>Interface to Model Collection Generic of categories</returns>
        IList<CategoryInfo> GetCategories();

        /// <summary>
        /// Get information on a specific category
        /// </summary>
        /// <param name="categoryId">Unique identifier for a category</param>
        /// <returns>Business Entity representing an category</returns>
        CategoryInfo GetCategory(string categoryId);
    }
}


text:
package org.elasticsearch.search.aggregations.bucket.range.geodistance;

import org.apache.lucene.index.AtomicReaderContext;
import org.apache.lucene.index.SortedNumericDocValues;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.geo.GeoDistance;
import org.elasticsearch.common.geo.GeoDistance.FixedSourceDistance;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.lucene.ReaderContextAware;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.fielddata.MultiGeoPointValues;
import org.elasticsearch.index.fielddata.SortedBinaryDocValues;
import org.elasticsearch.index.fielddata.SortedNumericDoubleValues;
import org.elasticsearch.search.SearchParseException;
import org.elasticsearch.search.aggregations.Aggregator;
import org.elasticsearch.search.aggregations.AggregatorFactory;
import org.elasticsearch.search.aggregations.bucket.range.InternalRange;
import org.elasticsearch.search.aggregations.bucket.range.RangeAggregator;
import org.elasticsearch.search.aggregations.bucket.range.RangeAggregator.Unmapped;
import org.elasticsearch.search.aggregations.support.*;
import org.elasticsearch.search.internal.SearchContext;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 *
 */
public class GeoDistanceParser implements Aggregator.Parser {

    private static final ParseField ORIGIN_FIELD = new ParseField("origin", "center", "point", "por");

    @Override
    public String type() {
        return InternalGeoDistance.TYPE.name();
    }

    private static String key(String key, double from, double to) {
        if (key != null) {
            return key;
        }
        StringBuilder sb = new StringBuilder();
        sb.append(from == 0 ? "*" : from);
        sb.append("-");
        sb.append(Double.isInfinite(to) ? "*" : to);
        return sb.toString();
    }

    @Override
    public AggregatorFactory parse(String aggregationName, XContentParser parser, SearchContext context) throws IOException {

        ValuesSourceParser<ValuesSource.GeoPoint> vsParser = ValuesSourceParser.geoPoint(aggregationName, InternalGeoDistance.TYPE, context).build();

        GeoPointParser geoPointParser = new GeoPointParser(aggregationName, InternalGeoDistance.TYPE, context, ORIGIN_FIELD);

        List<RangeAggregator.Range> ranges = null;
        DistanceUnit unit = DistanceUnit.DEFAULT;
        GeoDistance distanceType = GeoDistance.DEFAULT;
        boolean keyed = false;

        XContentParser.Token token;
        String currentFieldName = null;
        while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
            if (token == XContentParser.Token.FIELD_NAME) {
                currentFieldName = parser.currentName();
            } else if (vsParser.token(currentFieldName, token, parser)) {
                continue;
            } else if (geoPointParser.token(currentFieldName, token, parser)) {
                continue;
            } else if (token == XContentParser.Token.VALUE_STRING) {
                if ("unit".equals(currentFieldName)) {
                    unit = DistanceUnit.fromString(parser.text());
                } else if ("distance_type".equals(currentFieldName) || "distanceType".equals(currentFieldName)) {
                    distanceType = GeoDistance.fromString(parser.text());
                } else {
                    throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName + "]: [" + currentFieldName + "].");
                }
            } else if (token == XContentParser.Token.VALUE_BOOLEAN) {
                if ("keyed".equals(currentFieldName)) {
                    keyed = parser.booleanValue();
                } else {
                    throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName + "]: [" + currentFieldName + "].");
                }
            } else if (token == XContentParser.Token.START_ARRAY) {
                if ("ranges".equals(currentFieldName)) {
                    ranges = new ArrayList<>();
                    while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
                        String fromAsStr = null;
                        String toAsStr = null;
                        double from = 0.0;
                        double to = Double.POSITIVE_INFINITY;
                        String key = null;
                        String toOrFromOrKey = null;
                        while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
                            if (token == XContentParser.Token.FIELD_NAME) {
                                toOrFromOrKey = parser.currentName();
                            } else if (token == XContentParser.Token.VALUE_NUMBER) {
                                if ("from".equals(toOrFromOrKey)) {
                                    from = parser.doubleValue();
                                } else if ("to".equals(toOrFromOrKey)) {
                                    to = parser.doubleValue();
                                }
                            } else if (token == XContentParser.Token.VALUE_STRING) {
                                if ("key".equals(toOrFromOrKey)) {
                                    key = parser.text();
                                } else if ("from".equals(toOrFromOrKey)) {
                                    fromAsStr = parser.text();
                                } else if ("to".equals(toOrFromOrKey)) {
                                    toAsStr = parser.text();
                                }
                            }
                        }
                        ranges.add(new RangeAggregator.Range(key(key, from, to), from, fromAsStr, to, toAsStr));
                    }
                } else  {
                    throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName + "]: [" + currentFieldName + "].");
                }
            } else {
                throw new SearchParseException(context, "Unexpected token " + token + " in [" + aggregationName + "].");
            }
        }

        if (ranges == null) {
            throw new SearchParseException(context, "Missing [ranges] in geo_distance aggregator [" + aggregationName + "]");
        }

        GeoPoint origin = geoPointParser.geoPoint();
        if (origin == null) {
            throw new SearchParseException(context, "Missing [origin] in geo_distance aggregator [" + aggregationName + "]");
        }

        return new GeoDistanceFactory(aggregationName, vsParser.config(), InternalGeoDistance.FACTORY, origin, unit, distanceType, ranges, keyed);
    }

    private static class GeoDistanceFactory extends ValuesSourceAggregatorFactory<ValuesSource.GeoPoint, Map<String, Object>> {

        private final GeoPoint origin;
        private final DistanceUnit unit;
        private final GeoDistance distanceType;
        private final InternalRange.Factory rangeFactory;
        private final List<RangeAggregator.Range> ranges;
        private final boolean keyed;

        public GeoDistanceFactory(String name, ValuesSourceConfig<ValuesSource.GeoPoint> valueSourceConfig,
                                  InternalRange.Factory rangeFactory, GeoPoint origin, DistanceUnit unit, GeoDistance distanceType,
                                  List<RangeAggregator.Range> ranges, boolean keyed) {
            super(name, rangeFactory.type(), valueSourceConfig);
            this.origin = origin;
            this.unit = unit;
            this.distanceType = distanceType;
            this.rangeFactory = rangeFactory;
            this.ranges = ranges;
            this.keyed = keyed;
        }

        @Override
        protected Aggregator createUnmapped(AggregationContext aggregationContext, Aggregator parent, Map<String, Object> metaData) {
            return new Unmapped(name, ranges, keyed, null, aggregationContext, parent, rangeFactory, metaData);
        }

        @Override
        protected Aggregator create(final ValuesSource.GeoPoint valuesSource, long expectedBucketsCount, AggregationContext aggregationContext, Aggregator parent, Map<String, Object> metaData) {
            DistanceSource distanceSource = new DistanceSource(valuesSource, distanceType, origin, unit);
            aggregationContext.registerReaderContextAware(distanceSource);
            return new RangeAggregator(name, factories, distanceSource, null, rangeFactory, ranges, keyed, aggregationContext, parent, metaData);
        }

        private static class DistanceSource extends ValuesSource.Numeric implements ReaderContextAware {

            private final ValuesSource.GeoPoint source;
            private final GeoDistance distanceType;
            private final DistanceUnit unit;
            private final org.elasticsearch.common.geo.GeoPoint origin;
            private final MetaData metaData;
            private SortedNumericDoubleValues distanceValues;

            public DistanceSource(ValuesSource.GeoPoint source, GeoDistance distanceType, org.elasticsearch.common.geo.GeoPoint origin, DistanceUnit unit) {
                this.source = source;
                // even if the geo points are unique, there's no guarantee the distances are
                this.metaData = MetaData.builder(source.metaData()).uniqueness(MetaData.Uniqueness.UNKNOWN).build();
                this.distanceType = distanceType;
                this.unit = unit;
                this.origin = origin;
            }

            @Override
            public void setNextReader(AtomicReaderContext reader) {
                final MultiGeoPointValues geoValues = source.geoPointValues();
                final FixedSourceDistance distance = distanceType.fixedSourceDistance(origin.getLat(), origin.getLon(), unit);
                distanceValues = GeoDistance.distanceValues(geoValues, distance);
            }

            @Override
            public MetaData metaData() {
                return metaData;
            }

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

            @Override
            public SortedNumericDocValues longValues() {
                throw new UnsupportedOperationException();
            }

            @Override
            public SortedNumericDoubleValues doubleValues() {
                return distanceValues;
            }

            @Override
            public SortedBinaryDocValues bytesValues() {
                throw new UnsupportedOperationException();
            }

        }

    }

}


text:
package main

import (
	"fmt"
	"io/ioutil"
	"os"
	"strconv"
	"strings"
)

func main() {
	pwd, _ := os.Getwd()
	file, err := ioutil.ReadFile(pwd + "/" + os.Args[1])

	if err != nil {
		fmt.Println(err)
		return
	}

	input := string(file)
	input = input[:len(input)-1]
	results := getResults(input)
	printResults(results)
}

func printResults(results []int) {
	for i := 0; i < len(results); i++ {
		fmt.Printf("Case #%v: %v\n", i+1, results[i])
	}
}

func getResults(input string) []int {
	lines := strings.Split(input, "\n")
	var results []int

	for i := 1; i < len(lines); i++ {
		testCase := lines[i]
		results = append(results, getTestCaseResult(testCase))
	}

	return results
}

func getTestCaseResult(testCase string) int {
	maxShyness, _ := strconv.Atoi(strings.Split(testCase, " ")[0])
	audience := strings.Split(strings.Split(testCase, " ")[1], "")

	standingPeopleCount := 0
	friendsCount := 0

	for shynessLevel := 0; shynessLevel <= maxShyness; shynessLevel++ {
		peopleCount, _ := strconv.Atoi(audience[shynessLevel])

		if shynessLevel > standingPeopleCount {
			friendsNeeded := shynessLevel - standingPeopleCount
			friendsCount += friendsNeeded
			standingPeopleCount += friendsNeeded + peopleCount
		} else {
			standingPeopleCount += peopleCount
		}
	}

	return friendsCount
}


text:
Sign In

                                            <form class="form-horizontal" role="form">

                                                    <input type="text" class="form-control" placeholder="Your Email" id='inputEmail2' value=''>

                                                    <input type="password" class="form-control" placeholder="Your Password" id='inputpw2' value=''>

                                <input type="checkbox" value="" checked>
                                 Remember me

                                                        <button type="submit" ng-click="ok()"  class="btn btn-primary">Sign in</button>

                                            </form>


text:
<resources>
    <string name="app_name">amadeus</string>
</resources>


text:
import os
import sys
import time
import math

import numpy as np

import theano
import theano.tensor as T
import theano.tensor.shared_randomstreams

from util import datapy, color, paramgraphics
from optimization import optimizer
from layer import FullyConnected, nonlinearity
from layer import GaussianHidden, NoParamsBernoulliVisiable,Pegasos
from layer import ConvMaxPool, UnpoolConvNon

def c_6layer_mnist_imputation(seed=0,
             pertub_type=3, pertub_prob=6, pertub_prob1=14,
             predir=None, n_batch=144,
             dataset='mnist.pkl.gz', batch_size=500):

    """
    Missing data imputation
    """
    #cp->cd->cpd->cd->c
    nkerns=[32, 32, 64, 64, 64]
    drops=[0, 0, 0, 0, 0, 1]
    #skerns=[5, 3, 3, 3, 3]
    #pools=[2, 1, 1, 2, 1]
    #modes=['same']*5
    n_hidden=[500, 50]
    drop_inverses=[1,]
    # 28->12->12->5->5/5*5*64->500->50->500->5*5*64/5->5->12->12->28

    if dataset=='mnist.pkl.gz':
        dim_input=(28, 28)
        colorImg=False

    train_set_x, test_set_x, test_set_x_pertub, pertub_label, pertub_number = datapy.load_pertub_data(dirs='data_imputation/', pertub_type=pertub_type, pertub_prob=pertub_prob,pertub_prob1=pertub_prob1)

    datasets = datapy.load_data_gpu(dataset, have_matrix=True)

    _, train_set_y, train_y_matrix = datasets[0]
    valid_set_x, valid_set_y, valid_y_matrix = datasets[1]
    _, test_set_y, test_y_matrix = datasets[2]

    # compute number of minibatches for training, validation and testing
    n_test_batches = test_set_x.get_value(borrow=True).shape[0] / batch_size
    n_valid_batches = valid_set_x.get_value(borrow=True).shape[0] / batch_size
    n_train_batches = train_set_x.get_value(borrow=True).shape[0] / batch_size

    ######################
    # BUILD ACTUAL MODEL #
    ######################
    print '... building the model'

    # allocate symbolic variables for the data
    index = T.lscalar()  # index to a [mini]batch
    x = T.matrix('x')
    #x_pertub = T.matrix('x_pertub')  # the data is presented as rasterized images
    #p_label = T.matrix('p_label')

    y = T.ivector('y')  # the labels are presented as 1D vector of
                        # [int] labels
    y_matrix = T.imatrix('y_matrix')

    drop = T.iscalar('drop')
    drop_inverse = T.iscalar('drop_inverse')

    activation = nonlinearity.relu

    rng = np.random.RandomState(seed)
    rng_share = theano.tensor.shared_randomstreams.RandomStreams(0)

    input_x = x.reshape((batch_size, 1, 28, 28))

    recg_layer = []
    cnn_output = []

    #1
    recg_layer.append(ConvMaxPool.ConvMaxPool(
            rng,
            image_shape=(batch_size, 1, 28, 28),
            filter_shape=(nkerns[0], 1, 5, 5),
            poolsize=(2, 2),
            border_mode='valid',
            activation=activation
        ))
    if drops[0]==1:
        cnn_output.append(recg_layer[-1].drop_output(input=input_x, drop=drop, rng=rng_share))
    else:
        cnn_output.append(recg_layer[-1].output(input=input_x))

    #2
    recg_layer.append(ConvMaxPool.ConvMaxPool(
        rng,
        image_shape=(batch_size, nkerns[0], 12, 12),
        filter_shape=(nkerns[1], nkerns[0], 3, 3),
        poolsize=(1, 1),
        border_mode='same',
        activation=activation
    ))
    if drops[1]==1:
        cnn_output.append(recg_layer[-1].drop_output(cnn_output[-1], drop=drop, rng=rng_share))
    else:
        cnn_output.append(recg_layer[-1].output(cnn_output[-1]))

    #3
    recg_layer.append(ConvMaxPool.ConvMaxPool(
        rng,
        image_shape=(batch_size, nkerns[1], 12, 12),
        filter_shape=(nkerns[2], nkerns[1], 3, 3),
        poolsize=(2, 2),
        border_mode='valid',
        activation=activation
    ))
    if drops[2]==1:
        cnn_output.append(recg_layer[-1].drop_output(cnn_output[-1], drop=drop, rng=rng_share))
    else:
        cnn_output.append(recg_layer[-1].output(cnn_output[-1]))

    #4
    recg_layer.append(ConvMaxPool.ConvMaxPool(
        rng,
        image_shape=(batch_size, nkerns[2], 5, 5),
        filter_shape=(nkerns[3], nkerns[2], 3, 3),
        poolsize=(1, 1),
        border_mode='same',
        activation=activation
    ))
    if drops[3]==1:
        cnn_output.append(recg_layer[-1].drop_output(cnn_output[-1], drop=drop, rng=rng_share))
    else:
        cnn_output.append(recg_layer[-1].output(cnn_output[-1]))
    #5
    recg_layer.append(ConvMaxPool.ConvMaxPool(
        rng,
        image_shape=(batch_size, nkerns[3], 5, 5),
        filter_shape=(nkerns[4], nkerns[3], 3, 3),
        poolsize=(1, 1),
        border_mode='same',
        activation=activation
    ))
    if drops[4]==1:
        cnn_output.append(recg_layer[-1].drop_output(cnn_output[-1], drop=drop, rng=rng_share))
    else:
        cnn_output.append(recg_layer[-1].output(cnn_output[-1]))

    mlp_input = cnn_output[-1].flatten(2)

    recg_layer.append(FullyConnected.FullyConnected(
        rng=rng,
        n_in=nkerns[4] * 5 * 5,
        n_out=500,
        activation=activation
    ))

    feature = recg_layer[-1].drop_output(mlp_input, drop=drop, rng=rng_share)

    # classify the values of the fully-connected sigmoidal layer
    classifier = Pegasos.Pegasos(input=feature, rng=rng, n_in=500, n_out=10, weight_decay=0, loss=1)

    # the cost we minimize during training is the NLL of the model
    cost = classifier.hinge_loss(10, y, y_matrix) * batch_size
    weight_decay=1.0/n_train_batches

    # create a list of all model parameters to be fit by gradient descent
    params=[]
    for r in recg_layer:
        params+=r.params
    params += classifier.params

    # create a list of gradients for all model parameters
    grads = T.grad(cost, params)
    learning_rate = 3e-4
    l_r = theano.shared(np.asarray(learning_rate, dtype=np.float32))
    get_optimizer = optimizer.get_adam_optimizer_min(learning_rate=l_r, decay1 = 0.1, decay2 = 0.001, weight_decay=weight_decay)
    updates = get_optimizer(params,grads)

    '''
    Save parameters and activations
    '''

    parameters = theano.function(
        inputs=[],
        outputs=params,
    )

    # create a function to compute the mistakes that are made by the model
    test_model = theano.function(
        inputs=[index],
        outputs=classifier.errors(y),
        givens={
            x: test_set_x[index * batch_size: (index + 1) * batch_size],
            y: test_set_y[index * batch_size: (index + 1) * batch_size],
            #y_matrix: test_y_matrix[index * batch_size: (index + 1) * batch_size],
            drop: np.cast['int32'](0)
        }
    )

    test_pertub_model = theano.function(
        inputs=[index],
        outputs=classifier.errors(y),
        givens={
            x: test_set_x_pertub[index * batch_size: (index + 1) * batch_size],
            y: test_set_y[index * batch_size: (index + 1) * batch_size],
            #y_matrix: test_y_matrix[index * batch_size: (index + 1) * batch_size],
            drop: np.cast['int32'](0)
        }
    )

    validate_model = theano.function(
        inputs=[index],
        outputs=classifier.errors(y),
        givens={
            x: valid_set_x[index * batch_size: (index + 1) * batch_size],
            #y_matrix: valid_y_matrix[index * batch_size: (index + 1) * batch_size],
            y: valid_set_y[index * batch_size: (index + 1) * batch_size],
            drop: np.cast['int32'](0)
        }
    )

    ##################
    # Pretrain MODEL #
    ##################

    model_epoch = 250
    if os.environ.has_key('model_epoch'):
        model_epoch = int(os.environ['model_epoch'])
    if predir is not None:
        color.printBlue('... setting parameters')
        color.printBlue(predir)
        if model_epoch == -1:
            pre_train = np.load(predir+'best-model.npz')
        else:
            pre_train = np.load(predir+'model-'+str(model_epoch)+'.npz')
        pre_train = pre_train['model']
        for (para, pre) in zip(params, pre_train):
            para.set_value(pre)
    else:
        exit()

    ###############
    # TRAIN MODEL #
    ###############
    valid_losses = [validate_model(i) for i in xrange(n_valid_batches)]
    valid_score = np.mean(valid_losses)

    test_losses = [test_model(i) for i in xrange(n_test_batches)]
    test_score = np.mean(test_losses)

    test_losses_pertub = [test_pertub_model(i) for i in xrange(n_test_batches)]
    test_score_pertub = np.mean(test_losses_pertub)

    print valid_score, test_score, test_score_pertub

if __name__ == '__main__':

    pertub_type = int(sys.argv[1])
    pertub_prob = float(sys.argv[2])
    pertub_prob1 = float(sys.argv[3])
    predir = sys.argv[4]
    c_6layer_mnist_imputation(pertub_type=pertub_type, pertub_prob=pertub_prob, pertub_prob1=pertub_prob1, predir=predir)


text:
class Version04UpdateImpressionsTable < ActiveRecord::Migration[4.2]
  def self.up
    add_column :impressions, :referrer, :string
  end

  def self.down
    remove_column :impressions, :referrer
  end
end


text:
  class PMActivity < Android::App::Activity

    EXTRA_FRAGMENT_CLASS = "fragment_class"
    EXTRA_FRAGMENT_ARGUMENTS = "fragment_arguments"

    def onCreate(saved_instance_state)
      super

      mp "PMActivity onCreate", debugging_only: true

      on_create(saved_instance_state)
      PMApplication.current_application.context
    end

    def on_create(saved_instance_state)
      mp "PMActivity on_create", debugging_only: true
    end

    # These 2 methods are needed to pass on to inherited activities
    def onActivityResult(request_code, result_code, data)
      on_activity_result(request_code, result_code, data)
    end

    def on_activity_result(request_code, result_code, data)
      # Abstract
    end

    def onStart
      super
      on_start if respond_to?(:on_start)
    end

    def onNewIntent(intent)
      on_new_intent(intent) if respond_to?(:on_new_intent)
    end

    def onResume
      super
      on_resume
      PMApplication.current_application.current_activity = self
    end
    def on_resume; end

    def onPause
      clear_references
      super
    end

    def onDestroy
      on_destroy
      clear_references
      super
    end
    def on_destroy; end

    def clear_references
    end

    def onCreateOptionsMenu(menu)
      on_create_menu(menu)
    end
    def on_create_menu(_); end

    def onOptionsItemSelected(item)
      home_const = 16908332 # R.id.home
      return onBackPressed if item.getItemId == home_const
      # Don't call super if method returns false
      return true if on_options_item_selected(item) == false
      super
    end

    def onBackPressed
      super
      finish if fragmentManager.getBackStackEntryCount == 0
    end

    def open(screen, options={})
      find.screen.open screen, options
    end

    def close(options={})
      find.screen.close options
    end

    def set_content layout_xml
      layout_id = find.resource.layout(layout_xml)
      setContentView(layout_id)
    end

  end

#end