text:
require 'optparse'
include Java
import org.apache.hadoop.hbase.HConstants
import org.apache.hadoop.hbase.HBaseConfiguration
import org.apache.hadoop.hbase.client.HBaseAdmin
import org.apache.hadoop.hbase.client.Get
import org.apache.hadoop.hbase.client.Scan
import org.apache.hadoop.hbase.client.HTable
import org.apache.hadoop.hbase.client.HConnectionManager
import org.apache.hadoop.hbase.filter.FirstKeyOnlyFilter;
import org.apache.hadoop.hbase.util.Bytes
import org.apache.hadoop.hbase.util.Writables
import org.apache.hadoop.conf.Configuration
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.apache.hadoop.hbase.protobuf.ProtobufUtil
import org.apache.hadoop.hbase.ServerName
import org.apache.hadoop.hbase.HRegionInfo

# Name of this script
NAME = "region_mover"

# Get meta table reference
def getMetaTable(config)
  # Keep meta reference in ruby global
  if not $META
    $META = HTable.new(config, HConstants::META_TABLE_NAME)
  end
  return $META
end

# Get table instance.
# Maintains cache of table instances.
def getTable(config, name)
  # Keep dictionary of tables in ruby global
  if not $TABLES
    $TABLES = {}
  end
  key = Bytes.toString(name)
  if not $TABLES[key]
    $TABLES[key] = HTable.new(config, name)
  end
  return $TABLES[key]
end

# Returns true if passed region is still on 'original' when we look at .META.
def isSameServer(admin, r, original)
  server = getServerNameForRegion(admin, r)
  return false unless server
  return true unless original
  return server == original
end

class RubyAbortable
  include org.apache.hadoop.hbase.Abortable
  def abort(why, e)
    puts "ABORTED! why=" + why + ", e=" + e.to_s
  end
end

# Get servername that is up in .META.; this is hostname + port + startcode comma-delimited.
# Can return nil
def getServerNameForRegion(admin, r)
  if r.isMetaRegion()
    # Hack
    tracker = org.apache.hadoop.hbase.zookeeper.MetaRegionTracker.new(admin.getConnection().getZooKeeperWatcher(), RubyAbortable.new())
    tracker.start()
    while not tracker.isLocationAvailable()
      sleep 0.1
    end
    # Make a fake servername by appending ','
    metaServer = tracker.getMetaRegionLocation().toString() + ","
    tracker.stop()
    return metaServer
  end
  table = nil
  table = getMetaTable(admin.getConfiguration())
  g = Get.new(r.getRegionName())
  g.addColumn(HConstants::CATALOG_FAMILY, HConstants::SERVER_QUALIFIER)
  g.addColumn(HConstants::CATALOG_FAMILY, HConstants::STARTCODE_QUALIFIER)
  result = table.get(g)
  server = result.getValue(HConstants::CATALOG_FAMILY, HConstants::SERVER_QUALIFIER)
  startcode = result.getValue(HConstants::CATALOG_FAMILY, HConstants::STARTCODE_QUALIFIER)
  return nil unless server
  return java.lang.String.new(Bytes.toString(server)).replaceFirst(":", ",")  + "," + Bytes.toLong(startcode).to_s
end

# Trys to scan a row from passed region
# Throws exception if can't
def isSuccessfulScan(admin, r)
  scan = Scan.new(r.getStartKey())
  scan.setBatch(1)
  scan.setCaching(1)
  scan.setFilter(FirstKeyOnlyFilter.new())
  table = getTable(admin.getConfiguration(), r.getTableName())
  scanner = table.getScanner(scan)
  begin
    results = scanner.next()
    # We might scan into next region, this might be an empty table.
    # But if no exception, presume scanning is working.
  ensure
    scanner.close()
    table.close()
  end
end

# Check region has moved successful and is indeed hosted on another server
# Wait until that is the case.
def move(admin, r, newServer, original)
  # Now move it. Do it in a loop so can retry if fail.  Have seen issue where
  # we tried move region but failed and retry put it back on old location;
  # retry in this case.
  retries = admin.getConfiguration.getInt("hbase.move.retries.max", 5)
  count = 0
  same = true
  while count < retries and same
    if count > 0
      $LOG.info("Retry " + count.to_s + " of maximum " + retries.to_s)
    end
    count = count + 1
    begin
      admin.move(Bytes.toBytes(r.getEncodedName()), Bytes.toBytes(newServer))
    rescue java.lang.reflect.UndeclaredThrowableException => e
      $LOG.info("Exception moving "  + r.getEncodedName() +
        "; split/moved? Continuing: " + e)
      return
    end
    # Wait till its up on new server before moving on
    maxWaitInSeconds = admin.getConfiguration.getInt("hbase.move.wait.max", 60)
    maxWait = Time.now + maxWaitInSeconds
    while Time.now < maxWait
      same = isSameServer(admin, r, original)
      break unless same
      sleep 0.1
    end
  end
  raise RuntimeError, "Region stuck on #{original}, newserver=#{newServer}" if same
  # Assert can Scan from new location.
  isSuccessfulScan(admin, r)
end

# Return the hostname portion of a servername (all up to first ',')
def getHostnamePortFromServerName(serverName)
  parts = serverName.split(',')
  return parts[0] + ":" + parts[1]
end

# Return the hostname:port out of a servername (all up to first ',')
def getHostnameFromServerName(serverName)
  return serverName.split(',')[0]
end

# Return array of servernames where servername is hostname+port+startcode
# comma-delimited
def getServers(admin)
  serverInfos = admin.getClusterStatus().getServerInfo()
  servers = []
  for server in serverInfos
    servers << server.getServerName()
  end
  return servers
end

# Remove the servername whose hostname portion matches from the passed
# array of servers.  Returns as side-effect the servername removed.
def stripServer(servers, hostname)
  count = servers.length
  servername = nil
  for server in servers
    if getHostnameFromServerName(server) == hostname
      servername = servers.delete(server)
    end
  end
  # Check server to exclude is actually present
  raise RuntimeError, "Server %s not online" % hostname unless servers.length < count
  return servername
end

# Returns a new serverlist that excludes the servername whose hostname portion
# matches from the passed array of servers.
def stripExcludes(servers, excludefile)
  excludes = readExcludes(excludefile)
  servers =  servers.find_all{|server| !excludes.contains(getHostnameFromServerName(server)) }
  # return updated servers list
  return servers
end

# Return servername that matches passed hostname
def getServerName(servers, hostname)
  servername = nil
  for server in servers
    if getHostnameFromServerName(server) == hostname
      servername = server
      break
    end
  end
  raise ArgumentError, "Server %s not online" % hostname unless servername
  return servername
end

# Create a logger and disable the DEBUG-level annoying client logging
def configureLogging(options)
  apacheLogger = LogFactory.getLog(NAME)
  # Configure log4j to not spew so much
  unless (options[:debug])
    logger = org.apache.log4j.Logger.getLogger("org.apache.hadoop.hbase.client")
    logger.setLevel(org.apache.log4j.Level::INFO)
  end
  return apacheLogger
end

# Get configuration instance
def getConfiguration()
  config = HBaseConfiguration.create()
  # No prefetching on .META.
  config.setInt("hbase.client.prefetch.limit", 1)
  # Make a config that retries at short intervals many times
  config.setInt("hbase.client.pause", 500)
  config.setInt("hbase.client.retries.number", 100)
  return config
end

# Now get list of regions on targetServer
def getRegions(config, servername)
  connection = HConnectionManager::getConnection(config);
  return ProtobufUtil::getOnlineRegions(connection.getAdmin(ServerName.new(servername)));
end

def deleteFile(filename)
  f = java.io.File.new(filename)
  f.delete() if f.exists()
end

# Write HRegionInfo to file
# Need to serialize in case non-printable characters.
# Format is count of regionnames followed by serialized regionnames.
def writeFile(filename, regions)
  fos = java.io.FileOutputStream.new(filename)
  dos = java.io.DataOutputStream.new(fos)
  # Write out a count of region names
  dos.writeInt(regions.size())
  # Write actual region names.
  for r in regions
    Bytes.writeByteArray(dos, r.toByteArray())
  end
  dos.close()
end

# See writeFile above.
# Returns array of HRegionInfos
def readFile(filename)
  f = java.io.File.new(filename)
  return java.util.ArrayList.new() unless f.exists()
  fis = java.io.FileInputStream.new(f)
  dis = java.io.DataInputStream.new(fis)
  # Read count of regions
  count = dis.readInt()
  regions = java.util.ArrayList.new(count)
  index = 0
  while index < count
    regions.add(HRegionInfo.parseFromOrNull(Bytes.readByteArray(dis)))
    index = index + 1
  end
  dis.close()
  return regions
end

# Move regions off the passed hostname
def unloadRegions(options, hostname)
  # Get configuration
  config = getConfiguration()
  # Clean up any old files.
  filename = getFilename(options, hostname)
  deleteFile(filename)
  # Get an admin instance
  admin = HBaseAdmin.new(config)
  servers = getServers(admin)
  # Remove the server we are unloading from from list of servers.
  # Side-effect is the servername that matches this hostname
  servername = stripServer(servers, hostname)

  # Remove the servers in our exclude list from list of servers.
  servers = stripExcludes(servers, options[:excludesFile])
  puts "Valid region move targets: ", servers
  movedRegions = java.util.ArrayList.new()
  while true
    rs = getRegions(config, servername)
    break if rs.length == 0
    count = 0
    $LOG.info("Moving " + rs.length.to_s + " region(s) from " + servername +
      " during this cycle");
    for r in rs
      # Get a random server to move the region to.
      server = servers[rand(servers.length)]
      $LOG.info("Moving region " + r.getEncodedName() + " (" + count.to_s +
        " of " + rs.length.to_s + ") to server=" + server);
      count = count + 1
      # Assert we can scan region in its current location
      isSuccessfulScan(admin, r)
      # Now move it.
      move(admin, r, server, servername)
      movedRegions.add(r)
    end
  end
  if movedRegions.size() > 0
    # Write out file of regions moved
    writeFile(filename, movedRegions)
    $LOG.info("Wrote list of moved regions to " + filename)
  end
end

# Move regions to the passed hostname
def loadRegions(options, hostname)
  # Get configuration
  config = getConfiguration()
  # Get an admin instance
  admin = HBaseAdmin.new(config)
  filename = getFilename(options, hostname)
  regions = readFile(filename)
  return if regions.isEmpty()
  servername = nil
  # Wait till server is up
  maxWaitInSeconds = admin.getConfiguration.getInt("hbase.serverstart.wait.max", 180)
  maxWait = Time.now + maxWaitInSeconds
  while Time.now < maxWait
    servers = getServers(admin)
    begin
      servername = getServerName(servers, hostname)
    rescue ArgumentError => e
      $LOG.info("hostname=" + hostname.to_s + " is not up yet, waiting");
    end
    break if servername
    sleep 0.5
  end
  $LOG.info("Moving " + regions.size().to_s + " regions to " + servername)
  count = 0
  for r in regions
    exists = false
    begin
      isSuccessfulScan(admin, r)
      exists = true
    rescue org.apache.hadoop.hbase.exceptions.NotServingRegionException => e
      $LOG.info("Failed scan of " + e.message)
    end
    count = count + 1
    next unless exists
    currentServer = getServerNameForRegion(admin, r)
    if currentServer and currentServer == servername
      $LOG.info("Region " + r.getRegionNameAsString() + " (" + count.to_s +
        " of " + regions.length.to_s + ") already on target server=" + servername)
      next
    end
    $LOG.info("Moving region " + r.getEncodedName() + " (" + count.to_s +
      " of " + regions.length.to_s + ") to server=" + servername);
    move(admin, r, servername, currentServer)
  end
end

# Returns an array of hosts to exclude as region move targets
def readExcludes(filename)
  if filename == nil
    return java.util.ArrayList.new()
  end
  if ! File.exist?(filename)
      puts "Error: Unable to read host exclude file: ", filename
      raise RuntimeError
  end

  f = File.new(filename, "r")
  # Read excluded hosts list
  excludes = java.util.ArrayList.new()
  while (line = f.gets)
    line.strip! # do an inplace drop of pre and post whitespaces
    excludes.add(line) unless line.empty? # exclude empty lines
  end
  puts "Excluding hosts as region move targets: ", excludes
  f.close

  return excludes
end

def getFilename(options, targetServer)
  filename = options[:file]
  if not filename
    filename = "/tmp/" + targetServer
  end
  return filename
end

# Do command-line parsing
options = {}
optparse = OptionParser.new do |opts|
  opts.banner = "Usage: #{NAME}.rb [options] load|unload <hostname>"
  opts.separator 'Load or unload regions by moving one at a time'
  options[:file] = nil
  opts.on('-f', '--filename=FILE', 'File to save regions list into unloading, or read from loading; default /tmp/<hostname>') do |file|
    options[:file] = file
  end
  opts.on('-h', '--help', 'Display usage information') do
    puts opts
    exit
  end
  options[:debug] = false
  opts.on('-d', '--debug', 'Display extra debug logging') do
    options[:debug] = true
  end
  opts.on('-x', '--excludefile=FILE', 'File with hosts-per-line to exclude as unload targets; default excludes only target host; useful for rack decommisioning.') do |file|
    options[:excludesFile] = file
  end
end
optparse.parse!

# Check ARGVs
if ARGV.length < 2
  puts optparse
  exit 1
end
hostname = ARGV[1]
if not hostname
  opts optparse
  exit 2
end
# Create a logger and save it to ruby global
$LOG = configureLogging(options)
case ARGV[0]
  when 'load'
    loadRegions(options, hostname)
  when 'unload'
    unloadRegions(options, hostname)
  else
    puts optparse
    exit 3
end


text:
module Tr3llo
  module Command
    module List
      module Add
        extend self

        def execute(board_id)
          interface = Application.fetch_interface!()

          interface.print_frame do
            name = interface.input.ask("Name:", required: true)

            API::List.create(name, board_id)

            interface.puts("List has been created.")
          end
        end
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
const cachios = require('./../src');

const axios = require('axios');
const MockAdapter = require('axios-mock-adapter');

describe('cachios cancelling', () => {
  let mock;

  beforeEach(() => {
    mock = new MockAdapter(axios);
  });

  afterEach(() => {
    mock.reset();
  });

  test('nothing should explode if a request is cancelled', async () => {
    jest.useFakeTimers();

    const cachiosInstance = cachios.create(axios);
    const url = 'http://localhost/fake-url';

    const CancelToken = axios.CancelToken;
    let source = CancelToken.source();

    const cachiosPromise = cachiosInstance.get(url, {
      cancelToken: source.token,
    });

    source.cancel('test');

    try {
      await cachiosPromise;
      // this should never happen!
      throw new Error('Promise should not successfully resolve, we cancelled it!');
    } catch (ex) {
      // we should receive the normal axios cancel exception here
      // (and no "null" issues)
      expect(ex.message).toBe('test');
    }

    source = CancelToken.source();

    mock.onGet(url).reply(200);

    try {
      const resp = await cachiosInstance.get(url, {
        cancelToken: source.token,
      });
      expect(resp.status).toBe(200);
    } catch (ex) {
      throw new Error(`The cancelled request was unexpectedly cached, reproducing https://github.com/AlbinoDrought/cachios/issues/55`);
    }
  });
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NewEmployee.Data.Models {
    public class Test {

        private int _testId;
        private int _employeeId;
        private string _title;
        private string _description;
        private int _passingScore;
        private List<Question> _questions;

        public int TestId {
            get { return _testId; }
            set { _testId = value; }
        }

        public int EmployeeId {
            get { return _employeeId; }
            set { _employeeId = value; }
        }

        public string Title {
            get { return _title; }
            set { _title = value; }
        }

        public string Description {
            get { return _description; }
            set { _description = value; }
        }

        public int PassingScore {
            get { return _passingScore; }
            set { _passingScore = value; }
        }

        public List<Question> Questions {
            get { return _questions; }
            set { _questions = value; }
        }

    }
}


text:
package com.github.vbauer.jackdaw.util.model;

import com.github.vbauer.jackdaw.util.TypeUtils;
import com.google.common.base.Objects;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.StringUtils;

import javax.lang.model.element.ExecutableElement;
import javax.lang.model.type.TypeMirror;
import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 * @author Vladislav Bauer
 */
public class MethodInfo {

    private final String name;
    private final TypeMirror returnType;
    private final List<TypeMirror> parameterTypes;
    private final ExecutableElement element;

    public MethodInfo(
        final String name, final TypeMirror returnType, final List<TypeMirror> parameterTypes,
        final ExecutableElement element
    ) {
        this.name = name;
        this.returnType = returnType;
        this.parameterTypes = parameterTypes;
        this.element = element;
    }

    public static MethodInfo create(final ExecutableElement element) {
        return new MethodInfo(
            TypeUtils.getName(element),
            element.getReturnType(),
            TypeUtils.asTypes(element.getParameters()),
            element
        );
    }

    public static Set<ExecutableElement> convert(final Collection<MethodInfo> info) {
        final Set<ExecutableElement> methods = Sets.newHashSet();
        for (final MethodInfo method : info) {
            methods.add(method.getElement());
        }
        return methods;
    }

    public static MethodInfo find(
        final Collection<MethodInfo> info, final String name, final Collection<TypeMirror> types
    ) {
        for (final MethodInfo method : info) {
            final String methodName = method.getName();
            if (StringUtils.equals(methodName, name)
                && Objects.equal(method.getParameterTypes(), types)) {
                return method;
            }
        }
        return null;
    }

    public String getName() {
        return name;
    }

    public TypeMirror getReturnType() {
        return returnType;
    }

    public List<TypeMirror> getParameterTypes() {
        return parameterTypes;
    }

    public ExecutableElement getElement() {
        return element;
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(
            getName(),
            getParameterTypes(),
            getReturnType()
        );
    }

    @Override
    public boolean equals(final Object obj) {
        if (obj instanceof  MethodInfo) {
            final MethodInfo other = (MethodInfo) obj;
            return Objects.equal(other.getName(), getName())
                && Objects.equal(other.getParameterTypes(), getParameterTypes())
                && Objects.equal(other.getReturnType(), getReturnType());
        }
        return false;
    }

}


text:
import platform
import sys
import threading
import traceback
import tzlocal
import uuid

from king_phisher import its
from king_phisher import utilities
from king_phisher import version
from king_phisher.client import gui_utilities

import advancedhttpserver
from gi.repository import GLib
from gi.repository import Gtk
from gi.repository import Pango

__all__ = ('ExceptionDialog',)

EXCEPTION_DETAILS_TEMPLATE = """
Error Type: {error_type}
Error Details: {error_details}
Error UID: {error_uid}
RPC Error: {rpc_error_details}
King Phisher Version: {king_phisher_version}
Platform Version: {platform_version}
Python Version: {python_version}
Gtk Version: {gtk_version}
Timezone: {timezone}

Thread Information:
{thread_info}

Stack Trace:
{stack_trace}
"""

def format_exception_details(exc_type, exc_value, exc_traceback, error_uid=None):
	"""
	Format exception details to be show to a human. This should include enough
	information about the type of error that occurred and the system on which
	it was triggered to allow someone to attempt to debug and fix it. The first
	three parameters to this function directly correspond to the values
	returned from the :py:func:`sys.exc_info` function.

	:param exc_type: The type of the exception.
	:param exc_value: The exception instance.
	:param exc_traceback: The traceback object corresponding to the exception.
	:param error_uid: A unique identifier for this exception.
	:type error_uid: str, :py:class:`uuid.UUID`
	:return: A formatted message containing the details about the exception and environment.
	:rtype: str
	"""
	if isinstance(error_uid, uuid.UUID):
		error_uid = str(error_uid)
	elif error_uid is None:
		error_uid = 'N/A'
	elif not isinstance(error_uid, str):
		raise TypeError('error_uid must be an instance of either str, uuid.UUID or None')
	pversion = 'UNKNOWN'
	if its.on_linux:
		pversion = 'Linux: ' + ' '.join(platform.linux_distribution())
	elif its.on_windows:
		pversion = 'Windows: ' + ' '.join(platform.win32_ver())
		if its.frozen:
			pversion += ' (Frozen=True)'
		else:
			pversion += ' (Frozen=False)'
	exc_name = format_exception_name(exc_type)
	rpc_error_details = 'N/A (Not a remote RPC error)'
	if isinstance(exc_value, advancedhttpserver.RPCError) and exc_value.is_remote_exception:
		rpc_error_details = "Name: {0}".format(exc_value.remote_exception['name'])
		if exc_value.remote_exception.get('message'):
			rpc_error_details += " Message: '{0}'".format(exc_value.remote_exception['message'])
	current_tid = threading.current_thread().ident
	thread_info = (
		"{0: >4}{1} (alive={2} daemon={3})".format(('=> ' if thread.ident == current_tid else ''), thread.name, thread.is_alive(), thread.daemon) for thread in threading.enumerate()
	)
	thread_info = '\n'.join(thread_info)
	details = EXCEPTION_DETAILS_TEMPLATE.format(
		error_details=repr(exc_value),
		error_type=exc_name,
		error_uid=error_uid,
		rpc_error_details=rpc_error_details,
		king_phisher_version=version.version,
		platform_version=pversion,
		python_version="{0}.{1}.{2}".format(*sys.version_info),
		gtk_version="{0}.{1}.{2}".format(Gtk.get_major_version(), Gtk.get_minor_version(), Gtk.get_micro_version()),
		stack_trace=''.join(traceback.format_exception(exc_type, exc_value, exc_traceback)),
		thread_info=thread_info,
		timezone=tzlocal.get_localzone().zone
	)
	details = details.strip() + '\n'
	return details

def format_exception_name(exc_type):
	"""
	Format the exception name into a more easily recognizable format.

	:param exc_type: The type of the exception.
	:return: The formatted exception name.
	:rtype: str
	"""
	return "{0}.{1}".format(exc_type.__module__, exc_type.__name__)

class ExceptionDialog(gui_utilities.GladeGObject):
	"""
	Display a dialog which shows an error message for a python exception.
	The dialog includes useful details for reporting and debugging the exception
	which occurred.
	"""
	dependencies = gui_utilities.GladeDependencies(
		children=('linkbutton_github_issues',)
	)
	top_gobject = 'dialog'
	def __init__(self, application, exc_info=None, error_uid=None):
		"""
		:param application: The parent application for this object.
		:type application: :py:class:`Gtk.Application`
		:param tuple exc_info: The exception information as provided by :py:func:`sys.exc_info`.
		:param str error_uid: An optional unique identifier for the exception that can be provided for tracking purposes.
		"""
		super(ExceptionDialog, self).__init__(application)
		self.error_description = self.gtk_builder_get('label_error_description')
		self.error_details = self.gtk_builder_get('textview_error_details')
		self.error_details.modify_font(Pango.FontDescription('monospace 9'))
		self.exc_info = exc_info or sys.exc_info()
		self.error_uid = error_uid
		linkbutton = self.gobjects['linkbutton_github_issues']
		linkbutton.set_label('Project Issue Tracker')
		linkbutton.connect('activate-link', lambda _: utilities.open_uri(linkbutton.get_property('uri')))

	def interact(self):
		exc_type, exc_value, exc_traceback = self.exc_info
		details = format_exception_details(exc_type, exc_value, exc_traceback, self.error_uid)

		self.error_description.set_text("Error type: {0}".format(format_exception_name(exc_type)))
		self.error_details.get_buffer().set_text(details)

		self.dialog.show_all()
		self.dialog.run()
		self.dialog.destroy()
		return

	@classmethod
	def _interact_on_idle(cls, args, kwargs):
		instance = cls(*args, **kwargs)
		instance.interact()

	@classmethod
	def interact_on_idle(cls, *args, **kwargs):
		GLib.idle_add(cls._interact_on_idle, args, kwargs)


text:
package org.apache.flink.table.plan.rules.physical.batch

import org.apache.flink.table.api.{OperatorType, PlannerConfigOptions}
import org.apache.flink.table.calcite.FlinkContext
import org.apache.flink.table.plan.`trait`.FlinkRelDistribution
import org.apache.flink.table.plan.nodes.FlinkConventions
import org.apache.flink.table.plan.nodes.logical.FlinkLogicalJoin
import org.apache.flink.table.plan.nodes.physical.batch.BatchExecSortMergeJoin
import org.apache.flink.table.plan.util.FlinkRelOptUtil

import org.apache.calcite.plan.RelOptRule.{any, operand}
import org.apache.calcite.plan.{RelOptRule, RelOptRuleCall, RelTraitSet}
import org.apache.calcite.rel.core.Join
import org.apache.calcite.rel.{RelCollations, RelNode}
import org.apache.calcite.util.ImmutableIntList

import scala.collection.JavaConversions._

/**
  * Rule that converts [[FlinkLogicalJoin]] to [[BatchExecSortMergeJoin]]
  * if there exists at least one equal-join condition and SortMergeJoin is enabled.
  */
class BatchExecSortMergeJoinRule
  extends RelOptRule(
    operand(classOf[FlinkLogicalJoin],
      operand(classOf[RelNode], any)),
    "BatchExecSortMergeJoinRule")
  with BatchExecJoinRuleBase {

  override def matches(call: RelOptRuleCall): Boolean = {
    val join: Join = call.rel(0)
    val joinInfo = join.analyzeCondition
    val tableConfig = call.getPlanner.getContext.asInstanceOf[FlinkContext].getTableConfig
    val isSortMergeJoinEnabled = tableConfig.isOperatorEnabled(OperatorType.SortMergeJoin)
    !joinInfo.pairs().isEmpty && isSortMergeJoinEnabled
  }

  override def onMatch(call: RelOptRuleCall): Unit = {
    val join: Join = call.rel(0)
    val joinInfo = join.analyzeCondition
    val left = join.getLeft
    val right = join.getRight

    def getTraitSetByShuffleKeys(
        shuffleKeys: ImmutableIntList,
        requireStrict: Boolean,
        requireCollation: Boolean): RelTraitSet = {
      var traitSet = call.getPlanner.emptyTraitSet()
        .replace(FlinkConventions.BATCH_PHYSICAL)
        .replace(FlinkRelDistribution.hash(shuffleKeys, requireStrict))
      if (requireCollation) {
        val fieldCollations = shuffleKeys.map(FlinkRelOptUtil.ofRelFieldCollation(_))
        val relCollation = RelCollations.of(fieldCollations)
        traitSet = traitSet.replace(relCollation)
      }
      traitSet
    }

    def transformToEquiv(
        leftRequiredShuffleKeys: ImmutableIntList,
        rightRequiredShuffleKeys: ImmutableIntList,
        requireLeftSorted: Boolean,
        requireRightSorted: Boolean): Unit = {

      val leftRequiredTrait = getTraitSetByShuffleKeys(
        leftRequiredShuffleKeys, requireStrict = true, requireLeftSorted)
      val rightRequiredTrait = getTraitSetByShuffleKeys(
        rightRequiredShuffleKeys, requireStrict = true, requireRightSorted)

      val newLeft = RelOptRule.convert(left, leftRequiredTrait)
      val newRight = RelOptRule.convert(right, rightRequiredTrait)

      val providedTraitSet = call.getPlanner
        .emptyTraitSet()
        .replace(FlinkConventions.BATCH_PHYSICAL)
      val newJoin = new BatchExecSortMergeJoin(
        join.getCluster,
        providedTraitSet,
        newLeft,
        newRight,
        join.getCondition,
        join.getJoinType,
        requireLeftSorted,
        requireRightSorted)
      call.transformTo(newJoin)
    }

    val tableConfig = call.getPlanner.getContext.asInstanceOf[FlinkContext].getTableConfig
    val candidates = if (tableConfig.getConf.getBoolean(
      PlannerConfigOptions.SQL_OPTIMIZER_SMJ_REMOVE_SORT_ENABLED)) {
      // add more possibility to remove redundant sort, and longer optimization time
      Array((false, false), (true, false), (false, true), (true, true))
    } else {
      // will not try to remove redundant sort, and shorter optimization time
      Array((false, false))
    }
    candidates.foreach {
      case (requireLeftSorted, requireRightSorted) =>
        transformToEquiv(
          joinInfo.leftKeys,
          joinInfo.rightKeys,
          requireLeftSorted,
          requireRightSorted)
    }

    // add more possibility to only shuffle by partial joinKeys, now only single one
    val isShuffleByPartialKeyEnabled = tableConfig.getConf.getBoolean(
      PlannerConfigOptions.SQL_OPTIMIZER_SHUFFLE_PARTIAL_KEY_ENABLED)
    if (isShuffleByPartialKeyEnabled && joinInfo.pairs().length > 1) {
      joinInfo.pairs().foreach { pair =>
        // sort require full key not partial key,
        // so requireLeftSorted and requireRightSorted should both be false here
        transformToEquiv(
          ImmutableIntList.of(pair.source),
          ImmutableIntList.of(pair.target),
          requireLeftSorted = false,
          requireRightSorted = false)
      }
    }
  }
}

object BatchExecSortMergeJoinRule {
  val INSTANCE: RelOptRule = new BatchExecSortMergeJoinRule
}


text:
module PgLtree
  module Model
    extend ActiveSupport::Concern

    class_methods do
      def ltree_path_column
        ltree_option_for :column
      end

      # Get roots
      #
      # @return [ActiveRecord::Relation] relations of node's roots
      def roots
        at_depth 1
      end

      # Get nodes on the level
      #
      # @param depth [Integer] Depth of the nodes
      # @return [ActiveRecord::Relation] relations of nodes for the depth
      def at_depth(depth)
        where "NLEVEL(#{table_name}.#{ltree_path_column}) = ?", depth
      end

      # Get all leaves
      #
      # @return [ActiveRecord::Relation] relations of node's leaves
      def leaves
        subquery = unscoped.select("#{table_name}.#{ltree_path_column}")
          .from("#{table_name} AS subquery")
          .where("#{table_name}.#{ltree_path_column} <> subquery.#{ltree_path_column}")
          .where("#{table_name}.#{ltree_path_column} @> subquery.#{ltree_path_column}")

        where.not ltree_path_column => subquery
      end

      # Get all with nodes when path liked the lquery
      #
      # @param lquery [String] ltree query
      # @return [ActiveRecord::Relation] relations of node'
      def where_path_liked(lquery)
        where "#{table_name}.#{ltree_path_column} ~ ?", lquery
      end

      # Get all nodes with path matching full-text-search-like pattern
      #
      # @param ltxtquery [String] ltree search query
      # @return [ActiveRecord::Relation] of matching nodes
      def where_path_matches_ltxtquery(ltxtquery)
        where "#{table_name}.#{ltree_path_column} @ ?", ltxtquery
      end
    end

    included do
      # Get default scope of ltree
      #
      # @return current class
      def ltree_scope
        self.class
      end

      # Get lTree column
      #
      # @return [String] ltree column name
      delegate :ltree_path_column, to: :ltree_scope

      # Get lTree value
      #
      # @return [String] ltree current value
      def ltree_path
        public_send ltree_path_column
      end

      # Get ltree original value before the save just occurred
      # https://api.rubyonrails.org/classes/ActiveRecord/AttributeMethods/Dirty.html#method-i-attribute_before_last_save
      #
      # @return [String] ltree previous value
      def ltree_path_before_last_save
        public_send :attribute_before_last_save, ltree_path_column
      end

      # Get lTree previous value
      # originally +attribute_was+ used in before create/update, destroy won't call +save+ so this work
      # https://api.rubyonrails.org/classes/ActiveRecord/AttributeMethods/Dirty.html#method-i-attribute_in_database
      #
      # @return [String] ltree value in database

      def ltree_path_in_database
        public_send :attribute_in_database, ltree_path_column
      end

      # Check what current node is root
      #
      # @return [Boolean] True - for root node, False - for childen node
      def root?
        depth == 1
      end

      # Get node height
      #
      # The height of a node is the number of edges
      # on the longest downward path between that node and a leaf. The leaf nodes have height zero,
      # and a tree with only a single node (hence both a root and leaf) has height zero.
      # Conventionally, an empty tree (tree with no nodes, if such are allowed) has depth and height −1
      #
      # @return [Number] height of the given node. Height of the tree for root node.
      def height
        self_and_descendants.maximum("NLEVEL(#{ltree_path_column})") - depth.to_i
      end

      # Get node depth
      #
      # @return [Integer] node depth
      def depth
        ActiveRecord::Base.connection.select_all("SELECT NLEVEL('#{ltree_path}')").rows.flatten.first.to_i
      end

      # Get root of the node
      #
      # return [Object] root node
      def root
        ltree_scope.where("#{self.class.table_name}.#{ltree_path_column} = SUBPATH(?, 0, 1)", ltree_path).first
      end

      # Get parent of the node
      #
      # return [Object] root node
      def parent
        ltree_scope.find_by "#{self.class.table_name}.#{ltree_path_column} = SUBPATH(?, 0, NLEVEL(?) - 1)", ltree_path,
          ltree_path
      end

      # Get leaves of the node
      #
      # @return [ActiveRecord::Relation]
      def leaves
        ltree_scope.leaves.where("#{self.class.table_name}.#{ltree_path_column} <@ ?",
          ltree_path).where.not ltree_path_column => ltree_path
      end

      # Check what current node have leaves
      #
      # @return [Boolean] True - if node have leaves, False - if node doesn't have leaves
      def leaf?
        leaves.count == 0
      end

      # Get self and ancestors
      #
      # @return [ActiveRecord::Relation]
      def self_and_ancestors
        ltree_scope.where("#{self.class.table_name}.#{ltree_path_column} @> ?", ltree_path)
      end

      # Get ancestors
      #
      # @return [ActiveRecord::Relation]
      def ancestors
        self_and_ancestors.where.not ltree_path_column => ltree_path
      end

      # Get self and descendants
      #
      # @return [ActiveRecord::Relation]
      def self_and_descendants
        ltree_scope.where("#{self.class.table_name}.#{ltree_path_column} <@ ?", ltree_path)
      end

      # Get descendants
      #
      # @return [ActiveRecord::Relation]
      def descendants
        self_and_descendants.where.not ltree_path_column => ltree_path
      end

      # Get self and siblings
      #
      # @return [ActiveRecord::Relation]
      def self_and_siblings
        ltree_scope.where(
          "SUBPATH(?, 0, NLEVEL(?) - 1) @> #{self.class.table_name}.#{ltree_path_column} AND nlevel(#{self.class.table_name}.#{ltree_path_column}) = NLEVEL(?)",
          ltree_path, ltree_path, ltree_path
        )
      end

      # Get siblings
      #
      # @return [ActiveRecord::Relation]
      def siblings
        self_and_siblings.where.not ltree_path_column => ltree_path
      end

      # Get children
      #
      # @return [ActiveRecord::Relation]
      def children
        ltree_scope.where "? @> #{self.class.table_name}.#{ltree_path_column} AND nlevel(#{self.class.table_name}.#{ltree_path_column}) = NLEVEL(?) + 1",
          ltree_path, ltree_path
      end

      # Update all childen for current path
      #
      # @return [ActiveRecord::Relation]
      def cascade_update
        ltree_scope
          .where("#{self.class.table_name}.#{ltree_path_column} <@ ?", ltree_path_before_last_save)
          .where("#{self.class.table_name}.#{ltree_path_column} != ?", ltree_path)
          .update_all("#{ltree_path_column} = ? || subpath(#{ltree_path_column}, nlevel(?))", ltree_path, ltree_path_before_last_save)
      end

      # Delete all children for current path
      #
      # @return [ActiveRecord::Relation]
      def cascade_destroy
        ltree_scope.where("#{self.class.table_name}.#{ltree_path_column} <@ ?", ltree_path_in_database).destroy_all
      end
    end
  end
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>C-Index</title>
<meta name="date" content="2016-12-29">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C E F G H I L M N P R S T U W

C

conditionalCommentDialect() - Method in class br.com.minitwitter.MinitwitterApplication

contains(User) - Method in class br.com.minitwitter.service.UserService

contextLoads() - Method in class br.com.minitwitter.MinitwitterApplicationTests

createUser(User, BindingResult) - Method in class br.com.minitwitter.controller.UserController

a post method to create a new user

A B C E F G H I L M N P R S T U W

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
<?php

/**
 * Service definition for Audit (v1).
 *
 *

 * Lets you access user activities in your enterprise made through various applications.
 *

 *
 *

 * For more information about this service, see the API
 * Documentation
 *

 *
 * @author Google, Inc.
 */
class Google_Service_Audit extends Google_Service
{

  public $activities;

  /**
   * Constructs the internal representation of the Audit service.
   *
   * @param Google_Client $client
   */
  public function __construct(Google_Client $client)
  {
    parent::__construct($client);
    $this->servicePath = 'apps/reporting/audit/v1/';
    $this->version = 'v1';
    $this->serviceName = 'audit';

    $this->activities = new Google_Service_Audit_Activities_Resource(
        $this,
        $this->serviceName,
        'activities',
        array(
          'methods' => array(
            'list' => array(
              'path' => '{customerId}/{applicationId}',
              'httpMethod' => 'GET',
              'parameters' => array(
                'customerId' => array(
                  'location' => 'path',
                  'type' => 'string',
                  'required' => true,
                ),
                'applicationId' => array(
                  'location' => 'path',
                  'type' => 'string',
                  'required' => true,
                ),
                'actorEmail' => array(
                  'location' => 'query',
                  'type' => 'string',
                ),
                'actorApplicationId' => array(
                  'location' => 'query',
                  'type' => 'string',
                ),
                'actorIpAddress' => array(
                  'location' => 'query',
                  'type' => 'string',
                ),
                'caller' => array(
                  'location' => 'query',
                  'type' => 'string',
                ),
                'maxResults' => array(
                  'location' => 'query',
                  'type' => 'integer',
                ),
                'eventName' => array(
                  'location' => 'query',
                  'type' => 'string',
                ),
                'startTime' => array(
                  'location' => 'query',
                  'type' => 'string',
                ),
                'endTime' => array(
                  'location' => 'query',
                  'type' => 'string',
                ),
                'continuationToken' => array(
                  'location' => 'query',
                  'type' => 'string',
                ),
              ),
            ),
          )
        )
    );
  }
}

/**
 * The "activities" collection of methods.
 * Typical usage is:
 *
 *   $auditService = new Google_Service_Audit(...);
 *   $activities = $auditService->activities;
 *
 */
class Google_Service_Audit_Activities_Resource extends Google_Service_Resource
{

  /**
   * Retrieves a list of activities for a specific customer and application.
   * (activities.listActivities)
   *
   * @param string $customerId
   * Represents the customer who is the owner of target object on which action was performed.
   * @param string $applicationId
   * Application ID of the application on which the event was performed.
   * @param array $optParams Optional parameters.
   *
   * @opt_param string actorEmail
   * Email address of the user who performed the action.
   * @opt_param string actorApplicationId
   * Application ID of the application which interacted on behalf of the user while performing the
    * event.
   * @opt_param string actorIpAddress
   * IP Address of host where the event was performed. Supports both IPv4 and IPv6 addresses.
   * @opt_param string caller
   * Type of the caller.
   * @opt_param int maxResults
   * Number of activity records to be shown in each page.
   * @opt_param string eventName
   * Name of the event being queried.
   * @opt_param string startTime
   * Return events which occured at or after this time.
   * @opt_param string endTime
   * Return events which occured at or before this time.
   * @opt_param string continuationToken
   * Next page URL.
   * @return Google_Service_Audit_Activities
   */
  public function listActivities($customerId, $applicationId, $optParams = array())
  {
    $params = array('customerId' => $customerId, 'applicationId' => $applicationId);
    $params = array_merge($params, $optParams);
    return $this->call('list', array($params), "Google_Service_Audit_Activities");
  }
}

class Google_Service_Audit_Activities extends Google_Collection
{
  protected $itemsType = 'Google_Service_Audit_Activity';
  protected $itemsDataType = 'array';
  public $kind;
  public $next;

  public function setItems($items)
  {
    $this->items = $items;
  }

  public function getItems()
  {
    return $this->items;
  }

  public function setKind($kind)
  {
    $this->kind = $kind;
  }

  public function getKind()
  {
    return $this->kind;
  }

  public function setNext($next)
  {
    $this->next = $next;
  }

  public function getNext()
  {
    return $this->next;
  }
}

class Google_Service_Audit_Activity extends Google_Collection
{
  protected $actorType = 'Google_Service_Audit_ActivityActor';
  protected $actorDataType = '';
  protected $eventsType = 'Google_Service_Audit_ActivityEvents';
  protected $eventsDataType = 'array';
  protected $idType = 'Google_Service_Audit_ActivityId';
  protected $idDataType = '';
  public $ipAddress;
  public $kind;
  public $ownerDomain;

  public function setActor(Google_Service_Audit_ActivityActor $actor)
  {
    $this->actor = $actor;
  }

  public function getActor()
  {
    return $this->actor;
  }

  public function setEvents($events)
  {
    $this->events = $events;
  }

  public function getEvents()
  {
    return $this->events;
  }

  public function setId(Google_Service_Audit_ActivityId $id)
  {
    $this->id = $id;
  }

  public function getId()
  {
    return $this->id;
  }

  public function setIpAddress($ipAddress)
  {
    $this->ipAddress = $ipAddress;
  }

  public function getIpAddress()
  {
    return $this->ipAddress;
  }

  public function setKind($kind)
  {
    $this->kind = $kind;
  }

  public function getKind()
  {
    return $this->kind;
  }

  public function setOwnerDomain($ownerDomain)
  {
    $this->ownerDomain = $ownerDomain;
  }

  public function getOwnerDomain()
  {
    return $this->ownerDomain;
  }
}

class Google_Service_Audit_ActivityActor extends Google_Model
{
  public $applicationId;
  public $callerType;
  public $email;
  public $key;

  public function setApplicationId($applicationId)
  {
    $this->applicationId = $applicationId;
  }

  public function getApplicationId()
  {
    return $this->applicationId;
  }

  public function setCallerType($callerType)
  {
    $this->callerType = $callerType;
  }

  public function getCallerType()
  {
    return $this->callerType;
  }

  public function setEmail($email)
  {
    $this->email = $email;
  }

  public function getEmail()
  {
    return $this->email;
  }

  public function setKey($key)
  {
    $this->key = $key;
  }

  public function getKey()
  {
    return $this->key;
  }
}

class Google_Service_Audit_ActivityEvents extends Google_Collection
{
  public $eventType;
  public $name;
  protected $parametersType = 'Google_Service_Audit_ActivityEventsParameters';
  protected $parametersDataType = 'array';

  public function setEventType($eventType)
  {
    $this->eventType = $eventType;
  }

  public function getEventType()
  {
    return $this->eventType;
  }

  public function setName($name)
  {
    $this->name = $name;
  }

  public function getName()
  {
    return $this->name;
  }

  public function setParameters($parameters)
  {
    $this->parameters = $parameters;
  }

  public function getParameters()
  {
    return $this->parameters;
  }
}

class Google_Service_Audit_ActivityEventsParameters extends Google_Model
{
  public $name;
  public $value;

  public function setName($name)
  {
    $this->name = $name;
  }

  public function getName()
  {
    return $this->name;
  }

  public function setValue($value)
  {
    $this->value = $value;
  }

  public function getValue()
  {
    return $this->value;
  }
}

class Google_Service_Audit_ActivityId extends Google_Model
{
  public $applicationId;
  public $customerId;
  public $time;
  public $uniqQualifier;

  public function setApplicationId($applicationId)
  {
    $this->applicationId = $applicationId;
  }

  public function getApplicationId()
  {
    return $this->applicationId;
  }

  public function setCustomerId($customerId)
  {
    $this->customerId = $customerId;
  }

  public function getCustomerId()
  {
    return $this->customerId;
  }

  public function setTime($time)
  {
    $this->time = $time;
  }

  public function getTime()
  {
    return $this->time;
  }

  public function setUniqQualifier($uniqQualifier)
  {
    $this->uniqQualifier = $uniqQualifier;
  }

  public function getUniqQualifier()
  {
    return $this->uniqQualifier;
  }
}


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

@Component({
  selector: 'patients-page',
  template: `

Patients list

  `
})
class PatientsPage {

}

export {
  PatientsPage
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Toucan Toco Sparklines</title>
    <meta name="author" content="David Nowinsky <david@toucantoco.com>">
    <meta name="description" content="Trendy graphs">
    <meta name="keywords" content="sparkline,sparklines,toucan toco,toucan,toco,open-source,d3,plugin,chart,trends">

    <link href="dist/tc-sparklines.css" rel="stylesheet">

     <link href="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.5.3/mocha.css" rel="stylesheet" />


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?><!--

  Copyright 2003 - 2013 The eFaps Team

  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.

  Author:          The eFaps Team
  Revision:        $Rev$
  Last Changed:    $Date$
  Last Changed By: $Author$

-->
<ui-form xmlns="http://www.efaps.org/xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.efaps.org/xsd http://www.efaps.org/xsd/eFaps_1.0.xsd">
    <uuid>ca3cb29d-08b6-4772-a5c4-4945d0904302</uuid>
    <file-application>eFapsApp-Accounting</file-application>
    <file-revision>$Rev$</file-revision>
    <definition>
        <version-expression>(version==latest)</version-expression>
        <name>Accounting_AccountConfigDocument2PeriodForm</name>
        <!-- fields -->
        <field name="type">
            <property name="Attribute">Type</property>
        </field>
        <field name="isSale">
            <property name="Attribute">IsSale</property>
            <property name="ModeEdit">EDITABLE</property>
        </field>
    </definition>
</ui-form>


text:
<?php

namespace Theme\AssetManager;

use \Zend\ServiceManager\FactoryInterface;
use \Zend\ServiceManager\ServiceLocatorInterface;

/**
 *
 * @author PedromDev
 */
class AssetManagerFactory implements FactoryInterface
{
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        return new AssetManager(
            $serviceLocator->get('AssetManagerConfig')
        );
    }
}


text:
import * as Guifast from "guifast_shared";

export interface ClientEvent<T> {
    add(callback: Guifast.Fn1<void, T>): number;
    remove(eventHandlerId: number): void;
}


text:
var Slider = new Widget({
  include: Updater,

  extend: {
    version: '2.3.1',

    EVENTS: $w('change'),

    Options: {
      min:       0,     // the min value
      max:       100,   // the max value
      snap:      0,     // the values threshold
      range:     false, // whether a single handle slider or a range slider
      value:     null,  // start value, if null then the min value will be used
      values:    null,  // range values when range = true, if null then then min/max value will be used
      direction: 'x',   // slider direction 'x', 'y'
      update:    null,  // reference to an element to update
      round:     0      // the number of symbols after the decimal pointer
    },

    current: false
  },

  /**
   * basic constructor
   * USAGE:
   *   new Slider('element-id'[, {options}]);
   *   new Slider({options});
   *
   * @param mixed slider element reference or options
   * @param Object options
   */
  initialize: function() {
    var args = $A(arguments).compact(), options = args.pop(), element = args.pop();

    // figuring out the arguments
    if (!isHash(options) || options instanceof Element) {
      element = $(element || options);
      options = {};
    }

    this.$super('slider', element).setOptions(options)
      .on('selectstart', 'stopEvent'); // disable select under IE

    this.level  = this.first('.level')  || $E('div', {'class': 'level'}).insertTo(this);

    options = this.options;
    this.value = options.value === null ? options.min : options.value;

    if (options.range === true) {
      this.handles = new Array();
      this.handles[0] = this.first('.handle.from') || $E('div', {'class': 'handle from'}).insertTo(this);
      this.handles[1] = this.first('.handle.to') || $E('div', {'class': 'handle to'}).insertTo(this);

      this.values = [0, 0];
      this.values[0] = options.values === null ? options.min : options.values[0];
      this.values[1] = options.values === null ? options.max : options.values[1];

      this.setValue(this.values[0], 'from');
      this.setValue(this.values[1], 'to');

    } else {
      this.handle = this.first('.handle') || $E('div', {'class': 'handle'}).insertTo(this);
      this.setValue(this.value);
    }

    if (options.update) { this.assignTo(options.update); }
    if (options.direction === 'y') { this.addClass('rui-slider-vertical'); }
    else if (this.hasClass('rui-slider-vertical')) { options.direction = 'y'; }

  },

  /**
   * The value setter
   *
   * NOTE: will get snapped according to the options
   *
   * @param mixed string or number value, an optional type specifying 'from' or 'to' when using with range slider
   * @return Slider this
   */
  setValue: function(value, type) {
    return this.precalc().shiftTo(value, type);
  },

  /**
   * Returns the value
   *
   * @return Float number
   */
  getValue: function() {
    if (this.options.range === true) {
      return this.values[0];
    } else {
      return this.value;
    }
  },

  /**
   * Returns the values that used to store the range
   *
   * @return An array storing the from/to float numbers
   */
  getValues: function() {
    return this.values;
  },

  /**
   * Inserts the widget into the element
   *
   * @param mixed element reference
   * @param String optional position
   * @return Slider this
   */
  insertTo: function(element, position) {
    return this.$super(element, position).setValue(this.value);
  },

// protected

  // precalculates dimensions, direction and offset for further use
  precalc: function() {
    var horizontal = this.options.direction === 'x',
        dims       = this.dims = this.dimensions();

    if (this.options.range === true) {
      var handle_f    = this.handles[0].setStyle(horizontal ? {left: 0} : {bottom: 0}).dimensions(),
          handle_size = this.hSize = horizontal ? handle_f.width : handle_f.height;
          // Assuming both handles are in the same size

      this.offset = horizontal ? handle_f.left - dims.left : dims.top + dims.height - handle_f.top - handle_size;
      this.space  = (horizontal ? dims.width : dims.height) - handle_size - (this.offset * 2);

      var handle_t = this.handles[1].setStyle(horizontal ? {left: this.space + 'px'} :
                                                           {bottom: this.space + 'px'}).dimensions();

    } else {
      var handle      = this.handle.setStyle(horizontal ? {left: 0} : {bottom: 0}).dimensions(),
          handle_size = this.hSize = horizontal ? handle.width : handle.height;

      this.offset = horizontal ? handle.left - dims.left : dims.top + dims.height - handle.top - handle_size;
      this.space  = (horizontal ? dims.width : dims.height) - handle_size - this.offset * 2;
    }

    return this;
  },

  // initializes the slider drag
  start: function(event) {
    this._type = null
    if (event.target.hasClass('handle')) {
      if (event.target.hasClass('from')) {
        this._type = "from";
      } else if (event.target.hasClass('to')) {
        this._type = "to";
      }
    }

    return this.precalc().e2val(event);
  },

  // processes the slider-drag
  move: function(event) {
    return this.e2val(event);
  },

  // shifts the slider to the value
  shiftTo: function(value, type) {
    var options = this.options, base = Math.pow(10, options.round), horizontal = options.direction === 'x';

    // rounding the value up
    value = Math.round(value * base) / base;

    // checking the value constraings
    if (value < options.min) { value = options.min; }
    if (value > options.max) { value = options.max; }

    // if range slider check if the "from" handle's value is larger than the "to" handle's
    if (options.range === true) {
      if ((type === "to") && (value < this.values[0])) {
          value = this.values[0];
      }
      if ((type === "from") || (type === undefined)) {
        if (value > this.values[1]) {
          value = this.values[1];
        }
      }
    }

    if (options.snap) {
      var snap = options.snap;
      var diff = (value - options.min) % snap;
      value = diff < snap/2 ? value - diff : value - diff + snap;
    }

    if (options.range === true) {
      var value_f = (type === "from") ? value : this.values[0];
      var value_t = (type === "to")   ? value : this.values[1];

      // calculating and setting the actual position
      var position_f = this.space / (options.max - options.min) * (value_f - options.min);
      var position_t = this.space / (options.max - options.min) * (value_t - options.min);
      var length = position_t - position_f;

      if (type === "to") {
        this.handles[1]._.style[horizontal ? 'left' : 'bottom'] = position_t + 'px';
      } else {
        this.handles[0]._.style[horizontal ? 'left' : 'bottom'] = position_f + 'px';
       }

      this.level._.style[horizontal ? 'left': 'top'] = ((position_f > 0 ? position_f : 0) + 2) + 'px';
      this.level._.style[horizontal ? 'width': 'height'] = ((length > 0 ? length : 0) + 2) + 'px';

      // checking the change status
      var fireEvent = false;
      if ((type === "from") && (value !== this.values[0])) {
        this.values[0] = value;
        fireEvent = true;
      }
      if ((type === "to") && (value !== this.values[1])) {
        this.values[1] = value;
        fireEvent = true;
      }
      if (fireEvent) {
        this.fire('change', {value: value, values: this.values});
      }

    } else {
      // calculating and setting the actual position
      var position = this.space / (options.max - options.min) * (value - options.min);
      this.handle._.style[horizontal ? 'left' : 'bottom'] = position + 'px';
      this.level._.style[horizontal  ? 'width': 'height'] = ((position > 0 ? position : 0) + 2) + 'px';

      // checking the change status
      if (value !== this.value) {
        this.value = value;
        this.fire('change', {value: value});
      }
    }

    return this;
  },

  // converts the event position into the actual value in terms of the slider measures
  e2val: function(event) {
    var options = this.options, horizontal = options.direction === 'x',
        dims    = this.dims, offset = this.offset, space = this.space,
        cur_pos = event.position()[horizontal ? 'x' : 'y'] - offset - this.hSize/2,
        min_pos = horizontal ? dims.left + offset : dims.top + offset,
        value   = (options.max - options.min) / space * (cur_pos - min_pos),
        type    = this._type;

    if (type == null) {
      return this.shiftTo(horizontal ? options.min + value : options.max - value);
    } else if (type === "to") {
      this.shiftTo(this.values[0], "from");
      return this.shiftTo(horizontal ? options.min + value : options.max - value, "to");
    } else {
      this.shiftTo(this.values[1], "to");
      return this.shiftTo(horizontal ? options.min + value : options.max - value, "from");
    }
  }
});


text:
@interface CompositePlot : PlotItem <CPPlotSpaceDelegate,
									 CPPlotDataSource,
									 CPScatterPlotDelegate,
									 CPBarPlotDelegate>
{
    CPGraphHostingView  *scatterPlotView;
    CPGraphHostingView  *barChartView;
    CPGraphHostingView  *pieChartView;

    CPXYGraph           *scatterPlot;
    CPXYGraph           *barChart;
    CPXYGraph           *pieChart;

    NSMutableArray      *dataForChart;
    NSMutableArray      *dataForPlot;
}

@property(readwrite, retain, nonatomic) NSMutableArray  *dataForChart;
@property(readwrite, retain, nonatomic) NSMutableArray  *dataForPlot;

- (void)renderScatterPlotInLayer:(CPGraphHostingView *)layerHostingView withTheme:(CPTheme *)theme;
- (void)renderBarPlotInLayer:(CPGraphHostingView *)layerHostingView withTheme:(CPTheme *)theme;
- (void)renderPieChartInLayer:(CPGraphHostingView *)layerHostingView withTheme:(CPTheme *)theme;

@end


text:
#ifndef VCALTMP_H
#define VCALTMP_H

#include "libical_vcal_export.h"
#include "vcc.h"

#if defined(__CPLUSPLUS__) || defined(__cplusplus)
extern "C"
{
#endif

    LIBICAL_VCAL_EXPORT VObject *vcsCreateVCal(char *date_created,
                                               char *location,
                                               char *product_id, char *time_zone, char *version);

    LIBICAL_VCAL_EXPORT VObject *vcsAddEvent(VObject *vcal,
                                             char *start_date_time,
                                             char *end_date_time,
                                             char *description,
                                             char *summary,
                                             char *categories,
                                             char *classification,
                                             char *status, char *transparency, char *uid,
                                             char *url);

    LIBICAL_VCAL_EXPORT VObject *vcsAddTodo(VObject *vcal,
                                            char *start_date_time,
                                            char *due_date_time,
                                            char *date_time_complete,
                                            char *description,
                                            char *summary,
                                            char *priority,
                                            char *classification, char *status, char *uid,
                                            char *url);

    LIBICAL_VCAL_EXPORT VObject *vcsAddAAlarm(VObject *vevent,
                                              char *run_time,
                                              char *snooze_time,
                                              char *repeat_count, char *audio_content);

    LIBICAL_VCAL_EXPORT VObject *vcsAddMAlarm(VObject *vevent,
                                              char *run_time,
                                              char *snooze_time,
                                              char *repeat_count, char *email_address, char *note);

    LIBICAL_VCAL_EXPORT VObject *vcsAddDAlarm(VObject *vevent,
                                              char *run_time,
                                              char *snooze_time,
                                              char *repeat_count, char *display_string);

    LIBICAL_VCAL_EXPORT VObject *vcsAddPAlarm(VObject *vevent,
                                              char *run_time,
                                              char *snooze_time,
                                              char *repeat_count, char *procedure_name);

#if defined(__CPLUSPLUS__) || defined(__cplusplus)
}

#endif

#endif /* VCALTMP_H */


text:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/kds_white"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:orientation="vertical">

        <include
            android:id="@+id/login_toolbar"
            layout="@layout/login_toolbar" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:orientation="vertical"
            android:paddingStart="@dimen/grid_21"
            android:paddingEnd="@dimen/grid_21">

            <com.google.android.material.button.MaterialButton
                android:id="@+id/facebook_login_button"
                style="@style/FacebookButton"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="@dimen/grid_1"
                app:iconGravity="textStart"
                app:iconPadding="@dimen/grid_2" />

            <TextView
                style="@style/Caption1Secondary"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="@dimen/grid_1"
                android:background="@drawable/click_indicator_light_masked"
                android:gravity="center"
                android:text="@string/Facebook_login_disclaimer_update" />

            <Button
                android:id="@+id/login_button"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="@dimen/grid_1"
                android:layout_marginBottom="@dimen/grid_1"
                android:text="@string/login_buttons_log_in_email" />

            <Button
                android:id="@+id/sign_up_button"
                style="@style/BorderButton"
                android:layout_width="match_parent"
                android:layout_marginTop="@dimen/grid_1"
                android:text="@string/signup_button_email" />

            <com.google.android.material.textview.MaterialTextView
                android:id="@+id/disclaimer_text_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="@dimen/grid_1"
                android:layout_marginBottom="@dimen/grid_2"
                android:gravity="center_horizontal"
                android:text="@string/login_tout_disclaimer_agree_to_terms_html"
                android:textAppearance="@style/Caption1Primary"
                android:textColor="@color/text_secondary" />

        </LinearLayout>

    </LinearLayout>

</ScrollView>


text:
#ifndef KeyedCodingValueCF_h
#define KeyedCodingValueCF_h

#include "KeyedCodingValue.h"
#include <wtf/RetainPtr.h>

namespace WebKit {

RetainPtr<CFTypeRef> toCFType(const KeyedCodingValue&);

} // namespace WebKit

#endif // KeyedCodingValueCF_h


text:
![](https://img.shields.io/github/release/azure/azure-documentdb-hadoop.svg)
![](https://img.shields.io/maven-central/v/com.microsoft.azure/azure-documentdb-hadoop.svg)
![](https://img.shields.io/github/issues/azure/azure-documentdb-hadoop.svg)

This project provides a client library in Java that allows Microsoft Azure DocumentDB to act as an input source or output sink for MapReduce, Hive and Pig jobs.

##Download
###Option 1: Via Github

To get the binaries of this library as distributed by Microsoft, ready for use within your project, you can use [GitHub releases](https://github.com/Azure/azure-documentdb-hadoop/releases).

###Option 2: Source Via Git

To get the source code of the connector via git just type:

    git clone git://github.com/Azure/azure-documentdb-hadoop.git

###Option 3: Source Zip

To download a copy of the source code, click "Download ZIP" on the right side of the page or click [here](https://github.com/Azure/azure-documentdb-hadoop/archive/master.zip).

###Option 4: Via Maven

To get the binaries of this library as distributed by Microsoft, ready for use within your project, you can use Maven.

    <dependency>
    	<groupId>com.microsoft.azure</groupId>
    	<artifactId>azure-documentdb-hadoop</artifactId>
    	<version>1.1.0</version>
    </dependency>

###Option 5: HDInsight

Install the DocumentDB Hadoop Connector onto HDInsight clusters through custom action scripts. Full instructions can be found [here](https://azure.microsoft.com/documentation/articles/documentdb-run-hadoop-with-hdinsight/).

##Requirements
* Java Development Kit 7

##Supported Versions
* Apache Hadoop & YARN 2.4.0
    * Apache Pig 0.12.1
    * Apache Hive & HCatalog 0.13.1
* Apache Hadoop & YARN 2.6.0
    * Apache Pig 0.14.0
    * Apache Hive $ HCatalog 0.14.0
* HDI 3.1 ([Getting started with HDInsight](https://azure.microsoft.com/documentation/articles/documentdb-run-hadoop-with-hdinsight/))
* HDI 3.2

## Dependencies
* Microsoft Azure DocumentDB Java SDK 1.1.0 (com.microsoft.azure / azure-documentdb / 1.1.0)

When using Hive:
* OpenX Technologies JsonSerde 1.3.1-SNAPSHOT (org.openx.data / json-serde-parent / 1.3.1-SNAPSHOT)
    GitHub repo can be found [here](https://github.com/rcongiu/Hive-JSON-Serde)

Please download the jars and add them to your build path.

##Usage

To use this client library with Azure DocumentDB, you need to first [create an account](http://azure.microsoft.com/en-us/documentation/articles/documentdb-create-account/).

###MapReduce

#####Configuring input and output from DocumentDB Example
```Java
    // Import Hadoop Connector Classes
    import com.microsoft.azure.documentdb.Document;
    import com.microsoft.azure.documentdb.hadoop.ConfigurationUtil;
    import com.microsoft.azure.documentdb.hadoop.DocumentDBInputFormat;
    import com.microsoft.azure.documentdb.hadoop.DocumentDBOutputFormat;
    import com.microsoft.azure.documentdb.hadoop.DocumentDBWritable;

    // Set Configurations
    Configuration conf = new Configuration();
    final String host = "Your DocumentDB Endpoint";
    final String key = "Your DocumentDB Primary Key";
    final String dbName = "Your DocumentDB Database Name";
    final String inputCollNames = "Your DocumentDB Input Collection Name[s]";
    final String outputCollNames = "Your DocumentDB Output Collection Name[s]";
    final String query = "[Optional] Your DocumentDB Query";
    final String outputStringPrecision = "[Optional] Number of bytes to use for String indexes"
    final String offerType = "[Optional] Your performance level for Output Collection Creations";
    final String upsert = "[Optional] Bool to disable or enable document upsert";

    conf.set(ConfigurationUtil.DB_HOST, host);
    conf.set(ConfigurationUtil.DB_KEY, key);
    conf.set(ConfigurationUtil.DB_NAME, dbName);
    conf.set(ConfigurationUtil.INPUT_COLLECTION_NAMES, inputCollNames);
    conf.set(ConfigurationUtil.OUTPUT_COLLECTION_NAMES, outputCollNames);
    conf.set(ConfigurationUtil.QUERY, query);
    conf.set(ConfigurationUtil.OUTPUT_STRING_PRECISION, outputStringPrecision);
    conf.set(ConfigurationUtil.OUTPUT_COLLECTIONS_OFFER, offerType);
    conf.set(ConfigurationUtil.UPSERT, upsert);
```

Full MapReduce sample can be found [here](https://github.com/Azure/azure-documentdb-hadoop/blob/master/samples/MapReduceTutorial.java).

###Hive
#####Loading data from DocumentDB Example
```Java
    CREATE EXTERNAL TABLE DocumentDB_Hive_Table( COLUMNS )
    STORED BY 'com.microsoft.azure.documentdb.hive.DocumentDBStorageHandler'
    tblproperties (
        'DocumentDB.endpoint' = 'Your DocumentDB Endpoint',
        'DocumentDB.key' = 'Your DocumentDB Primary Key',
        'DocumentDB.db' = 'Your DocumentDB Database Name',
        'DocumentDB.inputCollections' = 'Your DocumentDB Input Collection Name[s]',
        'DocumentDB.query' = '[Optional] Your DocumentDB Query' );
```

#####Storing data to DocumentDB Example
```Java
    CREATE EXTERNAL TABLE Hive_DocumentDB_Table( COLUMNS )
    STORED BY 'com.microsoft.azure.documentdb.hive.DocumentDBStorageHandler'
    tblproperties (
        'DocumentDB.endpoint' = 'Your DocumentDB Endpoint',
        'DocumentDB.key' = 'Your DocumentDB Primary Key',
        'DocumentDB.db' = 'Your DocumentDB Database Name',
        'DocumentDB.outputCollections' = 'Your DocumentDB Output Collection Name[s]',
        '[Optional] DocumentDB.outputStringPrecision' = '[Optional] Number of bytes to use for String indexes',
        '[Optional] DocumentDB.outputCollectionsOffer' = '[Optional] Your performance level for Output Collection Creations',
        '[Optional] DocumentDB.upsert' = '[Optional] Bool to disable or enable document upsert');
    INSERT INTO TABLE Hive_DocumentDB_Table
```
Full Hive sample can be found [here](https://github.com/Azure/azure-documentdb-hadoop/blob/master/samples/Hive_Tutorial.hql).

###Pig
#####Loading data from DocumentDB Example
```Java
    LOAD 'Your DocumentDB Endpoint'
    USING com.microsoft.azure.documentdb.hadoop.pig.DocumentDBLoader(
        'Your DocumentDB Primary Key',
        'Your DocumentDB Database Name',
        'Your DocumentDB Input Collection Name[s]',
        '[Optional] Your DocumentDB SQL Query' );
```

#####Storing data to DocumentDB Example
```Java
    STORE data  INTO 'DocumentDB Endpoint'
    USING com.microsoft.azure.documentdb.hadoop.pig.DocumentDBStorage(
        'DocumentDB Primary Key',
        'DocumentDB Database Name',
        'DocumentDB Output Collection Name[s]',
        '[Optional] Your performance level for Output Collection Creations',
        '[Optional] Number of bytes to use for String indexes',
        '[Optional] Bool to disable or enable document upsert');
```
Full Pig sample can be found [here](https://github.com/Azure/azure-documentdb-hadoop/blob/master/samples/Pig_Tutorial.pig).

##Remarks
* When outputting to DocumentDB, your output collection will require capacity for an [additional stored procedure](http://azure.microsoft.com/en-us/documentation/articles/documentdb-limits/). The stored procedure will remain in your collection for reuse.
* The Hadoop Connector automatically sets your indexes to range indexes with max precision on strings and numbers. More information can be found [here](http://azure.microsoft.com/en-us/documentation/articles/documentdb-indexing-policies/).
* Connector supports configurable *upsert* option. *Upsert* configuration is automatically set to *true* and will overwrite documents within the same collection with the same *id*.
* Reads and writes to DocumentDB will be counted against your provisioned throughput for each collection.
* Output to DocumentDB collections is done in batch round robin.
* Connector supports configurable *offer* option. *Offer* configuration allows users to set the [performance tier](http://azure.microsoft.com/en-us/documentation/articles/documentdb-performance-levels/) of their newly creation collections (this does not apply when outputting to an already existing collection). The offer types are **S1**, **S2** and **S3**.

##Need Help?

Be sure to check out the Microsoft Azure [Developer Forums on MSDN](https://social.msdn.microsoft.com/forums/azure/en-US/home?forum=AzureDocumentDB) or the [Developer Forums on Stack Overflow](http://stackoverflow.com/questions/tagged/azure-documentdb) if you have trouble with the provided code. Also, check out our [tutorial](http://azure.microsoft.com/en-us/documentation/articles/documentdb-run-hadoop-with-hdinsight/) for more information.

##Contribute Code or Provide Feedback

If you would like to become an active contributor to this project please follow the instructions provided in [Azure Projects Contribution Guidelines](http://azure.github.io/guidelines.html).

If you encounter any bugs with the library please file an issue in the [Issues](https://github.com/Azure/azure-documentdb-hadoop/issues) section of the project.

##Learn More
* [DocumentDB with HDInsight Tutorial](https://azure.microsoft.com/documentation/articles/documentdb-run-hadoop-with-hdinsight/)
* [Official Hadoop Documentation](http://hadoop.apache.org/docs/current/hadoop-project-dist/hadoop-common/ClusterSetup.html)
* [Azure Developer Center](http://azure.microsoft.com/en-us/develop/java/)
* [Azure DocumentDB Service](http://azure.microsoft.com/en-us/documentation/services/documentdb/)
* [Azure DocumentDB Team Blog](http://blogs.msdn.com/b/documentdb/)


text:
from .database import *

def command(bot, session, author, message):
    tokens  = message.tokens()
    command = tokens[0].split('@')

    try:
        if command[1] != bot.metadata.username:
            return None
    except:
        pass

    if command[0] == '/slap':
        return slap(session, author, tokens)

    elif command[0] == '/mind':
        return mind(bot)

    elif command[0] == '/explain':
        return explain(bot)

    return None

def slap(session, author, tokens):
    if author.user_name != '':
        actor = '@' + author.user_name
    else:
        actor = author.first_name

    try:
        target = tokens[1]
    except:
        target = '#schizo'

    obj = ' '.join(tokens[2:])

    if obj != '':
        new_slap           = Slap()
        new_slap.author_id = author.id
        new_slap.object    = obj
        session.merge(new_slap)

    else:
        obj = Slap.fetch_random(session).object

    message         = Message()
    message.type    = Message.TYPE_TEXT
    message.content = '*{} slaps {} around a bit with {}'.format(actor, target, obj)
    return message

def mind(bot):
    mind = []
    for word, ttl in bot.mind.data.items():
        mind.append((ttl, word))
    mind.sort(key=lambda item: item[0], reverse=True)

    if len(mind) == 0:
        content = 'Calma aí, acabei de acordar!'

    else:
        content = 'TTL\tWORD\n'
        for (ttl, word) in mind:
            content += '{:02d}\t{}\n'.format(ttl, word)

    message         = Message()
    message.type    = Message.TYPE_TEXT
    message.content = content
    return message

explain_kw = {
    'mentions_me':   lambda stack: 'Me chamaram',
    'random_answer': lambda stack: 'Tava lendo o chat',

    'from_mind':     lambda stack: 'estava pensando em "{}"'.format(stack.pop()),
    'from_text':     lambda stack: 'falaram isso: "{}"'.format(stack.pop()),

    'response_mind':     lambda stack: 'pensava em "{}"'.format(explain_kw[stack.pop()]),
    'response_random':   lambda stack: 'nem li nada',
    'response_document': lambda stack: 'me lembrou uma imagem',
    'response_sticker':  lambda stack: 'quis responder com um sticker',
    'response_text':     lambda stack: 'quis enviar uma mensagem',

    'fetch_document': lambda stack: 'procurei por algo com "{}"'.format(stack.pop()),
    'fetch_sticker':  lambda stack: 'tentei achar um relacionado com "{}"'.format(stack.pop()),
    'fetch_word':     lambda stack: 'usei a palavra "{}"'.format(stack.pop()),
    'fetch_random':   lambda stack: 'respondi qualquer coisa',

    'random_document': lambda stack: 'não achei. Aí enviei qualquer coisa',
    'random_sticker':  lambda stack: 'não tinha. Mandei o primeiro que eu vi',
    'random_word':     lambda stack: 'não sabia nada sobre isso. Acabei falando qualquer merda aí',

    'period':      lambda stack: 'tranquilamente',
    'exclamation': lambda stack: 'excitada',
    'question':    lambda stack: 'intrigada',

    'nothing': lambda stack: 'Nem falei nada.',
    'error':   lambda stack: 'TELEGRAM ERROR: {}'.format(stack.pop),
}

def explain(bot):
    try:
        stack = bot.last_response.why
    except:
        stack = [ 'nothing' ]
    segments = []

    try:
        while True:
            index = stack.pop()

            try:
                func = explain_kw[index]
            except:
                # Keyword not found, just dump the stack as text.
                segments.append('EXPLAIN STACK ERROR: ' + index)
                while True:
                    segments.append(stack.pop())

            segments.append(func(stack))
    except:
        pass

    last = segments.pop()
    rest = ', '.join(segments)

    if rest == '':
        response = last + '.'
    else:
        response = rest + ' e ' + last + '.'

    message         = Message()
    message.type    = Message.TYPE_TEXT
    message.content = response
    return message


text:
<?php $this->load->view('includes/header') ?>

    <?php $this->load->view('includes/outsidemenu'); ?>

                  <?php if ($this->session->userdata('type') == 'admin'): ?>
                    <form class="" action="index.html" method="post">
                        Government Agency
                        <input type="text" name="office" class="form-control" value="">
                        Contact No.
                        <input type="text" name="number" class="form-control" value="">
                        <input type="submit" name="name" class="btn btn-primary pull-right margin-top-5px" value="Add" style="margin-bottom:10px;">

                    </form>
                  <?php endif; ?>

                            Government Agency
                            Contact

                        <?php
                            $h = $this->db->get('hotlines')->result_array();

                            foreach ($h as $hotline) {
                                ?>

                                <?php  echo $hotline['office']; ?>
                                <?php echo $hotline['num'] ?>

                        <?php } ?>

    <?php
        $this->load->view('forms/login');
        $this->load->view('includes/footer');
     ?>


text:
/* global define */
/* global afterEach, beforeEach, describe, it */

define([
  'shared',
  'sulfur/schema/qname',
  'sulfur/schema/type/simple/derived',
  'sulfur/schema/type/simple/primitive',
  'sulfur/schema/type/simple/restricted'
], function (shared, QName, DerivedType, PrimitiveType, RestrictedType) {

  'use strict';

  var expect = shared.expect;
  var sinon = shared.sinon;
  var returns = shared.returns;

  describe('sulfur/schema/type/simple/derived', function () {

    var type;
    var qname;
    var base;
    var valueType;
    var facets;

    beforeEach(function () {
      qname = QName.create('foo', 'urn:example:bar');
      base = PrimitiveType.create({
        qname: QName.create('x', 'urn:example:y'),
        valueType: {},
        facets: { toArray: returns([]) }
      });
      valueType = {};
      facets = { toArray: returns([]) };
      type = DerivedType.create(
        { base: base,
          qname: qname,
          valueType: valueType,
          facets: facets
        });
    });

    it("should be derived from sulfur/schema/type/simple/restricted", function () {
      expect(RestrictedType).to.be.prototypeOf(DerivedType);
    });

    describe('#initialize()', function () {

      var sandbox;

      beforeEach(function () {
        sandbox = sinon.sandbox.create();
      });

      afterEach(function () {
        sandbox.restore();
      });

      it("should call sulfur/schema/type/simple/restricted#initialize() with the base and facets", function () {
        var spy = sandbox.spy(RestrictedType.prototype, 'initialize');
        var type = DerivedType.create({ base: base, facets: facets });
        expect(spy)
          .to.be.calledOn(type)
          .to.be.calledWith(
            sinon.match.same(base),
            sinon.match.same(facets));
      });

    });

    describe('#qname', function () {

      it("should return the qualified name", function () {
        expect(type.qname).to.equal(qname);
      });

    });

    describe('#valueType', function () {

      it("should return the value type", function () {
        expect(type.valueType).to.equal(valueType);
      });

    });

    describe('#namedBaseOrSelf', function () {

      it("should return this", function () {
        expect(type.namedBaseOrSelf).to.equal(type);
      });

    });

  });

});


text:
// ==========================================================================
// $Id: SegmentVisualizer.java 10 2010-12-15 04:53:00Z a.solis.m $
// Base class of all operations

package gui;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.awt.event.MouseEvent;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.Map.Entry;
import java.util.Vector;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import events.SweepAlgorithmListener;
import structures.EventPoint;
import structures.EventPointList;
import structures.Segment;
import structures.YTreeStructure;
import util.Graphics.Animation;
import util.Graphics.CountBlinkingShape;
import util.Graphics.Drawable;
import util.Graphics.DrawableShape;
import util.Graphics.TemporalDrawableShape;

 public class SegmentVisualizer extends JPanel implements java.awt.event.MouseListener,
 													   java.awt.event.MouseMotionListener,
 													   SweepAlgorithmListener{

	private static final long serialVersionUID = 1L;
	public Point2D.Double _first;
	public boolean        _press = false;
	public boolean        EDITMODE = false;
	public boolean 		  AMODE = false;
	private Color  BC;
	private Stroke BS;
	private BasicStroke dashedStroke = new BasicStroke(1.0f,
			  					  					   BasicStroke.CAP_BUTT,
			  					  					   BasicStroke.JOIN_MITER,
			  					  					   5.0f,new float[]{ 4.0f }, 0.0f);

	public double scale;
	private LinkedList<Segment> segments = new LinkedList<Segment>();
	private Vector<Drawable> elements = new Vector<Drawable>();
	private LinkedList<Animation> animations = new LinkedList<Animation>();
	private double  vertical_line =0;

	public void AddShape(Drawable shape){
		elements.add(shape);
		repaint();
	}
	public void AddAnimation(Animation a){
		animations.add(a);
	}
	public void AddSegment(Segment s){
		Line2D.Double l = new Line2D.Double(s.FIRST().X(),s.FIRST().Y(),
							                s.LAST().X(),s.LAST().Y());
		segments.add(s);
		AddShape(new DrawableShape(this,l));
	}

	public void setSegments(LinkedList<Segment> segments){
		elements.clear();
		animations.clear();
		for (Segment s: segments){
			Line2D.Double l = new Line2D.Double(s.FIRST().X(),s.FIRST().Y(),
												s.LAST().X(),s.LAST().Y());

			elements.add(new DrawableShape(this,l));
		}
		this.segments = segments;
		vertical_line = 0;
		repaint();
	}
	public LinkedList<Segment> getSegments(){
		return segments;
	}
	public SegmentVisualizer(){
		this(1.);
	}
	// Construct
	public SegmentVisualizer(double scale) {
	    this.setScale(scale);
	    this.addMouseListener(this);
	    this.addMouseMotionListener(this);

	}

	// Methods
	public void paintComponent(Graphics g) {
		super.paintComponent(g);

	    g.setColor(Color.WHITE);
	    g.fillRect(0, 0, getWidth(), getHeight());
	    shapes(((Graphics2D)g));
	}

	// Painting Shapes on top of the background image
	public void shapes(Graphics2D g){

		g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, // Anti-alias!
				   		   RenderingHints.VALUE_ANTIALIAS_ON);
		BC  = g.getColor();
		BS = g.getStroke();
		g.setStroke(dashedStroke);
		g.setColor (Color.red);
		g.draw( new Line2D.Double(vertical_line,0,vertical_line,getHeight()));
		g.setStroke(BS);
		g.setColor(BC);
		if (_press){
			  BC  = g.getColor();
			  BS = g.getStroke();
			  g.setStroke(dashedStroke);
			  g.setColor (Color.gray);
			  Point _second = new Point(MouseInfo.getPointerInfo().getLocation().x,
										MouseInfo.getPointerInfo().getLocation().y);
			  SwingUtilities.convertPointFromScreen(_second, this);
			  g.draw(new java.awt.geom.Line2D.Double(_first,_second));
			  g.setStroke(BS);
			  g.setColor(BC);
		}
    	Enumeration<Drawable> e = elements.elements();
        Drawable obj;

        while (e.hasMoreElements()) { // step through all vector elements
           obj = (Drawable) e.nextElement();
           obj.setScale(scale);
           obj.draw(g);
           if ( obj instanceof TemporalDrawableShape){
        	   if (((TemporalDrawableShape) obj).Remove()) elements.remove(obj);

           }

        }
        if (animations.size() >0){
        	if (animations.get(0).Remove()) animations.poll();
	        animations.get(0).startAnimation();
	        animations.get(0).draw(g);

        }
        BC  = g.getColor();
		BS = g.getStroke();
		g.setColor(Color.black);
        for (Segment s: segments){
        	g.drawString(s.getName(),(int) s.FIRST().X()- (s.getName().length()*8),(int) s.FIRST().Y());
        }
		g.setStroke(BS);
		g.setColor(BC);
    }

	public void setScale(double scale) {
	    this.scale = scale;
	    setPreferredSize(new Dimension((int) (getWidth() * scale), (int) (getHeight() * scale)));
	    revalidate();
	    repaint();
	}

	public double getScale() {
	    return scale;
	}

	@Override
	public void mouseClicked(MouseEvent e) {

	}

	@Override
	public void mouseEntered(MouseEvent e) {

	}

	@Override
	public void mouseExited(MouseEvent e) {

	}

	@Override
	public void mousePressed(MouseEvent e) {

		if (EDITMODE){
			_press = true;
			_first = new Point2D.Double((double)e.getX(),(double)e.getY());

		}
	}

	@Override
	public void mouseReleased(MouseEvent e) {

		if (EDITMODE){
			Point2D.Double _second = new Point2D.Double(e.getX(),e.getY());
			if (_first.distanceSq(_second)>9){
				Segment s = new Segment(_first.x,_first.y,e.getX(),e.getY());
				this.AddSegment(s);
			}
			_press = false;
		}
	}

	@Override
	public void mouseDragged(MouseEvent e) {

		if (EDITMODE){
		Point _second = new Point(MouseInfo.getPointerInfo().getLocation().x,
				MouseInfo.getPointerInfo().getLocation().y);
		SwingUtilities.convertPointFromScreen(_second, this);
		this.repaint(Math.min((int)_first.x, _second.x)-100,
					 Math.min((int)_first.y, _second.y)-100,
					 Math.abs((int)_first.x- _second.x)+200,
					 Math.abs((int)_first.y- _second.y)+200);
		}
	}

	@Override
	public void mouseMoved(MouseEvent e) {

	}

	@Override
	public void newEventPointDetected(EventPoint e) {
		double diameter = 6;
		DrawableShape bS = new DrawableShape(this, new java.awt.geom.Ellipse2D.Double(e.X()-diameter/2,e.Y()-diameter/2,diameter,diameter));
		this.AddShape(bS);

	}

	@Override
	public void lineMoved(Entry<EventPoint, EventPointList>  v) {

		vertical_line = v.getKey().X();
		double diameter = 8;
		EventPoint k = v.getKey();
		CountBlinkingShape p = new CountBlinkingShape(this, new java.awt.geom.Ellipse2D.Double(
															k.X()-diameter/2,
															k.Y()-diameter/2,
															diameter,
															diameter));
		p.fillable = true;
		p.setColor(Color.red);
		this.AddShape(p);
		repaint();
	}

	@Override
	public void treeChanged(YTreeStructure tree) {

	}

	@Override
	public void intersectionFound(Entry<EventPoint, EventPointList> d) {

		if (AMODE){
			LinkedList<DrawableShape> list = new LinkedList<DrawableShape>();
			BasicStroke bs = new BasicStroke(2.f);
			for (Segment s: d.getValue().UCL()){
				DrawableShape l = new DrawableShape(this, new java.awt.geom.Line2D.Double(
						s.FIRST().X(),
						s.FIRST().Y(),
						s.LAST().X(),
						s.LAST().Y()));
				l.setColor(Color.BLUE);
				l.setStroke(bs);
				list.add(l);

			double diameter = 8;
			EventPoint k = d.getKey();

			DrawableShape p = new DrawableShape(this, new java.awt.geom.Ellipse2D.Double(
																k.X()-diameter/2,
																k.Y()-diameter/2,
																diameter,
																diameter));
			p.fillable = true;
			p.setColor(Color.red);
			list.add(p);

		}
			Animation an = new Animation(this,list);

		this.AddAnimation(an);

		}
	}

	@Override
	public void intersectionPair(Segment s1, Segment s2) {

		if (AMODE){
			BasicStroke bs = new BasicStroke(2.f);
			DrawableShape l = new DrawableShape(this, new java.awt.geom.Line2D.Double(
					s1.FIRST().X(),
					s1.FIRST().Y(),
					s1.LAST().X(),
					s1.LAST().Y()));
			l.setColor(Color.red);
			l.setStroke(bs);
			DrawableShape l2 = new DrawableShape(this, new java.awt.geom.Line2D.Double(
					s2.FIRST().X(),
					s2.FIRST().Y(),
					s2.LAST().X(),
					s2.LAST().Y()));
			l2.setColor(Color.green);
			l2.setStroke(bs);
			LinkedList<DrawableShape> list = new LinkedList<DrawableShape>();
			list.add(l);
			list.add(l2);
			Animation an = new Animation(this, list);
			this.AddAnimation(an);

		}
	}
	public void Clear() {
		segments.clear();
		elements.clear();
		animations.clear();
		vertical_line = 0;
		repaint();
	}
	@Override
	public void lineEnded() {
		vertical_line = getWidth();
		repaint();
	}

    }


text:
app.directive('exampleDirective', function() {
    return {
        scope: {
            someScopeVarFromParentWithTwoWay: '=',
            someScopeVarFromParentOneWay: '@'
        },
        restrict: 'E',
        require: 'distributeTransclude',
        controller: function($interval) {
            var _this = this;
            $interval(function() {
                _this.someScopeVarFromParentWithTwoWay = 'someScopeVarFromParentWithTwoWay changed inside the directive' + Date.now();
            }, 200);
        },
        controllerAs: 'vm',
        bindToController: true,
        templateUrl: 'example.directive.template.html'
    };
});


text:
"""
hyper/common/connection
~~~~~~~~~~~~~~~~~~~~~~~

Hyper's HTTP/1.1 and HTTP/2 abstraction layer.
"""
from .exceptions import TLSUpgrade, HTTPUpgrade
from ..http11.connection import HTTP11Connection
from ..http20.connection import HTTP20Connection
from ..tls import H2_NPN_PROTOCOLS, H2C_PROTOCOL

class HTTPConnection(object):
    """
    An object representing a single HTTP connection to a server.

    This object behaves similarly to the Python standard library's
    ``HTTPConnection`` object, with a few critical differences.

    Most of the standard library's arguments to the constructor are not
    supported by hyper. Most optional parameters apply to *either* HTTP/1.1 or
    HTTP/2.

    :param host: The host to connect to. This may be an IP address or a
        hostname, and optionally may include a port: for example,
        ``'http2bin.org'``, ``'http2bin.org:443'`` or ``'127.0.0.1'``.
    :param port: (optional) The port to connect to. If not provided and one
        also isn't provided in the ``host`` parameter, defaults to 80.
    :param secure: (optional) Whether the request should use TLS.
        Defaults to ``False`` for most requests, but to ``True`` for any
        request issued to port 443.
    :param window_manager: (optional) The class to use to manage flow control
        windows. This needs to be a subclass of the
        :class:`BaseFlowControlManager
        <hyper.http20.window.BaseFlowControlManager>`. If not provided,
        :class:`FlowControlManager <hyper.http20.window.FlowControlManager>`
        will be used.
    :param enable_push: (optional) Whether the server is allowed to push
        resources to the client (see
        :meth:`get_pushes() <hyper.HTTP20Connection.get_pushes>`).
    :param ssl_context: (optional) A class with custom certificate settings.
        If not provided then hyper's default ``SSLContext`` is used instead.
    :param proxy_host: (optional) The proxy to connect to.  This can be an IP
        address or a host name and may include a port.
    :param proxy_port: (optional) The proxy port to connect to. If not provided
        and one also isn't provided in the ``proxy_host`` parameter, defaults
        to 8080.
    :param proxy_headers: (optional) The headers to send to a proxy.
    """
    def __init__(self,
                 host,
                 port=None,
                 secure=None,
                 window_manager=None,
                 enable_push=False,
                 ssl_context=None,
                 proxy_host=None,
                 proxy_port=None,
                 proxy_headers=None,
                 timeout=None,
                 **kwargs):

        self._host = host
        self._port = port
        self._h1_kwargs = {
            'secure': secure, 'ssl_context': ssl_context,
            'proxy_host': proxy_host, 'proxy_port': proxy_port,
            'proxy_headers': proxy_headers, 'enable_push': enable_push,
            'timeout': timeout
        }
        self._h2_kwargs = {
            'window_manager': window_manager, 'enable_push': enable_push,
            'secure': secure, 'ssl_context': ssl_context,
            'proxy_host': proxy_host, 'proxy_port': proxy_port,
            'proxy_headers': proxy_headers,
            'timeout': timeout
        }

        # Add any unexpected kwargs to both dictionaries.
        self._h1_kwargs.update(kwargs)
        self._h2_kwargs.update(kwargs)

        self._conn = HTTP11Connection(
            self._host, self._port, **self._h1_kwargs
        )

    def request(self, method, url, body=None, headers=None):
        """
        This will send a request to the server using the HTTP request method
        ``method`` and the selector ``url``. If the ``body`` argument is
        present, it should be string or bytes object of data to send after the
        headers are finished. Strings are encoded as UTF-8. To use other
        encodings, pass a bytes object. The Content-Length header is set to the
        length of the body field.

        :param method: The request method, e.g. ``'GET'``.
        :param url: The URL to contact, e.g. ``'/path/segment'``.
        :param body: (optional) The request body to send. Must be a bytestring
            or a file-like object.
        :param headers: (optional) The headers to send on the request.
        :returns: A stream ID for the request, or ``None`` if the request is
            made over HTTP/1.1.
        """

        headers = headers or {}

        try:
            return self._conn.request(
                method=method, url=url, body=body, headers=headers
            )
        except TLSUpgrade as e:
            # We upgraded in the NPN/ALPN handshake. We can just go straight to
            # the world of HTTP/2. Replace the backing object and insert the
            # socket into it.
            assert e.negotiated in H2_NPN_PROTOCOLS

            self._conn = HTTP20Connection(
                self._host, self._port, **self._h2_kwargs
            )
            self._conn._sock = e.sock

            # Because we skipped the connecting logic, we need to send the
            # HTTP/2 preamble.
            self._conn._send_preamble()

            return self._conn.request(
                method=method, url=url, body=body, headers=headers
            )

    def get_response(self, *args, **kwargs):
        """
        Returns a response object.
        """
        try:
            return self._conn.get_response(*args, **kwargs)
        except HTTPUpgrade as e:
            # We upgraded via the HTTP Upgrade mechanism. We can just
            # go straight to the world of HTTP/2. Replace the backing object
            # and insert the socket into it.
            assert e.negotiated == H2C_PROTOCOL

            self._conn = HTTP20Connection(
                self._host, self._port, **self._h2_kwargs
            )

            self._conn._connect_upgrade(e.sock)
            # stream id 1 is used by the upgrade request and response
            # and is half-closed by the client

            return self._conn.get_response(1)

    # The following two methods are the implementation of the context manager
    # protocol.
    def __enter__(self):  # pragma: no cover
        return self

    def __exit__(self, type, value, tb):  # pragma: no cover
        self._conn.close()
        return False  # Never swallow exceptions.

    # Can anyone say 'proxy object pattern'?
    def __getattr__(self, name):
        return getattr(self._conn, name)


text:
<!--
  ~ Copyright 2015 Red Hat, Inc. and/or its affiliates.
  ~
  ~ 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.
  -->

<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
             xmlns:b="urn:import:org.gwtbootstrap3.client.ui"
        >

    <b:FormGroup>
        <b:FormLabel ui:field="valuePairLabel" addStyleNames="col-md-4" showRequiredIndicator="true" />
        <b:Column size="MD_8">
            <b:TextBox ui:field="textBox"/>
            <b:HelpBlock ui:field="helpBlock"/>
        </b:Column>
    </b:FormGroup>

</ui:UiBinder>