text:
package com.evolveum.midpoint.schema.statistics;

import com.evolveum.midpoint.prism.Objectable;
import com.evolveum.midpoint.prism.PrismContext;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.PrismObjectDefinition;
import com.evolveum.midpoint.prism.polystring.PolyString;
import com.evolveum.midpoint.xml.ns._public.common.common_3.*;

import javax.xml.namespace.QName;

/**
 * @author Pavol Mederly
 */
public class StatisticsUtil {

    public static String getDisplayName(ShadowType shadow) {
        String objectName = PolyString.getOrig(shadow.getName());
        QName oc = shadow.getObjectClass();
        String ocName = oc != null ? oc.getLocalPart() : null;
        return objectName + " (" + shadow.getKind() + " - " + shadow.getIntent() + " - " + ocName + ")";
    }

    public static <O extends ObjectType> String getDisplayName(PrismObject<O> object) {
        if (object == null) {
            return null;
        }
        O objectable = object.asObjectable();
        if (objectable instanceof UserType) {
            return "User " + ((UserType) objectable).getFullName() + " (" + object.getName() + ")";
        } else if (objectable instanceof RoleType) {
            return "Role " + ((RoleType) objectable).getDisplayName() + " (" + object.getName() + ")";
        } else if (objectable instanceof OrgType) {
            return "Org " + ((OrgType) objectable).getDisplayName() + " (" + object.getName() + ")";
        } else if (objectable instanceof ShadowType) {
            return "Shadow " + getDisplayName((ShadowType) objectable);
        } else {
            return objectable.getClass().getSimpleName() + " " + objectable.getName();
        }
    }

    public static QName getObjectType(ObjectType objectType, PrismContext prismContext) {
        if (objectType == null) {
            return null;
        }
        PrismObjectDefinition def = objectType.asPrismObject().getDefinition();
        if (def == null) {
            Class<? extends Objectable> clazz = objectType.asPrismObject().getCompileTimeClass();
            if (clazz == null) {
                return null;
            }
            def = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(clazz);
            if (def == null) {
                return ObjectType.COMPLEX_TYPE;
            }
        }
        return def.getTypeName();
    }

	public static boolean isEmpty(EnvironmentalPerformanceInformationType info) {
		return info == null ||
				(isEmpty(info.getProvisioningStatistics())
				&& isEmpty(info.getMappingsStatistics())
				&& isEmpty(info.getNotificationsStatistics())
				&& info.getLastMessage() == null
				&& info.getLastMessageTimestamp() == null);
	}

	public static boolean isEmpty(NotificationsStatisticsType notificationsStatistics) {
		return notificationsStatistics == null || notificationsStatistics.getEntry().isEmpty();
	}

	public static boolean isEmpty(MappingsStatisticsType mappingsStatistics) {
		return mappingsStatistics == null || mappingsStatistics.getEntry().isEmpty();
	}

	public static boolean isEmpty(ProvisioningStatisticsType provisioningStatistics) {
		return provisioningStatistics == null || provisioningStatistics.getEntry().isEmpty();
	}

}


text:
'use strict';

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

var _classnames = require('classnames');

var _classnames2 = _interopRequireDefault(_classnames);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

module.exports = _react2['default'].createClass({
	displayName: 'SegmentedControl',

	propTypes: {
		className: _react2['default'].PropTypes.string,
		equalWidthSegments: _react2['default'].PropTypes.bool,
		onChange: _react2['default'].PropTypes.func.isRequired,
		options: _react2['default'].PropTypes.array.isRequired,
		type: _react2['default'].PropTypes.oneOf('default', 'muted', 'danger', 'info', 'primary', 'success', 'warning'),
		value: _react2['default'].PropTypes.string
	},

	getDefaultProps: function getDefaultProps() {
		return {
			type: 'default'
		};
	},

	onChange: function onChange(value) {
		this.props.onChange(value);
	},

	render: function render() {
		var _this = this;

		var componentClassName = (0, _classnames2['default'])('SegmentedControl', 'SegmentedControl--' + this.props.type, {
			'SegmentedControl--equal-widths': this.props.equalWidthSegments
		}, this.props.className);

		var options = this.props.options.map(function (op) {

			var buttonClassName = (0, _classnames2['default'])('SegmentedControl__button', {
				'is-selected': op.value === _this.props.value
			});

			return _react2['default'].createElement(
				'span',
				{ key: 'option-' + op.value, className: 'SegmentedControl__item' },
				_react2['default'].createElement(
					'button',
					{ type: 'button', onClick: _this.onChange.bind(_this, op.value), className: buttonClassName },
					op.label
				)
			);
		});

		return _react2['default'].createElement(
			'div',
			{ className: componentClassName },
			options
		);
	}
});

redpajama_set_name: RedPajamaGithub


text:
<?php namespace ZN\Image;
/**
 * ZN PHP Web Framework
 *
 * "Simplicity is the ultimate sophistication." ~ Da Vinci
 *
 * @package ZN
 * @license MIT [http://opensource.org/licenses/MIT]
 * @author  Ozan UYKUN [ozan@znframework.com]
 */

use ZN\Singleton;

class GDFilter
{
    /**
     * Applies the used filters belonging to the GD class.
     *
     * @param string $file
     * @param array  $filters
     */
    public static function apply($file, $filters)
    {
        if( ! empty($filters) )
        {
            $gd = self::getSingletonGDClass();

            $gd->canvas($file);

            foreach( $filters as $filter )
            {
                $method     = $filter[0];
                $parameters = $filter[1] ?? [];

                $gd->$method(...(array) $parameters);
            }

            $gd->generate(MimeTypeFinder::get($file), $file);
        }
    }

    /**
     * Protected get singleton GD class
     */
    protected static function getSingletonGDClass()
    {
        return Singleton::class('ZN\Image\GD');
    }
}


text: DROP TABLE :tablename;


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

namespace GogoKit.Models.Request
{
    [DataContract(Name = "base_barcode")]
    public class BaseBarcodeUpload
    {
        [DataMember(Name = "seat_ordinal")]
        public int? SeatOrdinal { get; set; }

        [DataMember(Name = "seat")]
        public string Seat { get; set; }

        [DataMember(Name = "row")]
        public string Row { get; set; }
    }

    [DataContract(Name = "barcode")]
    public class BarcodeUpload : BaseBarcodeUpload
    {
        [DataMember(Name = "barcode_values")]
        public string[] Values { get; set; }
    }

    [DataContract(Name = "barcode")]
    public class SellerListingBarcodeUpload : BaseBarcodeUpload
    {
        [DataMember(Name = "barcode_values_sha256_hashed")]
        public string[] BarcodeValuesSha256Hashed { get; set; }
    }

    [DataContract(Name = "barcode")]
    public class SaleBarcodeUpload : BaseBarcodeUpload
    {
        [DataMember(Name = "barcode_values")]
        public string[] BarcodeValues { get; set; }
    }
}


text:
"""
Modules required to work with ironic_discoverd:
    https://pypi.python.org/pypi/ironic-discoverd
"""

import eventlet
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import importutils

from ironic.common import exception
from ironic.common.i18n import _
from ironic.common.i18n import _LE
from ironic.common.i18n import _LI
from ironic.common import keystone
from ironic.common import states
from ironic.conductor import task_manager
from ironic.drivers import base

LOG = logging.getLogger(__name__)

discoverd_opts = [
    cfg.BoolOpt('enabled', default=False,
                help='whether to enable inspection using ironic-discoverd'),
    cfg.StrOpt('service_url',
               help='ironic-discoverd HTTP endpoint. If this is not set, the '
               'ironic-discoverd client default (http://127.0.0.1:5050) '
               'will be used.'),
    cfg.IntOpt('status_check_period', default=60,
               help='period (in seconds) to check status of nodes '
               'on inspection')
]

CONF = cfg.CONF
CONF.register_opts(discoverd_opts, group='discoverd')

ironic_discoverd = importutils.try_import('ironic_discoverd')
if ironic_discoverd:
    from ironic_discoverd import client

class DiscoverdInspect(base.InspectInterface):
    """In-band inspection via ironic-discoverd project."""

    @classmethod
    def create_if_enabled(cls, driver_name):
        """Create instance of DiscoverdInspect if it's enabled.

        Reports log warning with given driver_name if it's not.

        :return: DiscoverdInspect instance or None
        """
        if CONF.discoverd.enabled:
            return cls()
        else:
            LOG.info(_LI("Inspection via ironic-discoverd is disabled in "
                         "configuration for driver %s. To enable, change "
                         "[discoverd] enabled = True."), driver_name)

    def __init__(self):
        if not CONF.discoverd.enabled:
            raise exception.DriverLoadError(
                _('ironic-discoverd support is disabled'))

        if not ironic_discoverd:
            raise exception.DriverLoadError(
                _('ironic-discoverd Python module not found'))

        # NOTE(dtantsur): __version_info__ attribute appeared in 1.0.0
        version = getattr(ironic_discoverd, '__version_info__', (0, 2))
        if version < (1, 0):
            raise exception.DriverLoadError(
                _('ironic-discoverd version is too old: required >= 1.0.0, '
                  'got %s') % '.'.join(str(x) for x in version))

    def get_properties(self):
        """Return the properties of the interface.

        :returns: dictionary of <property name>:<property description> entries.
        """
        return {}  # no properties

    def validate(self, task):
        """Validate the driver-specific inspection information.

        If invalid, raises an exception; otherwise returns None.

        :param task: a task from TaskManager.
        """
        # NOTE(deva): this is not callable if discoverd is disabled
        #             so don't raise an exception -- just pass.
        pass

    def inspect_hardware(self, task):
        """Inspect hardware to obtain the hardware properties.

        This particular implementation only starts inspection using
        ironic-discoverd. Results will be checked in a periodic task.

        :param task: a task from TaskManager.
        :returns: states.INSPECTING
        """
        LOG.debug('Starting inspection for node %(uuid)s using '
                  'ironic-discoverd client %(version)s',
                  {'uuid': task.node.uuid, 'version':
                   ironic_discoverd.__version__})

        # NOTE(dtantsur): we're spawning a short-living green thread so that
        # we can release a lock as soon as possible and allow ironic-discoverd
        # to operate on a node.
        eventlet.spawn_n(_start_inspection, task.node.uuid, task.context)
        return states.INSPECTING

    @base.driver_periodic_task(spacing=CONF.discoverd.status_check_period,
                               enabled=CONF.discoverd.enabled)
    def _periodic_check_result(self, manager, context):
        """Periodic task checking results of inspection."""
        filters = {'provision_state': states.INSPECTING}
        node_iter = manager.iter_nodes(filters=filters)

        for node_uuid, driver in node_iter:
            try:
                # TODO(dtantsur): we need an exclusive lock only once
                # inspection is finished.
                with task_manager.acquire(context, node_uuid) as task:
                    _check_status(task)
            except (exception.NodeLocked, exception.NodeNotFound):
                continue

def _call_discoverd(func, uuid, context):
    """Wrapper around calls to discoverd."""
    # NOTE(dtantsur): due to bug #1428652 None is not accepted for base_url.
    kwargs = {}
    if CONF.discoverd.service_url:
        kwargs['base_url'] = CONF.discoverd.service_url
    return func(uuid, auth_token=context.auth_token, **kwargs)

def _start_inspection(node_uuid, context):
    """Call to discoverd to start inspection."""
    try:
        _call_discoverd(client.introspect, node_uuid, context)
    except Exception as exc:
        LOG.exception(_LE('Exception during contacting ironic-discoverd '
                          'for inspection of node %(node)s: %(err)s'),
                      {'node': node_uuid, 'err': exc})
        # NOTE(dtantsur): if acquire fails our last option is to rely on
        # timeout
        with task_manager.acquire(context, node_uuid) as task:
            task.node.last_error = _('Failed to start inspection: %s') % exc
            task.process_event('fail')
    else:
        LOG.info(_LI('Node %s was sent to inspection to ironic-discoverd'),
                 node_uuid)

def _check_status(task):
    """Check inspection status for node given by a task."""
    node = task.node
    if node.provision_state != states.INSPECTING:
        return
    if not isinstance(task.driver.inspect, DiscoverdInspect):
        return

    LOG.debug('Calling to discoverd to check status of node %s',
              task.node.uuid)

    # NOTE(dtantsur): periodic tasks do not have proper tokens in context
    task.context.auth_token = keystone.get_admin_auth_token()
    try:
        status = _call_discoverd(client.get_status, node.uuid, task.context)
    except Exception:
        # NOTE(dtantsur): get_status should not normally raise
        # let's assume it's a transient failure and retry later
        LOG.exception(_LE('Unexpected exception while getting '
                          'inspection status for node %s, will retry later'),
                      node.uuid)
        return

    if status.get('error'):
        LOG.error(_LE('Inspection failed for node %(uuid)s '
                      'with error: %(err)s'),
                  {'uuid': node.uuid, 'err': status['error']})
        node.last_error = (_('ironic-discoverd inspection failed: %s')
                           % status['error'])
        task.process_event('fail')
    elif status.get('finished'):
        LOG.info(_LI('Inspection finished successfully for node %s'),
                 node.uuid)
        task.process_event('done')


text:
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
 *
 * @package PhpMyAdmin
 */

/**
 *
 */
require_once './libraries/common.inc.php';

$GLOBALS['js_include'][] = 'export.js';
$GLOBALS['js_include'][] = 'codemirror/lib/codemirror.js';
$GLOBALS['js_include'][] = 'codemirror/mode/mysql/mysql.js';

/**
 * Gets tables informations and displays top links
 */
require_once './libraries/tbl_common.php';
$url_query .= '&goto=tbl_export.php&back=tbl_export.php';
require_once './libraries/tbl_info.inc.php';

// Dump of a table

$export_page_title = __('View dump (schema) of table');

// When we have some query, we need to remove LIMIT from that and possibly
// generate WHERE clause (if we are asked to export specific rows)

if (! empty($sql_query)) {
    // Parse query so we can work with tokens
    $parsed_sql = PMA_SQP_parse($sql_query);
    $analyzed_sql = PMA_SQP_analyze($parsed_sql);

    // Need to generate WHERE clause?
    if (isset($where_clause)) {

        $temp_sql_array = explode("where", strtolower($sql_query));

        // The fields which is going to select will be remain
        // as it is regardless of the where clause(s).
        // EX :- The part "SELECT `id`, `name` FROM `customers`"
        // will be remain same when representing the resulted rows
        // from the following query,
        // "SELECT `id`, `name` FROM `customers` WHERE id NOT IN
        //  ( SELECT id FROM companies WHERE name LIKE '%u%')"
        $sql_query = $temp_sql_array[0];

        // Append the where clause using the primary key of each row
        if (is_array($where_clause) && (count($where_clause) > 0)) {
            $sql_query .= ' WHERE (' . implode(') OR (', $where_clause) . ')';
        }

        if (!empty($analyzed_sql[0]['group_by_clause'])) {
            $sql_query .= ' GROUP BY ' . $analyzed_sql[0]['group_by_clause'];
        }
        if (!empty($analyzed_sql[0]['having_clause'])) {
            $sql_query .= ' HAVING ' . $analyzed_sql[0]['having_clause'];
        }
        if (!empty($analyzed_sql[0]['order_by_clause'])) {
            $sql_query .= ' ORDER BY ' . $analyzed_sql[0]['order_by_clause'];
        }
    } else {
        // Just crop LIMIT clause
        $sql_query = $analyzed_sql[0]['section_before_limit'] . $analyzed_sql[0]['section_after_limit'];
    }
    $message = PMA_Message::success();
}

/**
 * Displays top menu links
 */
require './libraries/tbl_links.inc.php';

$export_type = 'table';
require_once './libraries/display_export.lib.php';

/**
 * Displays the footer
 */
require './libraries/footer.inc.php';
?>


text:
<?php

namespace Hotpms\Http\Middleware;

use Closure;
use Hotpms\Menu;

class SetCurrentSection
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next, $currentRoute)
    {
    	$menuItem= Menu::where('route',$currentRoute)->first();

    	if($menuItem !== null){
    		$section= Menu::findOrFail($menuItem->id_section);
    		if($section->name == 'toplevel'){
    			session(['current_section' => $menuItem]);
    		}
    		else{
       			session(['current_section' => $section]);
    		}
    	}
        return $next($request);
    }
}


text:
<com.tle.beans.mime.MimeEntry>
  <id>216287</id>
  <institution>
    <id>215895</id>
    <uniqueId>0</uniqueId>
    <quota>0.0</quota>
    <enabled>true</enabled>
  </institution>
  <extensions class="list"/>
  <type>equella/ims-package</type>
  <attributes>
    <entry>
      <string>enabledViewers</string>
      <string>['downloadIms']</string>
    </entry>
    <entry>
      <string>PluginIconPath</string>
      <string>icons/ims.png</string>
    </entry>
  </attributes>
</com.tle.beans.mime.MimeEntry>


text:
require_relative './load_path'

require 'log'


text:
title: Coding software-based mutex algos for fun
summary: Rather than memorize the algos for my exam :)
tags: OS, kernel, python
category: programming
id: mutex
author: Saksham Sharma
------

I learnt a couple of nice scheduling algorithms in my Operating Systems class last semester. They seemed like an interesting bunch, but it was not generally clear whether their performance would be good.

Now, what better a way to understand them than by coding them up? <!--more--> So it began.

First off, those who know about [GIL](https://en.wikipedia.org/wiki/Global_interpreter_lock) would rather laugh at me when I tell you that I wrote the algorithms in Python.

> Multi-threading in Python? But Why ?!?!

Simple reason, I was looking to write code fast. After all, I had an exam I hadn't studied anything for (yes, this exam). Plus, I don't know, but might be that GIL isn't going to affect the output of this test significantly anyway (have not verified this yet).

So I went, and wrote a few classes (one for each algorithm):

## The algorithms

### Dekker's algorithm (2-thread)
``` python
class Dekker:
    def __init__(self):
        self.flag = [0, 0]
        self.turn = 0

    def lock(self, i):
        j = 1-i
        while self.flag[j]:
            if self.turn == j:
                self.flag[i] = 0
                while self.turn == j:
                    pass
                self.flag[i] = 1

    def unlock(self, i):
        j = 1-i
        self.turn = j
        self.flag[i] = 0
```

### Peterson's algorithm (2-thread)
``` python
Peterson:
    def __init__(self):
        self.flag = [0, 0]
        self.turn = 0

    def lock(self, i):
        j = 1-i
        self.flag[i] = 1
        self.turn = j
        while self.flag[j] and self.turn == j:
            pass

    def unlock(self, i):
        self.flag[i] = 0
```

### Lamport's bakery algorithm (n-thread)
``` python
class Lamport:
    def __init__(self, c):
        self.count = c
        self.ticket = [0]*c
        self.choosing = [0]*c

    def lock(self, i):
        self.choosing[i] = 1
        self.ticket[i] = max(self.ticket) + 1
        self.choosing[i] = 0
        for j in range(0, self.count):
            while self.choosing[j]:
                pass
            while (self.ticket[j] and
                   (self.ticket[j], j) < (self.ticket[i], i)):
                pass

    def unlock(self, i):
        self.ticket[i] = 0
```

## Testing, how?
So I made a simple function. It would grab the lock, increment the thread's counter (globally placed), print the new total count for all threads, and release the lock.

I wrote some clever python idioms, but that's irrelevant. What is relevant is the rate at which the counter increases for each thread. That could be throught of as a metric to quantify the performance of the algorithms.

## Results
I ran each algorithm for 5 seconds, and looked at the count of iterations of each process. Also, to note the presence of unfairness, or an initial bias, I also ran one for 10 seconds, but it did not have any noticeable effect. Also, since Dekker and Peterson only work for 2 threads, I also tested Lamport on 2 threads (highly unfair, I know).

|          | Thread 1 | Thread 2 |
|----------|----------|----------|
| Dekker   | 7415     | 7245     |
| Peterson | 116      | 114      |
| Lamport  | 119      | 117      |

Through this, it is quite clear who the winner is. Dekker seems to perform much faster than the other 2. Of course, it has the other issues of being more complicated, and of only supporting 2 threads. But the huge performance gap is no doubt remarkable.

This experiment was never intended to be of very high accuracy; why, it was hardly more than an exam time fun exercise. But a difference of this magnitude is certainly of interest, and what an in-depth look at the algorithms reveals, not completely unexpected.


text:
. ${ROOT_PATH}/utils/utils.sh
load_configs

usage() {
  echo "Usage:"
  echo "  $ deploy versions"
  echo ""
}

if [ $# -ge 1 ]; then
  usage
  exit 1
fi

echo "⇲ Retrieving deployed versions..."
echo ""

${ROOT_PATH}/cmds/run-remote.sh "versions" "${REMOTE_GIT_PATH}"


text:
using System.Collections.Generic;

namespace Coevery.Recipes.Models {
    public class RecipeJournal {
        public string ExecutionId { get; set; }
        public RecipeStatus Status { get; set; }
        public IEnumerable<JournalMessage> Messages { get; set; }
    }

    public class JournalMessage {
        public string Message { get; set; }
    }

    public enum RecipeStatus {
        Unknown,
        Started,
        Complete,
        Failed
    }
}


text:
/**
 * Created by Apurv on 4/19/2017.
 */
(function () {
    'use strict';
    var myApp=angular.module('myApp');
    myApp.controller('movieController',movieController);
    movieController.$inject=['mySer','restServices','$cookieStore'];
     function movieController( mySer,restServices,$cookieStore){
         var self = this;
         self.mov = mySer.getAllMovie();
         self.search='';
         self.jet=mySer.getUser();
         console.log($cookieStore.get('userName'));
         if(self.jet==='admin')
         {
             self.user=true;
         }
         else if($cookieStore.get('userName')==='admin')
         {
             self.user=true;
         }
         else
         {
             self.user=false;
         }
        console.log(self.mov);
         self.logout=function () {
             $cookieStore.remove('userName');

         };
                 fetchAllMovies1();
         function getAverage1(){
             console.log("fetchAllUsers1");
             restServices.getAverage(self.result)
                 .then(
                     function(d) {
                         console.log(d)
                         self.result1=d;
                         self.withAverage=[];
                         angular.forEach(d, function(v) {
                             angular.forEach(self.movie, function(t) {
                                 if(v.title==t.title) {
                                     t['average']= v.average;
                                     self.withAverage.push(t)
                                 }
                             })
                         });
                         mySer.set(self.withAverage);
                         console.log(self.withAverage);
                     },
                     function(errResponse){
                         console.error('Error while fetching Users');
                     }
                 );
         };
         function fetchAllMovies1(){
            console.log("fetchAllUsers1");
            restServices.fetchAllMovies()
                .then(
                    function(d) {
                        self.movie= d;
                        self.dataLoaded = true;
                        self.result = [];
                        angular.forEach(self.movie, function(v) {
                            if(v.title!=null) {
                                self.result.push(v.title);
                            }
                        });
                        console.log(self.result)
                        getAverage1();
                    },
                    function(errResponse){
                        console.error('Error while fetching Users');
                    }
                );
        };

};

})();


text:
package org.semanticweb.elk.reasoner.indexing.classes;

import org.semanticweb.elk.reasoner.indexing.model.IndexedClass;
import org.semanticweb.elk.reasoner.indexing.model.IndexedClassExpression;
import org.semanticweb.elk.reasoner.indexing.model.IndexedIndividual;
import org.semanticweb.elk.reasoner.indexing.model.IndexedObjectCache;
import org.semanticweb.elk.reasoner.indexing.model.IndexedObjectProperty;
import org.semanticweb.elk.reasoner.indexing.model.IndexedPropertyChain;

/**
 * An {@link IndexedObjectCache.ChangeListener} that does nothing; can be used
 * as a prototype to implement other listeners
 *
 * @author Yevgeny Kazakov
 *
 */
public class IndexedObjectCacheDummyChangeListener
		implements IndexedObjectCache.ChangeListener {

	@Override
	public void classAddition(IndexedClass cls) {
		// does nothing by default
	}

	@Override
	public void classRemoval(IndexedClass cls) {
		// does nothing by default
	}

	@Override
	public void individualAddition(IndexedIndividual ind) {
		// does nothing by default
	}

	@Override
	public void individualRemoval(IndexedIndividual ind) {
		// does nothing by default
	}

	@Override
	public void objectPropertyAddition(IndexedObjectProperty prop) {
		// does nothing by default
	}

	@Override
	public void objectPropertyRemoval(IndexedObjectProperty prop) {
		// does nothing by default
	}

	@Override
	public void classExpressionAddition(IndexedClassExpression expr) {
		// does nothing by default
	}

	@Override
	public void classExpressionRemoval(IndexedClassExpression expr) {
		// does nothing by default
	}

	@Override
	public void propertyChainAddition(IndexedPropertyChain chain) {
		// does nothing by default
	}

	@Override
	public void propertyChainRemoval(IndexedPropertyChain chain) {
		// does nothing by default
	}

}


text:
package io.strimzi.kafka.bridge.http;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.vertx.core.Handler;
import io.vertx.ext.web.RoutingContext;

/**
 * Represents an OpenApi operation with related logging
 */
public abstract class HttpOpenApiOperation implements Handler<RoutingContext> {

    protected final static String LOGGER_NAME_PREFIX = "http.openapi.operation.";

    protected Logger log;
    protected final HttpOpenApiOperations operationId;

    public HttpOpenApiOperation(HttpOpenApiOperations operationId) {
        this.operationId = operationId;
        this.log = LoggerFactory.getLogger(LOGGER_NAME_PREFIX + operationId.toString());
    }

    public abstract void process(RoutingContext routingContext);

    @Override
    public void handle(RoutingContext routingContext) {
        this.logRequest(routingContext);
        this.process(routingContext);
        this.logResponse(routingContext);
    }

    protected void logRequest(RoutingContext routingContext) {
        int requestId = System.identityHashCode(routingContext.request());
        routingContext.put("request-id", requestId);
        String msg = logRequestMessage(routingContext);
        log(msg);
    }

    protected void logResponse(RoutingContext routingContext) {
        String msg = logResponseMessage(routingContext);
        log(msg);
    }

    protected String logRequestMessage(RoutingContext routingContext) {
        int requestId = System.identityHashCode(routingContext.request());
        StringBuilder sb = new StringBuilder();
        if (log.isInfoEnabled()) {
            sb.append("[").append(requestId).append("] ").append(operationId.name())
                .append(" Request: from ")
                .append(routingContext.request().remoteAddress())
                .append(", method = ").append(routingContext.request().method())
                .append(", path = ").append(routingContext.request().path());

            if (log.isDebugEnabled()) {
                sb.append(", headers = ").append(routingContext.request().headers());
            }
        }
        return sb.toString();
    }

    protected String logResponseMessage(RoutingContext routingContext) {
        int requestId = routingContext.get("request-id");
        StringBuilder sb = new StringBuilder();
        if (log.isInfoEnabled()) {
            sb.append("[").append(requestId).append("] ").append(operationId.name())
                .append(" Response: ")
                .append(" statusCode = ").append(routingContext.response().getStatusCode())
                .append(", message = ").append(routingContext.response().getStatusMessage());

            if (log.isDebugEnabled()) {
                sb.append(", headers = ").append(routingContext.response().headers());
            }
        }
        return sb.toString();
    }

    private void log(String msg) {
        if (msg != null && !msg.isEmpty()) {
            log.info(msg);
        }
    }

    /**
     * @return the OpenAPI operation invoked
     */
    public HttpOpenApiOperations getOperationId() {
        return this.operationId;
    }
}


text:
const async = require('async');
const _ = require('lodash');
const parseCFSummaryIntoDeploymentConfig = require('../lib/parseCFSummaryIntoDeploymentConfig');

module.exports = (api) => {
  return (done) => {
    api.getSpaceSummary((err, summary) => {
      if (err) return done(err);

      if (!summary) return done(null);

      const deploymentConfig = parseCFSummaryIntoDeploymentConfig(summary);

      async.each(deploymentConfig.services, (service, callback) => {
        api.getServiceBindings({
          serviceInstanceGuid: service.guid
        }, (err, result) => {
          if (err) return callback(err);

          if (result.length > 0) {
            _.each(result, (b) => {
              var binding = _.find(deploymentConfig.serviceBindings, {
                serviceInstanceGuid: b.entity.service_instance_guid,
                appGuid: b.entity.app_guid
              });
              if (binding) {
                binding.guid = b.metadata.guid;
              }
            });
          }

          callback(null);
        });
      }, (err) => {
        if (err) return done(err);

        api.getDomains((err, domains) => {
          if (err) return done(err);
          api.domains = domains;

          deploymentConfig.domains = _.map(domains, (d) => {
            return { guid: d.metadata.guid, name: d.entity.name };
          });

          api.actualDeploymentConfig = deploymentConfig;

          api.getRoutes((err, routes) => {
            if (err) return done(err);

            const newRoutes = _.map(routes, (route) => {
              const dom = _.find(deploymentConfig.domains, { guid: route.entity.domain_guid });
              var foundRoute = _.find(deploymentConfig.routes, { guid: route.metadata.guid });
              if (foundRoute) {
                return foundRoute;
              }
              return {
                guid: route.metadata.guid,
                domain: dom ? dom.name : undefined,
                domainGuid: route.entity.domain_guid,
                hostname: route.entity.host,
                path: route.entity.path,
                port: route.entity.port
              };
            });
            api.routes = newRoutes;
            deploymentConfig.routes = newRoutes;

            api.actualDeploymentConfig = deploymentConfig;

            done(null, deploymentConfig);
          });
        });
      });
    });
  };
};


text:
package org.red5.server.api.stream;

import org.red5.server.api.scope.IScope;

/**
 * Interface for handlers that control access to stream publishing.
 *
 * @author The Red5 Project
 * @author Joachim Bauch (jojo@struktur.de)
 */
public interface IStreamPublishSecurity {

    /**
     * Check if publishing a stream with the given name is allowed.
     *
     * @param scope
     *            Scope the stream is about to be published in.
     * @param name
     *            Name of the stream to publish.
     * @param mode
     *            Publishing mode.
     * @return

     * True
     *

     *
     *         if publishing is allowed, otherwise
     *
     *

     * False
     *

     */
    public boolean isPublishAllowed(IScope scope, String name, String mode);

}


text:
<?php

namespace GoldenPlanet\WebpackBundle\Service;

use RuntimeException;

class ManifestPhpStorage
{
	private $manifestPath;

	public function __construct($manifestPath)
	{
		$this->manifestPath = $manifestPath;
	}

	/**
	 * Save `/cache/webpack-manifest.php`
	 *
	 * @param array $manifest
	 */
	public function saveManifest(array $manifest)
	{
		file_put_contents($this->manifestPath, '<?php return ' . var_export($manifest, true) . ';');
	}

	/**
	 * Execute `/cache/webpack-manifest.php`
	 *
	 * @return mixed
	 */
	public function requireManifest()
	{
		if (!file_exists($this->manifestPath)) {

			throw new RuntimeException(sprintf(
				'Manifest file not found: %s. %s',
				$this->manifestPath,
				'You must run webpack:compile or webpack:dev-server before twig can render webpack assets'
			));
		}

		return require $this->manifestPath;
	}
}


text:
[#]: collector: (lujun9972)
[#]: translator: ( )
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: subject: (Termtosvg – Record Your Terminal Sessions As SVG Animations In Linux)
[#]: via: (https://www.2daygeek.com/termtosvg-record-your-terminal-sessions-as-svg-animations-in-linux/)
[#]: author: (Magesh Maruthamuthu https://www.2daygeek.com/author/magesh/)

Termtosvg – Record Your Terminal Sessions As SVG Animations In Linux
======

By default everyone prefer history command to review/recall the previously entered commands in terminal.

But unfortunately, that shows only the commands that we ran and doesn't shows the commands output which was performed previously.

There are many utilities available in Linux to record the terminal session activity.

This tool will help us to record the users terminal activity, also will help us to identify other useful information from the output.

Also, we had written about few utilities in the past and today also we are going to discuss about the same kind of topic.

If you would like to check other utilities to record your Linux terminal session activity then you can give a try to **[Script Command][1]** and **[Terminalizer Tool][2]**.

But if you are looking for **[GIF Recorder][3]** then try **[Gifine][4]** , **[Kgif][5]** and **[Peek][6]** utilities.

Script is one of the best utility to record your terminal session on headless server.

Script is a Unix command line utility that records a terminal session (in other terms, It's record everything displayed on your terminal).

It stores the output in the current directory as a text file and the default file name is typescript.

### What is Termtosvg

Termtosvg is a Unix terminal recorder written in Python that renders your command line sessions as standalone SVG animations.

### Termtosvg Features

  * Produce lightweight and clean looking animations embeddable on a project page.
  * Custom color themes, terminal UI and animation controls via SVG templates.
  * Compatible with asciinema recording format.
  * It requires Python >= 3.5

### How to Install Termtosvg In Linux

It was written in Python and pip installation is a recommended method to install Termtosvg on Linux.

Make sure you should have installed python-pip package on your system. If no, use the following command to install it.

For Debian/Ubuntu users, use **[Apt Command][7]** or **[Apt-Get Command][8]** to install pip package.

```
$ sudo apt install python-pip
```

For Archlinux users, use **[Pacman Command][9]** to install pip package.

```
$ sudo pacman -S python-pip
```

For Fedora users, use **[DNF Command][10]** to install pip package.

```
$ sudo dnf install python-pip
```

For CentOS/RHEL users, use **[YUM Command][11]** to install pip package.

```
$ sudo yum install python-pip
```

For openSUSE users, use **[Zypper Command][12]** to install pip package.

```
$ sudo zypper install python-pip
```

Finally run the following **[pip command][13]** to install Termtosvg tool in Linux.

```
$ sudo pip3 install termtosvg pyte python-xlib svgwrite
```

### How to Record Your Terminal Session Using Termtosvg

Once you successfully installed Termtosvg. Just run the following command to start recording.

```
$ termtosvg
Recording started, enter "exit" command or Control-D to end
```

For testing purpose run few commands and see whether it's working fine or not.

```
$ uname -a
Linux daygeek-Y700 4.19.8-2-MANJARO #1 SMP PREEMPT Sat Dec 8 14:45:36 UTC 2018 x86_64 GNU/Linux
$ hostname
daygeek-Y700
$ cat /etc/*-release
Manjaro Linux
DISTRIB_ID=ManjaroLinux
DISTRIB_RELEASE=18.0
DISTRIB_CODENAME=Illyria
DISTRIB_DESCRIPTION="Manjaro Linux"
Manjaro Linux
NAME="Manjaro Linux"
ID=manjaro
ID_LIKE=arch
PRETTY_NAME="Manjaro Linux"
ANSI_COLOR="1;32"
HOME_URL="https://www.manjaro.org/"
SUPPORT_URL="https://www.manjaro.org/"
BUG_REPORT_URL="https://bugs.manjaro.org/"
$ free -g
free: Multiple unit options doesn't make sense.
$ free -m
free: Multiple unit options doesn't make sense.
$ pip3 --version
pip 18.1 from /usr/lib/python3.7/site-packages/pip (python 3.7)
```

Once you have done, simple press `CTRL+D` or type `exit` to stop the recording. The result will be saved in `/tmp` folder with a unique name.

```
$ exit
exit
Recording ended, SVG animation is /tmp/termtosvg_5waorper.svg
```

We can open the SVG file output with help of any web browser.

```
$ firefox /tmp/termtosvg_5waorper.svg
```

![][15]

--------------------------------------------------------------------------------

via: https://www.2daygeek.com/termtosvg-record-your-terminal-sessions-as-svg-animations-in-linux/

作者:[Magesh Maruthamuthu][a]
选题:[lujun9972][b]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)

本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出

[a]: https://www.2daygeek.com/author/magesh/
[b]: https://github.com/lujun9972
[1]: https://www.2daygeek.com/script-command-record-save-your-terminal-session-activity-linux/
[2]: https://www.2daygeek.com/terminalizer-a-tool-to-record-your-terminal-and-generate-animated-gif-images/
[3]: https://www.2daygeek.com/category/gif-recorder/
[4]: https://www.2daygeek.com/gifine-create-animated-gif-vedio-recorder-linux-mint-debian-ubuntu/
[5]: https://www.2daygeek.com/kgif-create-animated-gif-file-active-window-screen-recorder-capture-arch-linux-mint-fedora-ubuntu-debian-opensuse-centos/
[6]: https://www.2daygeek.com/peek-create-animated-gif-screen-recorder-capture-arch-linux-mint-fedora-ubuntu/
[7]: https://www.2daygeek.com/apt-command-examples-manage-packages-debian-ubuntu-systems/
[8]: https://www.2daygeek.com/apt-get-apt-cache-command-examples-manage-packages-debian-ubuntu-systems/
[9]: https://www.2daygeek.com/pacman-command-examples-manage-packages-arch-linux-system/
[10]: https://www.2daygeek.com/dnf-command-examples-manage-packages-fedora-system/
[11]: https://www.2daygeek.com/yum-command-examples-manage-packages-rhel-centos-systems/
[12]: https://www.2daygeek.com/zypper-command-examples-manage-packages-opensuse-system/
[13]: https://www.2daygeek.com/install-pip-manage-python-packages-linux/
[14]: data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7
[15]: https://www.2daygeek.com/wp-content/uploads/2018/12/Termtosvg-Record-Your-Terminal-Sessions-As-SVG-Animations-In-Linux-1.gif


text:
Argo allows you to setup API proxying rules as well. Below illustrates a few ways to setup proxies.

```JavaScript
var argo = require('../argo');

argo()
  .map('^/map$', function(server){
    server
      .target('http://api.usergrid.com/mtraining/sandbox')
  })
  .target('https://api.usergrid.com/mdobson/sandbox')
  .listen(3000);
```

A few things to note about this sample:
1. The `target` function will wire up proxy functionality for you. It will take care of the heavy lifting of putting together the backend server URL, and routing it to the specific server accordingly.
2. You can embed `target` functions under namespaces using `map`. It will still put everything together accordingly, but this will allow you to namespace proxies under routes.


text:
using System.Windows.Forms;

namespace LiveSplit.UI.Components
{
    public partial class PinConfimation : Form
    {
        public string Pin { get; set; }

        public PinConfimation()
        {
            InitializeComponent();

            txtPin.DataBindings.Add("Text", this, "Pin");
        }
    }
}


text:
require 'rails_helper'

RSpec.feature 'Users can watch and unwatch tickets' do
  let(:user) { FactoryGirl.create(:user) }
  let(:project) { FactoryGirl.create(:project) }
  let(:ticket) do
    FactoryGirl.create(:ticket, project: project, author: user)
  end

  before do
    assign_role!(user, 'viewer', project)
    login_as(user)
    visit project_ticket_path(project, ticket)
  end

  scenario 'successfully' do
    within('#watchers') do
      expect(page).to have_content user.email
    end

    click_link 'Unwatch'
    expect(page).to have_content 'You are no longer watching this ticket.'

    within('#watchers') do
      expect(page).to_not have_content user.email
    end

    click_link 'Watch'
    expect(page).to have_content 'You are now watching this ticket.'

    within('#watchers') do
      expect(page).to have_content user.email
    end
  end
end


text:
<?php namespace Cms;

use Codeception\Test\Unit;
use Gzero\Cms\Repositories\BlockReadRepository;
use Gzero\Core\Models\Language;
use Gzero\Core\Query\QueryBuilder;

class BlockReadRepositoryTest extends Unit {

    /** @var UnitTester */
    protected $tester;

    /** @var BlockReadRepository */
    protected $repository;

    protected function _before()
    {
        $this->repository = new BlockReadRepository();
    }

    /** @test */
    public function canPaginateResults()
    {
        $this->tester->haveBlocks([
            ['translations' => [['language_code' => 'en', 'title' => 'A title']]],
            ['translations' => [['language_code' => 'en', 'title' => 'B title']]],
            ['translations' => [['language_code' => 'en', 'title' => 'C title']]],
            ['translations' => [['language_code' => 'en', 'title' => 'D title']]]
        ]);

        $result = $this->repository->getMany(
            (new QueryBuilder)
                ->where('translations.is_active', '=', true)
                ->where('translations.language_code', '=', 'en')
                ->orderBy('translations.title', 'desc')
                ->setPageSize(2)
                ->setPage(2)
        );

        $this->assertEquals(2, $result->count());
        $this->assertEquals(2, $result->perPage());
        $this->assertEquals(2, $result->currentPage());
        $this->assertEquals('B title', $result->first()->translations->first()->title);
        $this->assertEquals('A title', $result->last()->translations->first()->title);
    }

    /** @test */
    public function getVisibleBlocksWithActiveTranslationInSpecifiedLanguage()
    {
        $language = new Language(['code' => 'en']);

        $block1 = $this->tester->haveBlock([
            'weight'       => 0,
            'is_active'    => true,
            'translations' => [
                [
                    'language_code' => 'en',
                    'title'         => 'First block title',
                    'is_active'     => true
                ]
            ]
        ]);

        $block2 = $this->tester->haveBlock([
            'weight'       => 1,
            'is_active'    => true,
            'translations' => [
                [
                    'language_code' => 'en',
                    'title'         => 'Second block title',
                    'is_active'     => false
                ]
            ]
        ]);

        $blocks      = $this->repository->getVisibleBlocks([$block1->id, $block2->id], $language);
        $block       = head($blocks->toArray());
        $translation = head($block['translations']);

        $this->assertEquals(1, count($blocks));
        $this->assertEquals('First block title', $translation['title']);
        $this->assertEquals('en', $translation['language_code']);
        $this->assertTrue($block['is_active']);
        $this->assertTrue($translation['is_active']);
    }

    /** @test */
    public function getVisibleBlocksWithoutActiveTranslationInSpecifiedLanguage()
    {
        $language = new Language(['code' => 'en']);

        $block1 = $this->tester->haveBlock([
            'weight'       => 0,
            'is_active'    => true,
            'translations' => [
                [
                    'language_code' => 'en',
                    'title'         => 'First block title',
                    'is_active'     => true
                ]
            ]
        ]);

        $block2 = $this->tester->haveBlock([
            'weight'       => 1,
            'filter'       => ['+' => ['1/*']],
            'is_active'    => false,
            'translations' => [
                [
                    'language_code' => 'en',
                    'title'         => 'Second block title',
                    'is_active'     => false
                ]
            ]
        ]);

        $blocks       = $this->repository->getVisibleBlocks([$block1->id, $block2->id], $language, false)->toArray();
        $block1       = head($blocks);
        $block2       = last($blocks);
        $translation1 = head($block1['translations']);
        $translation2 = head($block2['translations']);

        $this->assertEquals(2, count($blocks));
        $this->assertTrue($block1['is_active']);
        $this->assertEquals('First block title', $translation1['title']);
        $this->assertEquals('en', $translation1['language_code']);
        $this->assertTrue($translation1['is_active']);

        $this->assertFalse($block2['is_active']);
        $this->assertNull($translation2['title']);
        $this->assertNull($translation2['language_code']);
        $this->assertNull($translation2['is_active']);
    }
}


text:
<?php

namespace Pace\Facades;

use Pace\Client;
use Illuminate\Support\Facades\Facade;

class Pace extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return Client::class;
    }
}


text:
#import <Foundation/Foundation.h>
#import "AppBaseDelegate.h"

@interface NSObject(NewsAppDelegate)

-(UINavigationController *)appDelegate_navigationController;

-(AppBaseDelegate *)appDelegate_;
-(UIWindow *)appWindow_;

-(UIViewController *)current_present_viewcontroller;
-(UIViewController *)current_top_viewcontroller;

@end


text:
package org.apache.camel.component.grpc;

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

import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.support.SynchronizationAdapter;
import org.apache.camel.test.AvailablePortFinder;
import org.apache.camel.test.junit5.CamelTestSupport;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class GrpcProducerAsyncTest extends CamelTestSupport {

    private static final Logger LOG = LoggerFactory.getLogger(GrpcProducerAsyncTest.class);

    private static final int GRPC_TEST_PORT = AvailablePortFinder.getNextAvailable();
    private static final int GRPC_TEST_PING_ID = 1;
    private static final int GRPC_TEST_PONG_ID01 = 1;
    private static final int GRPC_TEST_PONG_ID02 = 2;
    private static final String GRPC_TEST_PING_VALUE = "PING";
    private static final String GRPC_TEST_PONG_VALUE = "PONG";

    private static Server grpcServer;
    private Object asyncPongResponse;

    @BeforeAll
    public static void startGrpcServer() throws Exception {
        grpcServer = ServerBuilder.forPort(GRPC_TEST_PORT).addService(new PingPongImpl()).build().start();
        LOG.info("gRPC server started on port {}", GRPC_TEST_PORT);
    }

    @AfterAll
    public static void stopGrpcServer() throws IOException {
        if (grpcServer != null) {
            grpcServer.shutdown();
            LOG.info("gRPC server stoped");
        }
    }

    @Test
    public void testPingSyncSyncMethodInvocation() throws Exception {
        LOG.info("gRPC PingSyncSync method test start");
        final CountDownLatch latch = new CountDownLatch(1);
        PingRequest pingRequest
                = PingRequest.newBuilder().setPingName(GRPC_TEST_PING_VALUE).setPingId(GRPC_TEST_PING_ID).build();

        // Testing sync service call with async style invocation
        template.asyncCallbackSendBody("direct:grpc-sync-sync", pingRequest, new SynchronizationAdapter() {

            @Override
            public void onComplete(Exchange exchange) {
                asyncPongResponse = exchange.getMessage().getBody();
                latch.countDown();
            }
        });
        latch.await(1, TimeUnit.SECONDS);

        assertNotNull(asyncPongResponse);
        assertTrue(asyncPongResponse instanceof List);

        @SuppressWarnings("unchecked")
        List<PongResponse> asyncPongResponseList = (List<PongResponse>) asyncPongResponse;
        assertEquals(1, asyncPongResponseList.size());
        assertEquals(GRPC_TEST_PING_ID, asyncPongResponseList.get(0).getPongId());
        assertEquals(GRPC_TEST_PING_VALUE + GRPC_TEST_PONG_VALUE, asyncPongResponseList.get(0).getPongName());
    }

    @Test
    public void testPingSyncAsyncMethodInvocation() throws Exception {
        LOG.info("gRPC PingSyncAsync method test start");
        final CountDownLatch latch = new CountDownLatch(1);
        PingRequest pingRequest
                = PingRequest.newBuilder().setPingName(GRPC_TEST_PING_VALUE).setPingId(GRPC_TEST_PING_ID).build();

        // Testing async service call
        template.asyncCallbackSendBody("direct:grpc-sync-async", pingRequest, new SynchronizationAdapter() {

            @Override
            public void onComplete(Exchange exchange) {
                asyncPongResponse = exchange.getMessage().getBody();
                latch.countDown();
            }
        });
        latch.await(1, TimeUnit.SECONDS);

        assertNotNull(asyncPongResponse);
        assertTrue(asyncPongResponse instanceof List);

        @SuppressWarnings("unchecked")
        List<PongResponse> asyncPongResponseList = (List<PongResponse>) asyncPongResponse;
        assertEquals(2, asyncPongResponseList.size());
        assertEquals(GRPC_TEST_PONG_ID01, asyncPongResponseList.get(0).getPongId());
        assertEquals(GRPC_TEST_PONG_ID02, asyncPongResponseList.get(1).getPongId());
        assertEquals(GRPC_TEST_PING_VALUE + GRPC_TEST_PONG_VALUE, asyncPongResponseList.get(0).getPongName());
    }

    @Test
    public void testPingAsyncSyncMethodInvocation() throws Exception {
        LOG.info("gRPC PingAsyncSync method test start");
        final CountDownLatch latch = new CountDownLatch(1);
        PingRequest pingRequest
                = PingRequest.newBuilder().setPingName(GRPC_TEST_PING_VALUE).setPingId(GRPC_TEST_PING_ID).build();

        // Testing async service call with async style invocation
        template.asyncCallbackSendBody("direct:grpc-async-sync", pingRequest, new SynchronizationAdapter() {

            @Override
            public void onComplete(Exchange exchange) {
                asyncPongResponse = exchange.getMessage().getBody();
                latch.countDown();
            }
        });
        latch.await(1, TimeUnit.SECONDS);

        assertNotNull(asyncPongResponse);
        assertTrue(asyncPongResponse instanceof List);

        @SuppressWarnings("unchecked")
        List<PongResponse> asyncPongResponseList = (List<PongResponse>) asyncPongResponse;
        assertEquals(1, asyncPongResponseList.size());
        assertEquals(GRPC_TEST_PING_ID, asyncPongResponseList.get(0).getPongId());
        assertEquals(GRPC_TEST_PING_VALUE + GRPC_TEST_PONG_VALUE, asyncPongResponseList.get(0).getPongName());
    }

    @Test
    public void testPingAsyncAsyncMethodInvocation() throws Exception {
        LOG.info("gRPC PingAsyncAsync method test start");
        final CountDownLatch latch = new CountDownLatch(1);
        PingRequest pingRequest
                = PingRequest.newBuilder().setPingName(GRPC_TEST_PING_VALUE).setPingId(GRPC_TEST_PING_ID).build();

        // Testing async service call with async style invocation
        template.asyncCallbackSendBody("direct:grpc-async-async", pingRequest, new SynchronizationAdapter() {

            @Override
            public void onComplete(Exchange exchange) {
                asyncPongResponse = exchange.getMessage().getBody();
                latch.countDown();
            }
        });
        latch.await(1, TimeUnit.SECONDS);

        assertNotNull(asyncPongResponse);
        assertTrue(asyncPongResponse instanceof List);

        @SuppressWarnings("unchecked")
        List<PongResponse> asyncPongResponseList = (List<PongResponse>) asyncPongResponse;
        assertEquals(1, asyncPongResponseList.size());
        assertEquals(GRPC_TEST_PING_ID, asyncPongResponseList.get(0).getPongId());
        assertEquals(GRPC_TEST_PING_VALUE + GRPC_TEST_PONG_VALUE, asyncPongResponseList.get(0).getPongName());
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() {
                from("direct:grpc-sync-sync").to(
                        "grpc://localhost:" + GRPC_TEST_PORT + "/org.apache.camel.component.grpc.PingPong?method=pingSyncSync");
                from("direct:grpc-sync-async").to("grpc://localhost:" + GRPC_TEST_PORT
                                                  + "/org.apache.camel.component.grpc.PingPong?method=pingSyncAsync");
                from("direct:grpc-async-sync").to("grpc://localhost:" + GRPC_TEST_PORT
                                                  + "/org.apache.camel.component.grpc.PingPong?method=pingAsyncSync");
                from("direct:grpc-async-async").to("grpc://localhost:" + GRPC_TEST_PORT
                                                   + "/org.apache.camel.component.grpc.PingPong?method=pingAsyncAsync");
            }
        };
    }

    /**
     * Test gRPC PingPong server implementation
     */
    static class PingPongImpl extends PingPongGrpc.PingPongImplBase {
        @Override
        public void pingSyncSync(PingRequest request, StreamObserver<PongResponse> responseObserver) {
            LOG.info("gRPC server received data from PingPong service PingId={} PingName={}", request.getPingId(),
                    request.getPingName());
            PongResponse response = PongResponse.newBuilder().setPongName(request.getPingName() + GRPC_TEST_PONG_VALUE)
                    .setPongId(request.getPingId()).build();
            responseObserver.onNext(response);
            responseObserver.onCompleted();
        }

        @Override
        public void pingSyncAsync(PingRequest request, StreamObserver<PongResponse> responseObserver) {
            LOG.info("gRPC server received data from PingAsyncResponse service PingId={} PingName={}", request.getPingId(),
                    request.getPingName());
            PongResponse response01 = PongResponse.newBuilder().setPongName(request.getPingName() + GRPC_TEST_PONG_VALUE)
                    .setPongId(GRPC_TEST_PONG_ID01).build();
            PongResponse response02 = PongResponse.newBuilder().setPongName(request.getPingName() + GRPC_TEST_PONG_VALUE)
                    .setPongId(GRPC_TEST_PONG_ID02).build();
            responseObserver.onNext(response01);
            responseObserver.onNext(response02);
            responseObserver.onCompleted();
        }

        @Override
        public StreamObserver<PingRequest> pingAsyncSync(StreamObserver<PongResponse> responseObserver) {
            StreamObserver<PingRequest> requestObserver = new StreamObserver<PingRequest>() {

                @Override
                public void onNext(PingRequest request) {
                    PongResponse response = PongResponse.newBuilder().setPongName(request.getPingName() + GRPC_TEST_PONG_VALUE)
                            .setPongId(request.getPingId()).build();
                    responseObserver.onNext(response);
                }

                @Override
                public void onError(Throwable t) {
                    LOG.info("Error in pingAsyncSync() " + t.getMessage());
                }

                @Override
                public void onCompleted() {
                    responseObserver.onCompleted();
                }
            };
            return requestObserver;
        }

        @Override
        public StreamObserver<PingRequest> pingAsyncAsync(StreamObserver<PongResponse> responseObserver) {
            StreamObserver<PingRequest> requestObserver = new StreamObserver<PingRequest>() {

                @Override
                public void onNext(PingRequest request) {
                    PongResponse response = PongResponse.newBuilder().setPongName(request.getPingName() + GRPC_TEST_PONG_VALUE)
                            .setPongId(request.getPingId()).build();
                    responseObserver.onNext(response);
                }

                @Override
                public void onError(Throwable t) {
                    LOG.info("Error in pingAsyncAsync() " + t.getMessage());
                }

                @Override
                public void onCompleted() {
                    responseObserver.onCompleted();
                }
            };
            return requestObserver;
        }
    }
}


text:
const {execSync, exec} = require('child_process');

const getLastWater = () =>{
    return parseInt(execSync(`tail -1 ~/.dotfiles/bitbar/water/log`))
}

let lastWater = getLastWater();
let now = new Date();

let icon = `💧`;

if(now.getDay() == 5 && 16 <= now.getHours() && now.getHours() < 20 ){
    icon = `:beer:`;
}

let distance = now.getTime() - lastWater;
let minutesPerDrop = 10;

if(distance > 0){
    let drops = Math.floor(distance / (1000 * 60 * minutesPerDrop));

    drops = drops > 6 ? 6 : drops;

    console.log(Array(drops).fill(icon).join(''));
    console.log('---');
    console.log('OKAY!|bash=~/.dotfiles/bitbar/water/log.sh terminal=false refresh=true');
}


text:
package org.solarvitamins;

import org.orekit.errors.OrekitException;

public class SunCalculatorApp {

	public static void main(String[] args) throws OrekitException {
		SolarElevationCalculator sec = new SolarElevationCalculator();
		System.out.println("Elevation = "
				+ sec.getElevation(0, 0, 0, System.currentTimeMillis()));
	}

}


text:
package com.facebook.buck.android;

import static com.facebook.buck.jvm.java.JavaCompilationConstants.ANDROID_JAVAC_OPTIONS;
import static com.facebook.buck.jvm.java.JavaCompilationConstants.DEFAULT_JAVA_CONFIG;
import static com.facebook.buck.jvm.java.JavaCompilationConstants.DEFAULT_JAVA_OPTIONS;

import com.facebook.buck.cli.FakeBuckConfig;
import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.jvm.java.JavaBuckConfig;
import com.facebook.buck.jvm.kotlin.KotlinBuckConfig;
import com.facebook.buck.jvm.scala.ScalaBuckConfig;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.rules.AbstractNodeBuilder;
import java.util.Optional;

public class RobolectricTestBuilder
    extends AbstractNodeBuilder<
        RobolectricTestDescriptionArg.Builder, RobolectricTestDescriptionArg,
        RobolectricTestDescription, RobolectricTest> {

  public static final AndroidLibraryCompilerFactory DEFAULT_ANDROID_COMPILER_FACTORY =
      new DefaultAndroidLibraryCompilerFactory(
          DEFAULT_JAVA_CONFIG,
          new ScalaBuckConfig(FakeBuckConfig.builder().build()),
          new KotlinBuckConfig(FakeBuckConfig.builder().build()));

  private RobolectricTestBuilder(BuildTarget target, JavaBuckConfig javaBuckConfig) {
    super(
        new RobolectricTestDescription(
            javaBuckConfig,
            DEFAULT_JAVA_OPTIONS,
            ANDROID_JAVAC_OPTIONS,
            /* testRuleTimeoutMs */ Optional.empty(),
            null,
            DEFAULT_ANDROID_COMPILER_FACTORY),
        target);
  }

  private RobolectricTestBuilder(BuildTarget target, ProjectFilesystem filesystem) {
    super(
        new RobolectricTestDescription(
            DEFAULT_JAVA_CONFIG,
            DEFAULT_JAVA_OPTIONS,
            ANDROID_JAVAC_OPTIONS,
            /* testRuleTimeoutMs */ Optional.empty(),
            null,
            DEFAULT_ANDROID_COMPILER_FACTORY),
        target,
        filesystem);
  }

  public static RobolectricTestBuilder createBuilder(BuildTarget target) {
    return new RobolectricTestBuilder(target, DEFAULT_JAVA_CONFIG);
  }

  public static RobolectricTestBuilder createBuilder(
      BuildTarget target, JavaBuckConfig javaBuckConfig) {
    return new RobolectricTestBuilder(target, javaBuckConfig);
  }

  public static RobolectricTestBuilder createBuilder(
      BuildTarget target, ProjectFilesystem filesystem) {
    return new RobolectricTestBuilder(target, filesystem);
  }

  public RobolectricTestBuilder addDep(BuildTarget rule) {
    getArgForPopulating().addDeps(rule);
    return this;
  }

  public RobolectricTestBuilder addProvidedDep(BuildTarget rule) {
    getArgForPopulating().addProvidedDeps(rule);
    return this;
  }
}


text:
import { IGitSource, IGithubSource, IImageSource, IAppDeploymentEnv, IAppCors } from ".";
import { IAppDeploymentRoute } from "./app-deployment-route";

export interface IAppDeploymentStaticSite {
  build_command: string;
  dockerfile_path: string;
  environment_slug: string;
  envs: IAppDeploymentEnv[]
  git: IGitSource;
  github: IGithubSource;
  image: IImageSource;
  instance_count: number;
  instance_size_slug: string;
  name: string;
  run_command: string;
  source_dir: string;
  output_dir: string;
  index_document: string;
  error_document: string;
  routes: IAppDeploymentRoute[];
  cors: IAppCors;
}


text:
@implementation ELNHTTPClient (RACExtensions)

- (RACSignal *)rac_sendRequest:(id<ELNHTTPRequest>)request
{
    @weakify(self);
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        @strongify(self);

        NSURLSessionTask *task = [self sendRequest:request withCompletion:^(id responseObject, NSError *error, ELNAPIResponseContext *context) {
            [subscriber sendNext:responseObject];

            if (error) {
                [subscriber sendError:error];
            } else {
                [subscriber sendCompleted];
            }
        }];

        return [RACDisposable disposableWithBlock:^{
            [task cancel];
        }];
    }];
}

@end


text:
package im.actor.core.api.rpc;
/*
 *  Generated by the Actor API Scheme generator.  DO NOT EDIT!
 */

import im.actor.runtime.bser.*;
import im.actor.runtime.collections.*;
import static im.actor.runtime.bser.Utils.*;
import im.actor.core.network.parser.*;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.NotNull;
import com.google.j2objc.annotations.ObjectiveCName;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
import im.actor.core.api.*;

public class ResponseGetCallInfo extends Response {

    public static final int HEADER = 0xa2e;
    public static ResponseGetCallInfo fromBytes(byte[] data) throws IOException {
        return Bser.parse(new ResponseGetCallInfo(), data);
    }

    private ApiPeer peer;
    private List<ApiGroupOutPeer> groups;
    private List<ApiUserOutPeer> users;
    private String eventBusId;

    public ResponseGetCallInfo(@NotNull ApiPeer peer, @NotNull List<ApiGroupOutPeer> groups, @NotNull List<ApiUserOutPeer> users, @NotNull String eventBusId) {
        this.peer = peer;
        this.groups = groups;
        this.users = users;
        this.eventBusId = eventBusId;
    }

    public ResponseGetCallInfo() {

    }

    @NotNull
    public ApiPeer getPeer() {
        return this.peer;
    }

    @NotNull
    public List<ApiGroupOutPeer> getGroups() {
        return this.groups;
    }

    @NotNull
    public List<ApiUserOutPeer> getUsers() {
        return this.users;
    }

    @NotNull
    public String getEventBusId() {
        return this.eventBusId;
    }

    @Override
    public void parse(BserValues values) throws IOException {
        this.peer = values.getObj(1, new ApiPeer());
        List<ApiGroupOutPeer> _groups = new ArrayList<ApiGroupOutPeer>();
        for (int i = 0; i < values.getRepeatedCount(2); i ++) {
            _groups.add(new ApiGroupOutPeer());
        }
        this.groups = values.getRepeatedObj(2, _groups);
        List<ApiUserOutPeer> _users = new ArrayList<ApiUserOutPeer>();
        for (int i = 0; i < values.getRepeatedCount(3); i ++) {
            _users.add(new ApiUserOutPeer());
        }
        this.users = values.getRepeatedObj(3, _users);
        this.eventBusId = values.getString(4);
    }

    @Override
    public void serialize(BserWriter writer) throws IOException {
        if (this.peer == null) {
            throw new IOException();
        }
        writer.writeObject(1, this.peer);
        writer.writeRepeatedObj(2, this.groups);
        writer.writeRepeatedObj(3, this.users);
        if (this.eventBusId == null) {
            throw new IOException();
        }
        writer.writeString(4, this.eventBusId);
    }

    @Override
    public String toString() {
        String res = "tuple GetCallInfo{";
        res += "}";
        return res;
    }

    @Override
    public int getHeaderKey() {
        return HEADER;
    }
}


text:
from __future__ import division
from collections import deque
import struct
import math
import sys

import pyaudio
import numpy as np

from sonicky.codec.conf import Settings
from sonicky.codec.ecc import EmptyEcc

class Decoder:
    def __init__(self, debug=True, coder=EmptyEcc(), setting=Settings()):
        self.win_len = 2 * int(setting.bit_duration * setting.rate / setting.chunk_size / 2)
        self.win_fudge = int(self.win_len / 2)
        self.buffer = deque()
        self.buf_len = self.win_len + self.win_fudge
        self.byte = []
        self.receivebytes = bytearray()
        self.idlecount = 0
        self.coder = coder
        self.do_quit = False
        self.character_callback = None
        self.idle_callback = None
        self.debug = debug
        self.setting = setting
        self.p = pyaudio.PyAudio()
        self.stream = self.p.open(format=pyaudio.paInt16,
                                  channels=1,
                                  rate=setting.rate,
                                  input=True,
                                  frames_per_buffer=setting.audiobuf_size)

    def listen(self):
        self.do_quit = False
        self.receivebytes = []

        while not self.do_quit:
            audiostr = self.stream.read(self.setting.chunk_size)
            self.audio = list(struct.unpack("%dh" % self.setting.chunk_size, audiostr))
            self.window()
            powerlist = np.array([self.goertzel(i) for i in self.setting.char_freq])
            base = self.goertzel(self.setting.baseline)
            self.update_state(powerlist, base)
            self.signal_to_bits()
            self.process_byte()
        return self.receivebytes

    def window(self):
        self.audio = [aud * win for aud, win in zip(self.audio, self.setting.window)]

    def goertzel(self, frequency):
        prev1 = prev2 = 0.0
        norm_freq = frequency / self.setting.rate
        coeff = 2 * math.cos(2 * math.pi * norm_freq)
        for sample in self.audio:
            s = sample + (coeff * prev1) - prev2
            prev2 = prev1
            prev1 = s
        power = (prev2 * prev2) + (prev1 * prev1) - (coeff * prev1 * prev2)
        return int(power) + 1  # prevents division by zero problems

    def update_state(self, powerlist, base):
        state = -3  # silent
        pw = powerlist / base
        th = np.array(self.setting.char_threshold)
        judge = pw > th
        pw[judge == False] = 0

        # Find the maximum value
        if sum(judge) > 0:
            state = int(np.argmax(pw) - 2)

        if len(self.buffer) >= self.buf_len:
            self.buffer.popleft()
        self.buffer.append(state)

    # Takes the raw noisy samples of -1/0/1 and finds the bitstream from it
    def signal_to_bits(self):
        if len(self.buffer) < self.buf_len:
            return

        buf = list(self.buffer)

        if self.debug:
            self.printbuf(buf)

        costs = [[] for i in range(19)]  #
        for i in range(self.win_fudge):
            win = buf[i: self.win_len + i]
            #
            costs[0].append(sum(x != 0 for x in win))
            costs[1].append(sum(x != 1 for x in win))
            costs[2].append(sum(x != 2 for x in win))
            costs[3].append(sum(x != 3 for x in win))
            costs[4].append(sum(x != 4 for x in win))
            costs[5].append(sum(x != 5 for x in win))
            costs[6].append(sum(x != 6 for x in win))
            costs[7].append(sum(x != 7 for x in win))
            costs[8].append(sum(x != 8 for x in win))
            costs[9].append(sum(x != 9 for x in win))
            costs[10].append(sum(x != 10 for x in win))
            costs[11].append(sum(x != 11 for x in win))
            costs[12].append(sum(x != 12 for x in win))
            costs[13].append(sum(x != 13 for x in win))
            costs[14].append(sum(x != 14 for x in win))
            costs[15].append(sum(x != 15 for x in win))
            costs[16].append(sum(x != -1 for x in win))
            costs[17].append(sum(x != -2 for x in win))
            costs[18].append(sum(x != -3 for x in win))
            #
        min_costs = [min(costs[i]) for i in range(19)]  #
        min_cost = min(min_costs)
        signal = min_costs.index(min_cost)
        fudge = costs[signal].index(min_cost)
        for i in range(self.win_len + fudge):
            self.buffer.popleft()

        # got a signal
        if signal < 16:  #
            self.byte.append(signal)

        # got charstart signal.
        elif signal == 16:  #
            signal = 's'
            self.byte = []

        # got charend signal
        elif signal == 17:  #
            signal = 'e'
            self.byte = []
            self.buffer = deque()
            self.quit()

        # If we get no signal, increment idlecount
        if signal == 18:  #
            self.idlecount += 1
        else:
            self.idlecount = 0
        if self.idlecount > self.setting.idle_limit and self.idle_callback:
            self.idlecount = 0
            self.idle_callback()

        if self.debug:
            if signal == 18:  #
                signal = '-'
            sys.stdout.write('')
            sys.stdout.write('|{}|\n'.format(signal))
            sys.stdout.flush()

    def process_byte(self):
        if len(self.byte) != self.coder.expected_size():
            return
        byte = self.coder.get_decoded_bytes(self.byte)
        if byte is not None:
            self.receivebytes.append(byte)  #
        self.byte = []

    def quit(self):
        self.do_quit = True

    def printbuf(self, buf):
        newbuf = ['-' if x is -3 else x for x in buf]  #
        newbuf = ['s' if x is -1 else x for x in newbuf]  #
        newbuf = ['e' if x is -2 else x for x in newbuf]  #
        print(repr(newbuf).replace(', ', ' ').replace('\'', ''))


text:
module Sphinxsearchlogic
  class Search
    module Implementation
      # Use like:
      #  Movie.sphinxsearchlogic(params[:search], :page => params[:page], :per_page => [:per_page])
      def sphinxsearchlogic(conditions = {}, pagination = {})
        conditions ||= {} # params[:search] might be nil
        conditions.merge!(pagination)
        # Merge array of hashes, but doesn't work if Hash value is an Array.
        # conditions = Hash[*args.collect {|h| h.to_a}.flatten]
        Search.new(self, scope(:find), conditions)
      end
    end

    # Is an invalid condition is used this error will be raised. Ex:
    #
    #   User.search(:unkown => true)
    #
    # Where unknown is not a valid named scope for the User model.
    class UnknownConditionError < StandardError
      def initialize(condition)
        msg = "The #{condition} is not a valid condition. You may only use conditions that map to a thinking sphinx named scope or attribute."
        super(msg)
      end
    end

    # class OutofboundsError < StandardError
    #   def initialize(page, per_page)
    #     msg = "The page #{page} is out of bounds. Using per_page #{per_page}."
    #     super(msg)
    #   end
    # end

    # Accessors that define this Search object.
    attr_accessor :klass, :current_scope, :with, :without, :with_all, :params, :conditions, :scopes, :all
    undef :id if respond_to?(:id)

    module Pagination
      attr_writer :page, :per_page, :max_matches

      def default_per_page
        default_per_page = 20
        default_per_page = klass.per_page if klass.respond_to?(:per_page)
        default_per_page
      end

      # Returns a set max_matches or 1000.
      def max_matches
        @max_matches || 1000
      end

      # Returns the last page we have in this search based on the max_matches.
      # So we don't get a Riddle error for an offset that is too high.
      def last_page
        (max_matches.to_f / per_page).ceil
      end

      def offset
        (page-1)*per_page
      end

      def page
        page = (@page || 1).to_i
        page = 1 if page < 1 # Fixes pages like -1 and 0.
        # Fix riddle error.. we always return the last page? Think should be handled by application!
        # However this isn't yet the case for pages > total_results.
        # raise OutofboundsError.new(page, per_page) if page > last_page
        page = last_page if page > last_page
        page
      end

      # Returns 20 by default (ThinkingSphinx/Riddle default)
      def per_page
        per_page = (@per_page || default_per_page).to_i
        per_page = default_per_page if per_page < 1 # Fixes per_page like -1 and 0.
        per_page
      end

      def pagination_options
        options = {}
        options[:page] = page
        options[:per_page] = per_page
        options
      end

    end
    include Pagination

    module Ordering

      attr_reader :order, :order_direction, :order_attribute

      # Sets the order. If the order is incorrect this won't be set. Similar to pagination the
      # defaults will be used.
      def order=(order)
        @order = order
        return if order.blank?
        if is_sphinx_scope?(order) # We first check for scopes since they might be named ascend_by_scopename.
          scopes[order.to_sym] = true
        elsif order.to_s =~ /^(ascend|descend)_by_(\w+)$/
          @order_direction = ($1 == 'ascend') ? :asc : :desc
          if is_sphinx_attribute?($2)
            @order_attribute = $2.to_sym
          elsif [:weight, :relevance, :rank, :id, :random, :geodist].include?($2.to_sym)
            @order_attribute = "@#{$2} #{@order_direction}"
          end
        end
      end

      def ordering_options
        if order_attribute.blank?
          {}
        elsif order_attribute.is_a?(Symbol)
          {
            :order => order_attribute,
            :sort_mode => order_direction
          }
        else
          {:order => order_attribute}
        end
      end

    end
    include Ordering

    # Creates a new search object for the given class. Ex:
    #
    #   Searchlogic::Search.new(User, {}, {:username_like => "bjohnson"})
    def initialize(klass, current_scope, params = {})
      @with = {}
      @without = {}
      @with_all = {}
      @conditions = {}
      @scopes = {}

      self.klass = klass
      raise "No Sphinx indexes found on #{klass.to_s}!" unless has_sphinx_index?
      self.current_scope = current_scope
      self.params = params if params.is_a?(Hash)
    end

    # Accepts a hash of conditions.
    def params=(values)
      values.each do |param, value|
        value.delete_if { |v| v.blank? } if value.is_a?(Array)
        next if value.blank?
        send("#{param}=", value)
      end
    end

    # Returns actual search results.
    #  Movie.sphinxsearchlogic.results
    def results
      Rails.logger.debug("Sphinxsearchlogic: #{klass.to_s}.search('#{all}', #{search_options.inspect})")
      if scopes.empty?
        klass.search(all, search_options)
      else
        cloned_scopes = scopes.clone # Clone scopes since we're deleting form the hash.
        # Get the first scope and call all others on this one..
        first_scope = cloned_scopes.keys.first
        first_args = cloned_scopes.delete(first_scope)
        result = klass.send(first_scope, first_args)
        # Call remaining scopes on this scope.
        cloned_scopes.each do |scope, args|
          result = result.send(scope, args)
        end
        result.search(all, search_options)
      end
    end

  # private

    # Handles (in order):
    # * with / without / with_all conditions (Filters)
    # * field conditions (Regular searches)
    # * scope conditions
    def method_missing(name, *args, &block)
      name = name.to_s
      if name =~ /^(\w+)=$/ # If we have a setter
        name = $1
        if name =~ /^with(out|_all)?_(\w+)$/
          attribute_name = $2.to_sym
          if is_sphinx_attribute?(attribute_name)
            # Put in with / without / with_all depending on what the regexp matched.
            if $1 == 'out'
              without[attribute_name] = type_cast(args.first, cast_type(attribute_name))
            elsif $1 == '_all'
              with_all[attribute_name] = type_cast(args.first, cast_type(attribute_name))
            else
              with[attribute_name] = type_cast(args.first, cast_type(attribute_name))
            end
          else
            raise UnknownConditionError.new(attribute_name)
          end
        elsif is_sphinx_field?(name)
          conditions[name.to_sym] = args.first
        elsif is_sphinx_scope?(name)
          scopes[name.to_sym] = args.first
        else
          # If we have an unknown setter..
          # raise UnknownConditionError.new(attribute_name)
          super
        end
      else
        if name =~ /^with(out|_all)?_(\w+)$/
          attribute_name = $2
          attribute_name = attribute_name.gsub(/_before_type_cast$/, '').to_sym
          if is_sphinx_attribute?(attribute_name)
            # Put in with / without / with_all depending on what the regexp matched.
            if $1 == 'out'
              without[attribute_name]
            elsif $1 == '_all'
              with_all[attribute_name]
            else
              with[attribute_name]
            end
          else
            raise UnknownConditionError.new(attribute_name)
          end
        elsif is_sphinx_field?(name)
          conditions[name.to_sym]
        elsif is_sphinx_scope?(name)
          scopes[name.to_sym]
        else
          # If we have something else than a setter..
          # raise UnknownConditionError.new(attribute_name)
          super
        end
      end
    end

    # Returns a hash for the ThinkingSphinx search method. Eg.
    #  {
    #    :with => {:year => 2001}
    #  }
    def attribute_filter_options
      options = {}
      options[:with] = with unless with.blank?
      options[:without] = without unless without.blank?
      options[:with_all] = with_all unless with_all.blank? # See http://www.mailinglistarchive.com/thinking-sphinx@googlegroups.com/msg00351.html
      options
    end

    # Returns a hash for the ThinkingSphinx search method. Eg.
    #  {
    #    :conditions => {:name => 'John'}
    #  }
    def search_options
      options = {}
      options[:conditions] = conditions unless conditions.blank?
      options.merge(attribute_filter_options).merge(ordering_options).merge(pagination_options)
    end

    # # cleanup_hash removes empty and nil stuff from params hashes.
    # def cleanup_hash(hash)
    #   hash.collect do |condition, value|
    #     value.delete_if { |v| v.blank? } if value.is_a?(Array)
    #     value unless value.blank?
    #   end.compact
    # end

    # Returns the ThinkingSphinx index for the klass we search on.
    def sphinx_index
      klass.define_indexes if klass.sphinx_indexes.blank?
      klass.sphinx_indexes.first
    end

    # Returns true if the class of this Search has a Sphinx index.
    def has_sphinx_index?
      sphinx_index.is_a?(ThinkingSphinx::Index)
    rescue
      false
    end

    # Returns particular ThinkingSphinx::Attribute.
    def sphinx_attribute(attribute_name)
      sphinx_index.attributes.find do |index_attribute|
        index_attribute.public? && index_attribute.unique_name.to_s =~ /^#{attribute_name}(_sort)?$/ # Also check for :sortable attributes (they are given prefix _sort)
      end
    end

    # Returns true if the class of this search has a public attribute with this name (or name_sort if field is :sortable).
    def is_sphinx_attribute?(attribute_name)
      !!sphinx_attribute(attribute_name)
    end

    # Returns true if the class of this search has a public field with this name.
    def is_sphinx_field?(field_name)
      !sphinx_index.fields.find do |index_field|
        index_field.public? && (index_field.unique_name.to_s == field_name.to_s)
      end.nil?
    end

    # Returns true if class of this search has a sphinx scope with this name.
    def is_sphinx_scope?(scope_name)
      klass.sphinx_scopes.include?(scope_name.to_sym)
    end

    # Returns the type we should type_cast a ThinkingSphinx::Attribute to, eg. :integer.
    def cast_type(name)
      sphinx_attribute(name).type
    end

    # type_cast method of Searchlogic plugin
    def type_cast(value, type)
      case value
      when Array
        value.collect { |v| type_cast(v, type) }
      else
        # Let's leverage ActiveRecord's type casting, so that casting is consistent
        # with the other models.
        column_for_type_cast = ::ActiveRecord::ConnectionAdapters::Column.new("", nil)
        column_for_type_cast.instance_variable_set(:@type, type)
        value = column_for_type_cast.type_cast(value)
        Time.zone && value.is_a?(Time) ? value.in_time_zone : value
      end
    end

  end
end


text:
    <fieldset class="fldSetClosestFacilityParameters row">
        <legend class="fieldSetLegend esriCTEllipsisFieldSet" title="${nls.captionClosestFacilityParameters}">
            ${nls.captionClosestFacilityParameters}</legend>

                    ${nls.lblClosestFacilityServiceUrl}

                    <button class="jimu-btn jimu-float-trailing jimu-leading-margin1 urlButton esriCTBtnEllipsis"
                        title="${nls.btnSet}" data-dojo-attach-point="onSetBtnClick">
                        ${nls.btnSet}</button>

                    ${nls.hintText.closestFacilityText}

                        ${nls.lblFacilitySearchDistance}

                        ${nls.hintText.facilitySearchDistanceText}

                        ${nls.lblImpedanceAttribute}

                        <select data-dojo-attach-point="selectInpedanceAttribute" data-dojo-type="dijit/form/Select">
                        </select>

                        ${nls.hintText.impedanceText}

                        ${nls.lblDefaultCutOffDistance}

                        ${nls.hintText.cuttOffDistanceText}

                        <input type="radio" name="attributeParameterSelection" data-dojo-type="dijit/form/RadioButton"
                            data-dojo-attach-point="travelModeRdb" />
                        ${nls.lblTravelMode}

                        <select data-dojo-type="dijit/form/Select" data-dojo-attach-point="travelModesList">
                        </select>

                        <input type="radio" name="attributeParameterSelection" data-dojo-type="dijit/form/RadioButton"
                            data-dojo-attach-point="customAttributeParameterRdb" />
                        ${nls.lblAttributeParameterValues}

                            ${nls.hintText.AttributeParameterValueText1}

                            ${nls.hintText.AttributeParameterValueText2}

    </fieldset>
    <fieldset class="fldSetServiceAreaParameters row">
        <legend class="fieldSetLegend esriCTEllipsisFieldSet" title="${nls.captiveAttributeLookup}">
            ${nls.captiveAttributeLookup}</legend>

                ${nls.lblAttributeParamLookup}

                <textarea class="esriCTAttributeTextArea" data-dojo-type="dijit/form/SimpleTextarea"
                    rows="4" cols="50" data-dojo-attach-point="txtAttributeParam" data-dojo-props='required:true,trim:true,disabled:false'>${nls.defaultDataDictionaryValue}</textarea>
                <button class="jimu-btn jimu-float-trailing jimu-leading-margin1 urlButton esriCTBtnEllipsis esriCTBtnRefresh"
                    title="${nls.btnRefresh}" data-dojo-attach-point="_onRefreshBtnClick">
                    ${nls.btnRefresh}</button>

                ${nls.hintText.lookupText}

                ${nls.hintText.lookupTextOnSet}

    </fieldset>
    <fieldset class="fldSetServiceAreaParameters row">
        <legend class="fieldSetLegend esriCTEllipsisFieldSet" title="${nls.captionServiceAreaParameters}">
            ${nls.captionServiceAreaParameters}</legend>

                    ${nls.lblBusinessesLayer}

                    <select data-dojo-attach-point="selectBusinessLayer" data-dojo-type="dijit/form/Select">
                    </select>

                    ${nls.hintText.bussinessesLayerText}

                    ${nls.lblFieldTobeDisplayed}

                    <select data-dojo-attach-point="selectbusinessList" data-dojo-type="dijit/form/Select">
                    </select>

                    ${nls.hintText.bussinessListText}

                        ${nls.lblBufferDistanceToGenerateServiceArea}

                        ${nls.hintText.bufferDistanceText}

                        ${nls.lblBufferUnits}

                        <select data-dojo-attach-point="selectBufferUnits" data-dojo-type="dijit/form/Select">
                        </select>

                        ${nls.hintText.bufferUnitsText}

    </fieldset>

            ${nls.lblAccessPointLayers}

                ${nls.hintText.accessPointLayerText}

                ${nls.hintText.allowUserAccessPointLayerSelectText}

            ${nls.lblForBox}

            ${nls.hintText.hintLabelForBox}

            ${nls.lblLengthUnits}

            <select data-dojo-attach-point="selectLengthUnits" data-dojo-type="dijit/form/Select"></select>

            ${nls.hintText.lengthUnitsText}

            ${nls.lblForExpression}

            ${nls.hintText.hintExpressionText}

            ${nls.lblForRouteLengthUnits}

            ${nls.hintText.routeLengthUnitText}

            ${nls.lblForRouteUnitLblPosition}

            <input type="radio" name="Before_After" value="Before" data-dojo-attach-point="inputRadioBefore"
                data-dojo-type="dijit/form/RadioButton" class="esriCTInputBeforeAfter" title="${nls.lblForRadioBtnBefore}" />

                ${nls.lblForRadioBtnBefore}
            <input type="radio" name="Before_After" value="After" data-dojo-attach-point="inputRadioAfter"
                data-dojo-type="dijit/form/RadioButton" class="esriCTInputBeforeAfter" title="${nls.lblForRadioBtnAfter}"
                checked />

                ${nls.lblForRadioBtnAfter}

            ${nls.hintText.resulUnitLabelPosition}

            ${nls.lblForRouteRoundingOption}

            <select data-dojo-attach-point="selectRoundingOption" data-dojo-type="dijit/form/Select">
                <option value="${nls.routeLengthroundingOption.twoDecimalValue}">${nls.routeLengthroundingOption.twoDecimalName}</option>
                <option value="${nls.routeLengthroundingOption.oneDecimalValue}">${nls.routeLengthroundingOption.oneDecimalName}</option>
                <option value="${nls.routeLengthroundingOption.noDecimalValue}">${nls.routeLengthroundingOption.noDecimalName}</option>
                <option value="${nls.routeLengthroundingOption.tenDecimalValue}">${nls.routeLengthroundingOption.tenDecimalName}</option>
                <option value="${nls.routeLengthroundingOption.hunderedDecimalValue}">${nls.routeLengthroundingOption.hunderedDecimalName}</option>
                <option value="${nls.routeLengthroundingOption.thousandDecimalValue}">${nls.routeLengthroundingOption.thousandDecimalName}</option>
            </select>

            ${nls.hintText.roundingOptionHintText}

    <fieldset class="fldSetServiceAreaParameters row">
        <legend class="fieldSetLegend esriCTEllipsisFieldSet" title="${nls.captionSaveResults}">
            ${nls.captionSaveResults}</legend>

                <select style="width: 100%" data-dojo-attach-point="selectSaveBusinessLayer" data-dojo-type="dijit/form/Select"
                    title="${nls.lblBusinessesLayer}">
                </select>

                    ${nls.hintText.bussinessLayerText}

                <select style="width: 100%" data-dojo-attach-point="selectSaveRouteLayer" data-dojo-type="dijit/form/Select"
                    title="${nls.lblRouteLayer}">
                </select>

                    ${nls.hintText.routeLayerText}

                    <select style="width: 100%" data-dojo-attach-point="selectSaveRouteLength" data-dojo-type="dijit/form/Select"
                        title="${nls.lblRouteLength}">
                    </select>

                        ${nls.hintText.routeLengthText}

                        <select style="width: 100%" data-dojo-attach-point="selectSaveBusinessCount" data-dojo-type="dijit/form/Select"
                            title="${nls.lblBusinessCount}">
                        </select>

                            ${nls.hintText.saveBussinessText}

                    <select style="width: 100%" data-dojo-attach-point="selectSaveRouteCost" data-dojo-type="dijit/form/Select"
                        title="${nls.lblRouteCost}">
                    </select>

                        ${nls.hintText.routeCostText}

                        ${nls.RoutLayerField}

                        <select style="width: 100%" data-dojo-attach-point="selectSaveRouteLayerField" data-dojo-type="dijit/form/Select"
                            title="${nls.RoutLayerField}">
                        </select>

                            ${nls.hintText.routeNameFieldText}

                        ${nls.BussinessLayerField}

                            <select style="width: 100%" data-dojo-attach-point="selectSaveBusinessLayerField"
                                data-dojo-type="dijit/form/Select" title="${nls.BussinessLayerField}">
                            </select>

                                ${nls.hintText.saveBusinessNameField}

    </fieldset>
    <fieldset class="fldSetServiceAreaParameters row">
        <legend class="fieldSetLegend esriCTEllipsisFieldSet" title="${nls.captionExportCSV}">
            ${nls.captionExportCSV}</legend>

            ${nls.hintText.exportToCSVText}

    </fieldset>
    <fieldset class="fldSetClosestFacilityParameters row">
        <legend class="fieldSetLegend esriCTEllipsisFieldSet" title="${nls.symbol.barrier}">
            ${nls.symbol.barrier}</legend>

                    ${nls.symbol.pointBarrierSymbol}

                    ${nls.symbol.lineBarrierSymbol}

                    ${nls.symbol.polygonBarrierSymbol}

    </fieldset>
    <fieldset class="fldSetClosestFacilityParameters row">
        <legend class="fieldSetLegend esriCTEllipsisFieldSet" title="${nls.symbol.location}">
            ${nls.symbol.location}</legend>

                ${nls.symbol.pointLocationSymbol}

    </fieldset>
    <fieldset class="fldSetClosestFacilityParameters row">
        <legend class="fieldSetLegend esriCTEllipsisFieldSet" title="${nls.symbol.route}">${nls.symbol.route}</legend>

    </fieldset>
    <fieldset class="fldSetClosestFacilityParameters row">
        <legend class="fieldSetLegend esriCTEllipsisFieldSet" title="${nls.symbol.buffer}">${nls.symbol.buffer}</legend>

    </fieldset>
    <fieldset class="fldSetClosestFacilityParameters row">
        <legend class="fieldSetLegend esriCTEllipsisFieldSet" title="${nls.highlighter.highlighterSection}">
            ${nls.highlighter.highlighterSection}</legend>

                ${nls.highlighter.imageUplaod}

                ${nls.hintText.selectImageHintText}

                ${nls.highlighter.imageHeight}

            <input data-dojo-attach-point="imageHeight" data-dojo-type="dijit/form/NumberSpinner"
                class="common-inputspin" value="100" data-dojo-props="smallDelta:1, constraints:{min:1,places:0,pattern: '#'}"
                title="${nls.highlighter.imageHeight}" />

                ${nls.highlighter.pixel}

                ${nls.hintText.imageHeightText}

                ${nls.highlighter.imageWidth}

            <input data-dojo-attach-point="imageWidth" data-dojo-type="dijit/form/NumberSpinner"
                class="common-inputspin" value="100" data-dojo-props="smallDelta:1, constraints:{min:1,places:0,pattern: '#'}"
                title="${nls.highlighter.imageWidth}" />

                ${nls.highlighter.pixel}

                ${nls.hintText.imageWidthText}

                ${nls.highlighter.imageHighlightTimeout}

            <input data-dojo-attach-point="highlighterImageTimeout" data-dojo-type="dijit/form/NumberSpinner"
                class="common-inputspin" value="1000" data-dojo-props="smallDelta:1000, constraints:{min:1,places:0,pattern: '#'}"
                title="${nls.highlighter.imageHighlightTimeout}" />

                ${nls.highlighter.milliseconds}

                ${nls.hintText.imageTimeoutText}

    </fieldset>


text:
package postgis

import (
	"database/sql"

	"github.com/pkg/errors"
)

// TxRouter routes inserts/deletes to TableTx
type TxRouter struct {
	Tables map[string]TableTx
	tx     *sql.Tx
}

func newTxRouter(pg *PostGIS, bulkImport bool) (*TxRouter, error) {
	txr := TxRouter{
		Tables: make(map[string]TableTx),
	}

	if bulkImport {
		for tableName, table := range pg.Tables {
			tt := NewBulkTableTx(pg, table)
			err := tt.Begin(nil)
			if err != nil {
				return nil, err
			}
			txr.Tables[tableName] = tt
		}
	} else {
		tx, err := pg.Db.Begin()
		if err != nil {
			return nil, errors.Wrap(err, "begin postgis transaction")
		}
		txr.tx = tx
		for tableName, table := range pg.Tables {
			tt := NewSynchronousTableTx(pg, table.FullName, table)
			err := tt.Begin(tx)
			if err != nil {
				return nil, errors.Wrapf(err, "begin postgis transaction for table %s", table.FullName)
			}
			txr.Tables[tableName] = tt
		}
		for tableName, table := range pg.GeneralizedTables {
			tt := NewSynchronousTableTx(pg, table.FullName, table)
			err := tt.Begin(tx)
			if err != nil {
				return nil, errors.Wrapf(err, "begin postgis transaction for generalized table %s", table.FullName)
			}
			txr.Tables[tableName] = tt
		}
	}

	return &txr, nil
}

func (txr *TxRouter) End() error {
	if txr.tx != nil {
		for _, tt := range txr.Tables {
			tt.End()
		}
		return txr.tx.Commit()
	}

	for _, tt := range txr.Tables {
		if err := tt.Commit(); err != nil {
			return err
		}
	}
	return nil
}

func (txr *TxRouter) Abort() error {
	if txr.tx != nil {
		for _, tt := range txr.Tables {
			tt.End()
		}
		return txr.tx.Rollback()
	}
	for _, tt := range txr.Tables {
		tt.Rollback()
	}
	return nil
}

func (txr *TxRouter) Insert(table string, row []interface{}) error {
	tt, ok := txr.Tables[table]
	if !ok {
		return errors.New("Insert into unknown table " + table)
	}
	return tt.Insert(row)
}

func (txr *TxRouter) Delete(table string, id int64) error {
	tt, ok := txr.Tables[table]
	if !ok {
		return errors.New("Delete from unknown table " + table)
	}
	return tt.Delete(id)
}