text:
namespace zetasql {
namespace local_service {

class GenericState;

// Pool of saved states that can be shared by multiple statements.
// The state class T must extend GenericState and must be thread safe.
template<class T>
class SharedStatePool {
 public:
  SharedStatePool() : next_id_(0) {}
  SharedStatePool(const SharedStatePool&) = delete;
  SharedStatePool& operator=(const SharedStatePool&) = delete;

  // Register a state object into the pool. The pool takes ownership.
  // Will return -1 if the state is null or already registered.
  int Register(T* state) {
    if (state == nullptr) {
      return -1;
    }

    absl::MutexLock lock(&mutex_);
    int64_t id = next_id_++;
    if (!state->SetId(id)) {
      return -1;
    }
    saved_states_[id].reset(state);
    return id;
  }

  bool Has(int64_t id) const {
    absl::MutexLock lock(&mutex_);
    return zetasql_base::ContainsKey(saved_states_, id);
  }

  // Get a state object with given id, ownership is shared by the pool and all
  // threads that currently hold the state object.
  std::shared_ptr<T> Get(int64_t id) {
    absl::MutexLock lock(&mutex_);
    std::shared_ptr<T>* result = zetasql_base::FindOrNull(saved_states_, id);
    if (result == nullptr) {
      return nullptr;
    } else {
      return *result;
    }
  }

  // Removes a state object from the pool. The state will be deleted immediately
  // if not held by any other threads, or after all threads releasing it.
  bool Delete(int64_t id) {
    absl::MutexLock lock(&mutex_);
    if (!zetasql_base::ContainsKey(saved_states_, id)) {
      return false;
    }
    saved_states_.erase(id);
    return true;
  }

  size_t NumSavedStates() {
    absl::MutexLock lock(&mutex_);
    return saved_states_.size();
  }

 private:
  mutable absl::Mutex mutex_;
  int64_t next_id_ ABSL_GUARDED_BY(mutex_);
  std::map<int64_t, std::shared_ptr<T>> saved_states_ ABSL_GUARDED_BY(mutex_);

  static_assert(
      std::is_base_of<GenericState, T>::value,
      "SharedStatePool only works with subclass of GenericState");
};

// Base class of saved states with an int64_t id.
class GenericState {
 public:
  GenericState() : id_(-1) {}
  virtual ~GenericState() {}

  int64_t GetId() const {
    return id_;
  }

 private:
  int64_t id_;

  // Should only be called by SharedStatePool.
  bool SetId(int64_t id) {
    if (id_ == -1) {
      id_ = id;
      return true;
    }
    return false;
  }

  template<class T> friend class SharedStatePool;

  GenericState(const GenericState&) = delete;
  GenericState& operator=(const GenericState&) = delete;
};

}  // namespace local_service
}  // namespace zetasql

#endif  // ZETASQL_LOCAL_SERVICE_STATE_H_


text:
package ec2 // import "go.opentelemetry.io/contrib/detectors/aws/ec2"

import (
	"context"
	"fmt"
	"net/http"

	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/aws/ec2metadata"
	"github.com/aws/aws-sdk-go/aws/session"

	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/sdk/resource"
	semconv "go.opentelemetry.io/otel/semconv/v1.12.0"
)

type config struct {
	c Client
}

// newConfig returns an appropriately configured config.
func newConfig(options ...Option) *config {
	c := new(config)
	for _, option := range options {
		option.apply(c)
	}

	return c
}

// Option applies an EC2 detector configuration option.
type Option interface {
	apply(*config)
}

type optionFunc func(*config)

func (fn optionFunc) apply(c *config) {
	fn(c)
}

// WithClient sets the ec2metadata client in config.
func WithClient(t Client) Option {
	return optionFunc(func(c *config) {
		c.c = t
	})
}

func (cfg *config) getClient() Client {
	return cfg.c
}

// resource detector collects resource information from EC2 environment.
type resourceDetector struct {
	c Client
}

// Client implements methods to capture EC2 environment metadata information.
type Client interface {
	Available() bool
	GetInstanceIdentityDocument() (ec2metadata.EC2InstanceIdentityDocument, error)
	GetMetadata(p string) (string, error)
}

// compile time assertion that resourceDetector implements the resource.Detector interface.
var _ resource.Detector = (*resourceDetector)(nil)

// NewResourceDetector returns a resource detector that will detect AWS EC2 resources.
func NewResourceDetector(opts ...Option) resource.Detector {
	c := newConfig(opts...)
	return &resourceDetector{c.getClient()}
}

// Detect detects associated resources when running in AWS environment.
func (detector *resourceDetector) Detect(ctx context.Context) (*resource.Resource, error) {
	client, err := detector.client()
	if err != nil {
		return nil, err
	}

	if !client.Available() {
		return nil, nil
	}

	doc, err := client.GetInstanceIdentityDocument()
	if err != nil {
		return nil, err
	}

	attributes := []attribute.KeyValue{
		semconv.CloudProviderAWS,
		semconv.CloudPlatformAWSEC2,
		semconv.CloudRegionKey.String(doc.Region),
		semconv.CloudAvailabilityZoneKey.String(doc.AvailabilityZone),
		semconv.CloudAccountIDKey.String(doc.AccountID),
		semconv.HostIDKey.String(doc.InstanceID),
		semconv.HostImageIDKey.String(doc.ImageID),
		semconv.HostTypeKey.String(doc.InstanceType),
	}

	m := &metadata{client: client}
	m.add(semconv.HostNameKey, "hostname")

	attributes = append(attributes, m.attributes...)

	if len(m.errs) > 0 {
		err = fmt.Errorf("%w: %s", resource.ErrPartialResource, m.errs)
	}

	return resource.NewWithAttributes(semconv.SchemaURL, attributes...), err
}

func (detector *resourceDetector) client() (Client, error) {
	if detector.c != nil {
		return detector.c, nil
	}

	s, err := session.NewSession()
	if err != nil {
		return nil, err
	}

	return ec2metadata.New(s), nil
}

type metadata struct {
	client     Client
	errs       []error
	attributes []attribute.KeyValue
}

func (m *metadata) add(k attribute.Key, n string) {
	v, err := m.client.GetMetadata(n)
	if err == nil {
		m.attributes = append(m.attributes, k.String(v))
		return
	}

	rf, ok := err.(awserr.RequestFailure)
	if !ok {
		m.errs = append(m.errs, fmt.Errorf("%q: %w", n, err))
		return
	}

	if rf.StatusCode() == http.StatusNotFound {
		return
	}

	m.errs = append(m.errs, fmt.Errorf("%q: %d %s", n, rf.StatusCode(), rf.Code()))
}

redpajama_set_name: RedPajamaGithub


text:
/**
 * (c) 2010-2018 Torstein Honsi
 *
 * License: www.highcharts.com/license
 */
'use strict';
import H from '../parts/Globals.js';
import '../parts/Utilities.js';
import '../parts/Options.js';
import '../parts/Chart.js';
import '../parts/SvgRenderer.js';
var Chart = H.Chart,
    defaultOptions = H.defaultOptions,
    each = H.each,
    extend = H.extend,
    merge = H.merge,
    pick = H.pick,
    Renderer = H.Renderer,
    SVGRenderer = H.SVGRenderer,
    VMLRenderer = H.VMLRenderer;

// Add language
extend(defaultOptions.lang, {
    zoomIn: 'Zoom in',
    zoomOut: 'Zoom out'
});

// Set the default map navigation options

/**
 * @product highmaps
 * @optionparent mapNavigation
 */
defaultOptions.mapNavigation = {

    /**
     * General options for the map navigation buttons. Individual options
     * can be given from the [mapNavigation.buttons](#mapNavigation.buttons)
     * option set.
     *
     * @sample {highmaps} maps/mapnavigation/button-theme/
     *         Theming the navigation buttons
     *
     * @type       {*}
     * @product    highmaps
     * @apioption  mapNavigation.buttonOptions
     */
    buttonOptions: {

        /**
         * What box to align the buttons to. Possible values are `plotBox`
         * and `spacingBox`.
         *
         * @type       {string}
         * @default    plotBox
         * @product    highmaps
         * @validvalue ["plotBox", "spacingBox"]
         * @apioption  mapNavigation.buttonOptions.alignTo
         */
        alignTo: 'plotBox',

        /**
         * The alignment of the navigation buttons.
         *
         * @type       {string}
         * @default    left
         * @product    highmaps
         * @validvalue ["left", "center", "right"]
         * @apioption  mapNavigation.buttonOptions.align
         */
        align: 'left',

        /**
         * The vertical alignment of the buttons. Individual alignment can
         * be adjusted by each button's `y` offset.
         *
         * @type       {string}
         * @default    bottom
         * @product    highmaps
         * @validvalue ["top", "middle", "bottom"]
         * @apioption  mapNavigation.buttonOptions.verticalAlign
         */
        verticalAlign: 'top',

        /**
         * The X offset of the buttons relative to its `align` setting.
         *
         * @type       {number}
         * @default    0
         * @product    highmaps
         * @apioption  mapNavigation.buttonOptions.x
         */
        x: 0,

        /**
         * The width of the map navigation buttons.
         *
         * @type       {number}
         * @default    18
         * @product    highmaps
         * @apioption  mapNavigation.buttonOptions.width
         */
        width: 18,

        /**
         * The pixel height of the map navigation buttons.
         *
         * @type       {number}
         * @default    18
         * @product    highmaps
         * @apioption  mapNavigation.buttonOptions.height
         */
        height: 18,

        /**
         * Padding for the navigation buttons.
         *
         * @type       {number}
         * @default    5
         * @since      5.0.0
         * @product    highmaps
         * @apioption  mapNavigation.buttonOptions.padding
         */
        padding: 5,

        /**
         * Text styles for the map navigation buttons. Defaults to
         *
         *
{
         *     fontSize: '15px',
         *     fontWeight: 'bold',
         *     textAlign: 'center'
         * }

         *
         * @type       {Highcharts.CSSObject}
         * @product    highmaps
         * @apioption  mapNavigation.buttonOptions.style
         */
        style: {
            fontSize: '15px',
            fontWeight: 'bold'
        },

        /**
         * A configuration object for the button theme. The object accepts
         * SVG properties like `stroke-width`, `stroke` and `fill`. Tri-state
         * button styles are supported by the `states.hover` and `states.select`
         * objects.
         *
         * @sample {highmaps} maps/mapnavigation/button-theme/
         *         Themed navigation buttons
         *
         * @type       {*}
         * @product    highmaps
         * @apioption  mapNavigation.buttonOptions.theme
         */
        theme: {
            'stroke-width': 1,
            'text-align': 'center'
        }

    },

    /**
     * The individual buttons for the map navigation. This usually includes
     * the zoom in and zoom out buttons. Properties for each button is
     * inherited from
     * [mapNavigation.buttonOptions](#mapNavigation.buttonOptions), while
     * individual options can be overridden. But default, the `onclick`, `text`
     * and `y` options are individual.
     *
     * @type        {*}
     * @product     highmaps
     * @apioptions  mapNavigation.buttons
     */
    buttons: {

        /**
         * Options for the zoom in button. Properties for the zoom in and zoom
         * out buttons are inherited from
         * [mapNavigation.buttonOptions](#mapNavigation.buttonOptions), while
         * individual options can be overridden. By default, the `onclick`,
         * `text` and `y` options are individual.
         *
         * @type        {*}
         * @extends     mapNavigation.buttonOptions
         * @product     highmaps
         * @apioptions  mapNavigation.buttons.zoomIn
         */
        zoomIn: {

            /**
             * Click handler for the button. Defaults to:
             *
             *
function () {
             * this.mapZoom(0.5);
             * }

             *
             * @type {Function}
             * @product highmaps
             */
            onclick: function () {
                this.mapZoom(0.5);
            },

            /**
             * The text for the button. The tooltip (title) is a language option
             * given by [lang.zoomIn](#lang.zoomIn).
             *
             * @type {String}
             * @default +
             * @product highmaps
             */
            text: '+',

            /**
             * The position of the zoomIn button relative to the vertical
             * alignment.
             *
             * @type {Number}
             * @default 0
             * @product highmaps
             */
            y: 0
        },

        /**
         * Options for the zoom out button. Properties for the zoom in and
         * zoom out buttons are inherited from
         * [mapNavigation.buttonOptions](#mapNavigation.buttonOptions), while
         * individual options can be overridden. By default, the `onclick`,
         * `text` and `y` options are individual.
         *
         * @type        {*}
         * @extends     mapNavigation.buttonOptions
         * @product     highmaps
         * @apioptions  mapNavigation.buttons.zoomOut
         */
        zoomOut: {

            /**
             * Click handler for the button. Defaults to:
             *
             *
function () {
             *     this.mapZoom(2);
             * }

             *
             * @type {Function}
             * @product highmaps
             */
            onclick: function () {
                this.mapZoom(2);
            },

            /**
             * The text for the button. The tooltip (title) is a language option
             * given by [lang.zoomOut](#lang.zoomIn).
             *
             * @type {String}
             * @default -
             * @product highmaps
             */
            text: '-',

            /**
             * The position of the zoomOut button relative to the vertical
             * alignment.
             *
             * @type {Number}
             * @default 28
             * @product highmaps
             */
            y: 28
        }
    },

    /**
     * Whether to enable navigation buttons. By default it inherits the
     * [enabled](#mapNavigation.enabled) setting.
     *
     * @type       {boolean}
     * @product    highmaps
     * @apioption  mapNavigation.enableButtons
     */

    /**
     * Whether to enable map navigation. The default is not to enable
     * navigation, as many choropleth maps are simple and don't need it.
     * Additionally, when touch zoom and mousewheel zoom is enabled, it breaks
     * the default behaviour of these interactions in the website, and the
     * implementer should be aware of this.
     *
     * Individual interactions can be enabled separately, namely buttons,
     * multitouch zoom, double click zoom, double click zoom to element and
     * mousewheel zoom.
     *
     * @type       {boolean}
     * @default    false
     * @product    highmaps
     * @apioption  mapNavigation.enabled
     */

    /**
     * Enables zooming in on an area on double clicking in the map. By default
     * it inherits the [enabled](#mapNavigation.enabled) setting.
     *
     * @type       {boolean}
     * @product    highmaps
     * @apioption  mapNavigation.enableDoubleClickZoom
     */

    /**
     * Whether to zoom in on an area when that area is double clicked.
     *
     * @sample {highmaps} maps/mapnavigation/doubleclickzoomto/
     *         Enable double click zoom to
     *
     * @type       {boolean}
     * @default    false
     * @product    highmaps
     * @apioption  mapNavigation.enableDoubleClickZoomTo
     */

    /**
     * Enables zooming by mouse wheel. By default it inherits the [enabled](
     * #mapNavigation.enabled) setting.
     *
     * @type       {boolean}
     * @product    highmaps
     * @apioption  mapNavigation.enableMouseWheelZoom
     */

    /**
     * Whether to enable multitouch zooming. Note that if the chart covers the
     * viewport, this prevents the user from using multitouch and touchdrag on
     * the web page, so you should make sure the user is not trapped inside the
     * chart. By default it inherits the [enabled](#mapNavigation.enabled)
     * setting.
     *
     * @type       {boolean}
     * @product    highmaps
     * @apioption  mapNavigation.enableTouchZoom
     */

    /**
     * Sensitivity of mouse wheel or trackpad scrolling. 1 is no sensitivity,
     * while with 2, one mousewheel delta will zoom in 50%.
     *
     * @type       {number}
     * @default    1.1
     * @since      4.2.4
     * @product    highmaps
     * @apioption  mapNavigation.mouseWheelSensitivity
     */
    mouseWheelSensitivity: 1.1
    // enabled: false,
    // enableButtons: null, // inherit from enabled
    // enableTouchZoom: null, // inherit from enabled
    // enableDoubleClickZoom: null, // inherit from enabled
    // enableDoubleClickZoomTo: false
    // enableMouseWheelZoom: null, // inherit from enabled
};

/**
 * Utility for reading SVG paths directly.
 *
 * @function Highcharts.splitPath
 *
 * @param  {string} path
 *
 * @return {Array<number|string>}
 */
H.splitPath = function (path) {
    var i;

    // Move letters apart
    path = path.replace(/([A-Za-z])/g, ' $1 ');
    // Trim
    path = path.replace(/^\s*/, '').replace(/\s*$/, '');

    // Split on spaces and commas
    path = path.split(/[ ,]+/); // Extra comma to escape gulp.scripts task

    // Parse numbers
    for (i = 0; i < path.length; i++) {
        if (!/[a-zA-Z]/.test(path[i])) {
            path[i] = parseFloat(path[i]);
        }
    }
    return path;
};

// A placeholder for map definitions
H.maps = {};

// Create symbols for the zoom buttons
function selectiveRoundedRect(
    x,
    y,
    w,
    h,
    rTopLeft,
    rTopRight,
    rBottomRight,
    rBottomLeft
) {
    return [
        'M', x + rTopLeft, y,
        // top side
        'L', x + w - rTopRight, y,
        // top right corner
        'C', x + w - rTopRight / 2,
        y, x + w,
        y + rTopRight / 2, x + w, y + rTopRight,
        // right side
        'L', x + w, y + h - rBottomRight,
        // bottom right corner
        'C', x + w, y + h - rBottomRight / 2,
        x + w - rBottomRight / 2, y + h,
        x + w - rBottomRight, y + h,
        // bottom side
        'L', x + rBottomLeft, y + h,
        // bottom left corner
        'C', x + rBottomLeft / 2, y + h,
        x, y + h - rBottomLeft / 2,
        x, y + h - rBottomLeft,
        // left side
        'L', x, y + rTopLeft,
        // top left corner
        'C', x, y + rTopLeft / 2,
        x + rTopLeft / 2, y,
        x + rTopLeft, y,
        'Z'
    ];
}
SVGRenderer.prototype.symbols.topbutton = function (x, y, w, h, attr) {
    return selectiveRoundedRect(x - 1, y - 1, w, h, attr.r, attr.r, 0, 0);
};
SVGRenderer.prototype.symbols.bottombutton = function (x, y, w, h, attr) {
    return selectiveRoundedRect(x - 1, y - 1, w, h, 0, 0, attr.r, attr.r);
};
// The symbol callbacks are generated on the SVGRenderer object in all browsers.
// Even VML browsers need this in order to generate shapes in export. Now share
// them with the VMLRenderer.
if (Renderer === VMLRenderer) {
    each(['topbutton', 'bottombutton'], function (shape) {
        VMLRenderer.prototype.symbols[shape] =
            SVGRenderer.prototype.symbols[shape];
    });
}

/**
 * The factory function for creating new map charts. Creates a new {@link Chart|
 * Chart} object with different default options than the basic Chart.
 *
 * @function Highcharts.mapChart
 *
 * @param  {string|Highcharts.HTMLDOMElement} [renderTo]
 *         The DOM element to render to, or its id.
 *
 * @param  {Highcharts.Options} options
 *         The chart options structure as described in the {@link
 *         https://api.highcharts.com/highstock|options reference}.
 *
 * @param  {Function} callback
 *         A function to execute when the chart object is finished loading and
 *         rendering. In most cases the chart is built in one thread, but in
 *         Internet Explorer version 8 or less the chart is sometimes
 *         initialized before the document is ready, and in these cases the
 *         chart object will not be finished synchronously. As a consequence,
 *         code that relies on the newly built Chart object should always run in
 *         the callback. Defining a
 *         {@link https://api.highcharts.com/highstock/chart.events.load|
 *         chart.event.load} handler is equivalent.
 *
 * @return {Highcharts.Chart}
 *         The chart object.
 */
H.Map = H.mapChart = function (a, b, c) {

    var hasRenderToArg = typeof a === 'string' || a.nodeName,
        options = arguments[hasRenderToArg ? 1 : 0],
        hiddenAxis = {
            endOnTick: false,
            visible: false,
            minPadding: 0,
            maxPadding: 0,
            startOnTick: false
        },
        seriesOptions,
        defaultCreditsOptions = H.getOptions().credits;

    /* For visual testing
    hiddenAxis.gridLineWidth = 1;
    hiddenAxis.gridZIndex = 10;
    hiddenAxis.tickPositions = undefined;
    // */

    // Don't merge the data
    seriesOptions = options.series;
    options.series = null;

    options = merge(
        {
            chart: {
                panning: 'xy',
                type: 'map'
            },
            credits: {
                mapText: pick(
                    defaultCreditsOptions.mapText,
                    ' \u00a9 ' +
                        '{geojson.copyrightShort}'
                ),
                mapTextFull: pick(
                    defaultCreditsOptions.mapTextFull,
                    '{geojson.copyright}'
                )
            },
            tooltip: {
                followTouchMove: false
            },
            xAxis: hiddenAxis,
            yAxis: merge(hiddenAxis, { reversed: true })
        },
        options, // user's options

        { // forced options
            chart: {
                inverted: false,
                alignTicks: false
            }
        }
    );

    options.series = seriesOptions;

    return hasRenderToArg ?
        new Chart(a, options, c) :
        new Chart(options, b);
};


text:
/*Разрезание циклов*/
/*Вопросы: Олег 8-903-462-33-24*/
#include "Transforms/Loops/LoopDistribution/LoopDistribution.h"
#include "Transforms/Loops/LoopFusion/LoopFusion.h"

#include <cassert>
#include <vector>
#include <map>
#include <iostream>
#include <algorithm>
#include "Analysis/DepGraph/DepGraph.h"
#include "Analysis/Montego/DependenceGraph/DependenceGraph.h"

using namespace OPS;
using namespace std;
using namespace DepGraph;
using namespace Montego;
using namespace OPS::Reprise;

bool isLoopFusionPossible(ForStatement* loop1, ForStatement* loop2)
{
	//не пустой ли оператор передан?
	OPS_ASSERT(loop1 != 0);
	OPS_ASSERT(loop2 != 0);

	//заголовки циклов совпадают
	if(!(loop1->getInitExpression().isEqual(loop2->getInitExpression())))
		return false;//начальные условия не совпадают
	if(!(loop1->getFinalExpression().isEqual(loop2->getFinalExpression())))
		return false;//условия выхода не совпадают
	if(!(loop1->getStepExpression().isEqual(loop2->getStepExpression())))
		return false;//шаги итераторов не совпадают

	//в теле первого цикла пресутствуют только операторы присваивания?
	for (BlockStatement::Iterator iter = loop1->getBody().getFirst(); iter.isValid(); ++iter)
	{
		if(!iter->is_a<ExpressionStatement>())
			return false;//в теле цикла пресутствуют не только операторы присваивания
		if(!iter->cast_to<ExpressionStatement>().get().is_a<BasicCallExpression>())
			return false;//в теле цикла пресутствуют не только операторы присваивания
		if(iter->cast_to<ExpressionStatement>().get().cast_to<BasicCallExpression>().getKind() != BasicCallExpression::BCK_ASSIGN)
			return false;//в теле цикла пресутствуют не только операторы присваивания
	}
	//в теле второго цикла пресутствуют только операторы присваивания?
	for (BlockStatement::Iterator iter = loop2->getBody().getFirst(); iter.isValid(); ++iter)
	{
		if(!iter->is_a<ExpressionStatement>())
			return false;//в теле цикла пресутствуют не только операторы присваивания
		if(!iter->cast_to<ExpressionStatement>().get().is_a<BasicCallExpression>())
			return false;//в теле цикла пресутствуют не только операторы присваивания
		if(iter->cast_to<ExpressionStatement>().get().cast_to<BasicCallExpression>().getKind() != BasicCallExpression::BCK_ASSIGN)
			return false;//в теле цикла пресутствуют не только операторы присваивания
	}

	//циклы loop1 и loop2 следуют непосредственно друг за другом?
	BlockStatement::Iterator iter = loop1->getParentBlock().convertToIterator(loop1);
	OPS_ASSERT(iter.isValid());
	BlockStatement::Iterator iter2 = loop2->getParentBlock().convertToIterator(loop2);
	OPS_ASSERT(iter2.isValid());

	iter++;
	if(iter != iter2)
		return false;

	//не стоит ли метки на заголовке второго цикла?
	//????????????
	if(loop2->hasLabel())
		return false;

	return true;
}

namespace OPS
{
namespace Transforms
{
namespace Loops
{
//на вход преобразование подается два цикла for и параметры VarToArray и TempArrays значение которого влияет на то будут ли использоваться соответствующие преобразования
bool LoopFusion(ForStatement* loop1, ForStatement* loop2, bool VarToArray, bool TempArrays)
{
//////начальные проверки на входные данные
	//можно ли применить преобразование к данным циклам
	if(!isLoopFusionPossible(loop1, loop2))
		return false;

////////формируем результирующий код
	//создаем новый цикл в котором вставляем операторы второго цикла следом за операторами первого
	//ForStatement* loop = loop1->clone();
	//loop1->getParentBlock().addAfter(loop1->getParentBlock().convertToIterator(loop1), loop);

	//вставляем операторы второго цикла следом за операторами первого
	//если же проверка покажет что присутствуют зависимости которые мешают выполнению преобразования,
	//то просто деелаем return false; (в следствии чего все изменения будут анулированы)
	BlockStatement::Iterator iter = loop2->getBody().getFirst();
	BlockStatement::Iterator iter_half = loop1->getBody().addLast(&*iter->clone());
	iter++;
	for(; iter.isValid();++iter)
	{
		loop1->getBody().addLast(&*iter->clone());
	}

	//проверяем нет ли дуг идущих от тела второго оператора цикла к телу первого
	//проверяем не идут ли дуги из второго списка в первый
	Id::id a(loop1->getBody());
	DepGraph::LamportGraph Lamp;
	Lamp.Build(a);

	//DependenceGraph graph(loop1->getBody());
	//graph.refineAllArcsWithLatticeGraph();

	//// соберем все ссылки на переменные, имеющиеся в заданных операторах
	//Shared::NodesCollector<ReferenceExpression> occurenceCollector1, occurenceCollector2;

	//it1->first->accept(occurenceCollector1);
	//it2->first->accept(occurenceCollector2);

	for(BlockStatement::Iterator iter1 = loop1->getBody().getFirst(); iter1 != iter_half; ++iter1)
	{
		for(BlockStatement::Iterator iter2 = iter_half; iter2.isValid(); ++iter2)
		{

			//if(graph.)
			if ((Lamp.TestDep(ANTIDEP, &*iter2, &*iter1)) || (Lamp.TestDep(FLOWDEP, &*iter2, &*iter1)) || (Lamp.TestDep(OUTPUTDEP, &*iter2, &*iter1)))
			{
				return false;
				//удаляем исходный первый цикл
				//iter = loop1->getParentBlock().convertToIterator(loop);
				//loop1->getParentBlock().erase(iter);
			}
		}
	}

	//удаляем исходный первый цикл
	//iter = loop1->getParentBlock().convertToIterator(loop1);
	//loop1->getParentBlock().erase(iter);
	//удаляем исходный второй цикл
	iter = loop2->getParentBlock().convertToIterator(loop2);
	loop2->getParentBlock().erase(iter);

	{
//////////	StatementBase* temp1_b = &(*loop1->getBody().getFirst());
//////////	StatementBase* temp1_e = &(*loop1->getBody().getLast());
//////////	StatementBase* temp2_b = &(*loop2->getBody().getFirst());
//////////	StatementBase* temp2_e = &(*loop2->getBody().getLast());
//////////
//////////	//добавляем тело второго цикла в конец тела первого цикла
//////////	loop1->getBody().addLast(&loop2->getBody());
//////////	//удаляем исходный второй цикл
//////////	BlockStatement::Iterator iter = loop2->getParentBlock().convertToIterator(loop2);
//////////	loop2->getParentBlock().erase(iter);
//////////
////////////////проверяем нет ли дуг идущих от тела второго цикла к телу первого
//////////	//проверяем не идут ли дуги из второго списка в первый
//////////	Id::id a(loop1->getBody());
//////////	DepGraph::LamportGraph Lamp;
//////////	Lamp.Build(a);
//////////
//////////	BlockStatement::Iterator iter_loop1_begin = loop1->getBody().convertToIterator(temp1_b);
//////////	BlockStatement::Iterator iter_loop1_end = loop1->getBody().convertToIterator(temp1_e);
//////////	BlockStatement::Iterator iter_loop2_begin = loop1->getBody().convertToIterator(temp2_b);
//////////	BlockStatement::Iterator iter_loop2_end = loop1->getBody().convertToIterator(temp2_e);
//////////	iter_loop1_end++;
//////////	iter_loop2_end++;
//////////	for(BlockStatement::Iterator iter1 = iter_loop2_begin; iter1 != iter_loop2_end; ++iter1)
//////////	{
//////////		for(BlockStatement::Iterator iter2 = iter_loop1_begin; iter2 != iter_loop1_end; ++iter2)
//////////		{
//////////			if ((Lamp.TestDep(ANTIDEP, &*iter1, &*iter2)) || (Lamp.TestDep(FLOWDEP, &*iter1, &*iter2)) || (Lamp.TestDep(OUTPUTDEP, &*iter1, &*iter2)))
//////////			{
//////////				return false;
//////////			}
//////////		}
//////////	}
	}
return true;
}
}	// Loops
}	// Transforms
}	// OPS


text:
package buck;

class JavaLib2 {}


text:
<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class tour_packages extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('tour_packages_model', 'obj_tour_packages', TRUE);
        $this->load->model('common_model', 'obj_common', TRUE);
        $this->load->model('template_content_model', 'obj_template_content', TRUE);
        $this->load->model('template_model', 'obj_template', TRUE);
        $this->thumb_width = 356;
        $this->thumb_height = 247;
        $this->main_width = 800;
        $this->main_height = 600;
        $this->max_size = 2048; //2MB
        $this->crop_size = $this->thumb_width / $this->thumb_height;
        if ($this->session->userdata('ADMIN_NAME') == FALSE) {

            redirect('/');
        }
    }

    function search($row = 0) {

        $date_from = strtotime($this->input->post('date_from') . '00:00:00');
        $date_to = strtotime($this->input->post('date_to') . '23:59:59');
        $user_profile_status = $this->input->post('user_profile_status');
        if ($this->input->post('date_from') && $this->input->post('date_to')) {
            $condition = array('tour_packages_created_date <= ' => $date_to,
                'tour_packages_created_date >=' => $date_from,
                'tour_packages_status' => $user_profile_status
            );
            $sess_data = array('tour_packages_created_date_from' => $date_from,
                'tour_packages_created_date_to' => $date_to,
                'tour_packages_status' => $user_profile_status
            );
            $this->session->set_userdata($sess_data);
        } else {
            $date_from = $this->session->userdata('tour_packages_created_date_from');
            $date_to = $this->session->userdata('tour_packages_created_date_to');
            $user_profile_status = $this->session->userdata('user_login_active_status');
            $condition = array('tour_packages_created_date <= ' => $date_to,
                'tour_packages_created_date >=' => $date_from,
                'tour_packages_status' => $user_profile_status
            );
        }
        $limit = 2;
        $config['base_url'] = site_url() . '/admin/tour_packages/search/';
        $config['full_tag_open'] = '
';
        $config['full_tag_close'] = '
';
        $config['uri_segment'] = 4;
        $config['total_rows'] = $this->obj_tour_packages->countrows($condition);
        $config['per_page'] = $limit;
        $this->pagination->initialize($config);
        $data['links'] = $this->pagination->create_links();
        $data['tour_packages'] = $this->obj_tour_packages->get_all_entries($row, $limit, $condition, 'tour_packages_created_date', 'desc');
        $data['row'] = $row;
        $data['page_active'] = 2;
        $data['per_page'] = $limit;
        $data['date_from'] = $date_from;
        $data['date_to'] = $date_to;
        $data['user_profile_active_status'] = $user_profile_status;
        $this->load->view('admin/tour_packages/list', $data);
    }

    function index($row = 0) {

        $this->session->unset_userdata('tour_packages_created_date_from');
        $this->session->unset_userdata('tour_packages_created_date_to');
        $this->session->unset_userdata('user_login_active_status');
        $limit = '15';
        $this->load->library('pagination');
        $config['base_url'] = site_url() . '/admin/tour_packages/index/';
        $config['full_tag_open'] = '
';
        $config['full_tag_close'] = '
';
        $config['uri_segment'] = 4;
        $condition = array();
        $config['total_rows'] = $this->obj_tour_packages->countrows($condition);
        $config['per_page'] = $limit;
        $this->pagination->initialize($config);
        $data['links'] = $this->pagination->create_links();
        $data['tour_packages'] = $this->obj_tour_packages->get_all_entries($row, $limit, $condition, 'tour_packages_display_order', 'asc');
//        print_r($data['tour_packages']);exit(0);
        $data['row'] = $row;
        $data['page_active'] = 2;
        $data['per_page'] = $limit;
        $this->load->view('admin/tour_packages/list', $data);
    }

    function homepage($row = 0) {

        $this->session->unset_userdata('tour_packages_created_date_from');
        $this->session->unset_userdata('tour_packages_created_date_to');

        $limit = '15';
        $this->load->library('pagination');
        $config['base_url'] = site_url() . '/admin/tour_packages/index/';
        $config['full_tag_open'] = '
';
        $config['full_tag_close'] = '
';
        $config['uri_segment'] = 5;
        $condition = array('tour_packages_homepage_status' => 'Y');
        $config['total_rows'] = $this->obj_tour_packages->countrows($condition);
        $config['per_page'] = $limit;
        $this->pagination->initialize($config);
        $data['links'] = $this->pagination->create_links();
        $data['tour_packages'] = $this->obj_tour_packages->get_all_entries($row, $limit, $condition, 'tour_packages_created_date', 'desc');
        $data['row'] = $row;
        $data['page_active'] = 2;
        $data['per_page'] = $limit;
        $data['user_profile_active_status'] = 3;
        $this->load->view('admin/tour_packages/list', $data);
    }

    function featured($row = 0) {

        $this->session->unset_userdata('tour_packages_created_date_from');
        $this->session->unset_userdata('tour_packages_created_date_to');

        $limit = '15';
        $this->load->library('pagination');
        $config['base_url'] = site_url() . '/admin/tour_packages/featured/';
        $config['full_tag_open'] = '
';
        $config['full_tag_close'] = '
';
        $config['uri_segment'] = 5;
        $condition = array('tour_packages_featured_status' => 'Y');
        $config['total_rows'] = $this->obj_tour_packages->countrows($condition);
        $config['per_page'] = $limit;
        $this->pagination->initialize($config);
        $data['links'] = $this->pagination->create_links();
        $data['tour_packages'] = $this->obj_tour_packages->get_all_entries($row, $limit, $condition, 'tour_packages_created_date', 'desc');
        $data['row'] = $row;
        $data['page_active'] = 2;
        $data['per_page'] = $limit;
        $data['user_profile_active_status'] = 3;
        $this->load->view('admin/tour_packages/list', $data);
    }

    function add() {
        $this->form_validation->set_rules('tour_packages_title', 'Name', 'required|prep_for_form');
        $this->form_validation->set_rules('tour_packages_place', 'Place', 'required|prep_for_form');
        $this->form_validation->set_rules('tour_packages_link', 'Link', 'required|prep_for_form');
        $this->form_validation->set_rules('tour_packages_content', 'Content', 'prep_for_form');
        if ($this->form_validation->run() == FALSE) {
            $data = array();
            $this->load->view('admin/tour_packages/add', $data);
        } else {
            //image start
            $file_name_image = '';
            $extension = '';
            $error = '';
            $tour_packages_url = url_title(strtolower($this->input->post('tour_packages_title')));
            if ($_FILES['image']['name'] != '') {
                $config['upload_path'] = 'uploads/tour_packages/main/';
                $config['allowed_types'] = 'gif|jpg|png|jpeg|pdf';
                $config['max_size'] = $this->max_size;
                $config['file_name'] = $tour_packages_url;
                $this->load->library('upload', $config);
                if (!$this->upload->do_upload('image')) {
                    $error = $this->upload->display_errors();
                } else {
                    $data = array('upload_data' => $this->upload->data());
                    $file_name_image = $data['upload_data']['file_name'];
                    //$extension=$data['upload_data']['file_ext'];
                    $config['source_image'] = 'uploads/tour_packages/main/' . $file_name_image;
                    $config['new_image'] = 'uploads/tour_packages/thumb/' . $file_name_image;
                    $config['width'] = $this->thumb_width;
                    $config['height'] = $this->thumb_height;
                    $config['maintain_ratio'] = FALSE;
                    $config['quality'] = '100';
                    $this->image_lib->initialize($config);
                    $this->image_lib->resize();
                    $this->image_lib->clear();
                    if ($data['upload_data']['image_height'] > $this->main_height || $data['upload_data']['image_width'] > $this->main_width) {
                        $config['image_library'] = 'gd2';
                        $config['source_image'] = 'uploads/tour_packages/main/' . $file_name_image;
                        $config['new_image'] = 'uploads/tour_packages/main/' . $file_name_image;
                        $config['width'] = $this->main_width;
                        $config['height'] = $this->main_height;
                        $config['maintain_ratio'] = TRUE;
                        $this->image_lib->initialize($config);
                        $this->image_lib->resize();
                    }
                }
            }
            //image end
            if ($error) {
                $data['error'] = $error;
                $this->load->view('admin/tour_packages/add', $data);
            } else {

                $gallery_url = url_title(strtolower($this->input->post('tour_packages_title')));
                $gallery_url = $this->obj_tour_packages->check_url_status($gallery_url);
                $tour_packages_wedding_date = strtotime($this->input->post('tour_packages_wedding_date') . '23:59:59');
                $tour_packages_display_order = $this->obj_tour_packages->countrows();
                $tour_packages_display_order++;

                $datas = array(
                    'tour_packages_title' => $this->input->post('tour_packages_title'),
                    'tour_packages_place' => $this->input->post('tour_packages_place'),
                    'tour_packages_link' => $this->input->post('tour_packages_link'),
                    'tour_packages_content' => $this->input->post('tour_packages_content'),
                    'tour_packages_image' => $file_name_image,
                    'tour_packages_created_id' => $this->session->userdata('users_id'),
                    'tour_packages_created_date' => time(),
                    'tour_packages_url' => $gallery_url,
                    'tour_packages_display_order' => $tour_packages_display_order
                );
                $tour_packages_id = $this->obj_tour_packages->add($datas);
                redirect('admin/tour_packages/index');
            }
        }
    }

    public function change_name() {
        $condition = array();
        $tour_packages_data = $this->obj_tour_packages->get_all($condition);
        foreach ($tour_packages_data as $results) {

            $gallery_url = url_title(strtolower($results['tour_packages_title']));

            $datas = array(
                'tour_packages_url' => $gallery_url
            );
            $condition = array('tour_packages_id' => $results['tour_packages_id']);
            $this->obj_tour_packages->edit($condition, $datas);
        }
    }

    public function crop($id, $row = 0) {
        $condition = array('tour_packages_id' => $id);
        $data['tour_packages'] = $this->obj_tour_packages->get_all($condition);
        $data["row"] = $row;
        $this->load->view('admin/tour_packages/crop', $data);
    }

    public function save($row = 0) {

        $config['image_library'] = 'gd2';
        $config['source_image'] = 'uploads/tour_packages/main/' . $this->input->post('image_name');
        $config['new_image'] = 'uploads/tour_packages/thumb/' . $this->input->post('image_name');
        $config['maintain_ratio'] = FALSE;
        $config['quality'] = '100';
        $config['x_axis'] = $this->input->post('x');
        $config['y_axis'] = $this->input->post('y');
        $config['width'] = $this->input->post('w');
        $config['height'] = $this->input->post('h');
        //	$config['dynamic_output'] = TRUE;
        $this->image_lib->initialize($config);
        if ($this->image_lib->crop()) {
            $this->session->set_userdata('tour_packages_crop_msg', 'Sucessfully updated');
            $config2['image_library'] = 'gd2';
            $config2['source_image'] = 'uploads/tour_packages/thumb/' . $this->input->post('image_name');
            $config2['new_image'] = 'uploads/tour_packages/thumb/' . $this->input->post('image_name');
            $config2['maintain_ratio'] = TRUE;
            $config2['quality'] = '100';
            $config2['width'] = $this->thumb_width;
            $config2['height'] = $this->thumb_height;
            $this->image_lib->initialize($config2);
            $this->image_lib->resize();
        }

        $tour_packages_id = $this->input->post('tour_packages_id');
        redirect('admin/tour_packages/crop/' . $tour_packages_id . '/' . $row);
    }

    function edit($id) {
        $data = array();
        $this->form_validation->set_rules('tour_packages_title', 'Name', 'required|prep_for_form');
        $this->form_validation->set_rules('tour_packages_place', 'Place', 'required|prep_for_form');
        $this->form_validation->set_rules('tour_packages_link', 'Link', 'required|prep_for_form');
        $this->form_validation->set_rules('tour_packages_content', 'Contents', 'prep_for_form');
        if ($this->form_validation->run() == FALSE) {

            $condition = array('tour_packages_id' => $id);
            $tour_packages_data = $this->obj_tour_packages->get_all($condition);
            if ($tour_packages_data) {
                $data['tour_packages_data'] = $tour_packages_data;
            } else {
                redirect('admin/tour_packages', 'refresh');
            }
            $data['tour_packages_id'] = $id;
            $data['tour_packages_data'] = $this->obj_tour_packages->get_all($condition);
            $this->load->view('admin/tour_packages/edit', $data);
        } else {
            //image start
            $file_name_image = '';
            $extension = '';
            $error = '';
            $tour_packages_url = url_title(strtolower($this->input->post('tour_packages_title')));
            if ($_FILES['image']['name'] != '') {
                $config['upload_path'] = 'uploads/tour_packages/main/';
                $config['allowed_types'] = 'gif|jpg|png|jpeg';
                $config['max_size'] = $this->max_size;
                $config['file_name'] = $tour_packages_url;
                $this->load->library('upload', $config);
                if (!$this->upload->do_upload('image')) {
                    $error = $this->upload->display_errors();
                } else {
                    $data = array('upload_data' => $this->upload->data());
                    $file_name_image = $data['upload_data']['file_name'];
                    $extension = $data['upload_data']['file_ext'];
                    $config['source_image'] = 'uploads/tour_packages/main/' . $file_name_image;
                    $config['new_image'] = 'uploads/tour_packages/thumb/' . $file_name_image;
                    $config['width'] = $this->thumb_width;
                    $config['height'] = $this->thumb_height;
                    $config['maintain_ratio'] = FALSE;
                    $config['quality'] = '100';
                    $this->image_lib->initialize($config);
                    $this->image_lib->resize();
                    $this->image_lib->clear();
                    if ($data['upload_data']['image_height'] > $this->main_height || $data['upload_data']['image_width'] > $this->main_width) {
                        $config['image_library'] = 'gd2';
                        $config['source_image'] = 'uploads/tour_packages/main/' . $file_name_image;
                        $config['new_image'] = 'uploads/tour_packages/main/' . $file_name_image;
                        $config['width'] = $this->main_width;
                        $config['height'] = $this->main_height;
                        $config['maintain_ratio'] = TRUE;
                        $this->image_lib->initialize($config);
                        $this->image_lib->resize();
                    }
                    @unlink('./uploads/tour_packages/main/' . $this->input->post('old_tour_packages_image'));
                    @unlink('./uploads/tour_packages/thumb/' . $this->input->post('old_tour_packages_image'));
                }
            } else {
                $file_name_image = $this->input->post('old_tour_packages_image');
            }
            //image end
            //thumb image

            if ($_FILES['image_thumb']['name'] != '') {
                @unlink('./uploads/tour_packages/thumb/' . $file_name_image);
                $config['upload_path'] = 'uploads/tour_packages/thumb/';
                $config['allowed_types'] = 'gif|jpg|png|jpeg';
                $config['file_name'] = $file_name_image;
                $this->load->library('upload', $config);
                $this->upload->initialize($config);
                if (!$this->upload->do_upload('image_thumb')) {
                    $error = $this->upload->display_errors();
                } else {
                    $data = array('upload_data' => $this->upload->data());
                }
            }

            //thumb image end

            if ($error) {
                $data['error'] = $error;
                $condition = array('tour_packages_id' => $id);
                $data['tour_packages_data'] = $this->obj_tour_packages->get_all($condition);
                $data["tour_packages_id"] = $id;
                $this->load->view('admin/tour_packages/edit', $data);
            } else {

                $tour_packages_dates = $this->input->post('tour_packages_date') . '23:59:59';
                $tour_packages_date = strtotime($tour_packages_dates);

                $datas = array(
                    'tour_packages_title' => $this->input->post('tour_packages_title'),
                    'tour_packages_place' => $this->input->post('tour_packages_place'),
                    'tour_packages_link' => $this->input->post('tour_packages_link'),
                    'tour_packages_content' => $this->input->post('tour_packages_content'),
                    'tour_packages_image' => $file_name_image,
                    'tour_packages_created_id' => $this->session->userdata('users_id'),
                    'tour_packages_created_date' => $tour_packages_date
                );
                $this->session->set_userdata(array('tour_packages_msg' => 'Update successfully'));
                $condition = array('tour_packages_id' => $id);
                $this->obj_tour_packages->edit($condition, $datas);
                redirect('admin/tour_packages/edit/' . $id);
            }
        }
    }

    function delete_image($id, $row = '') {
        // Delete Product image
        $condition = array('tour_packages_id' => $id);
        $img = $this->obj_tour_packages->get_all($condition);
        @unlink('uploads/tour_packages/main/' . $img[0]['tour_packages_image']);
        @unlink('uploads/tour_packages/thumb/' . $img[0]['tour_packages_image']);
        $datas = array('tour_packages_image' => '');
        $this->obj_tour_packages->edit($condition, $datas);
        redirect('admin/tour_packages/edit_main_image/' . $id . '/' . $row);
    }

    function edit_main_image($id = '', $row = '') {
        $data = array();
        $this->form_validation->set_rules('personal_details_name', ' Name', 'prep_for_form');

        if ($this->form_validation->run() == FALSE) {

            $condition = array('tour_packages_id' => $id);
            $tour_packages_data = $this->obj_tour_packages->get_all($condition);
            if ($tour_packages_data) {
                $data['tour_packages_data'] = $tour_packages_data;
            } else {
                redirect('admin/tour_packages', 'refresh');
            }
            $data["tour_packages_id"] = $id;
            $data["row"] = $row;
            $this->load->view('admin/tour_packages/edit_main_gallery', $data);
        } else {
            //image start
            $file_name_image = '';
            $extension = '';
            $error = '';
            if ($_FILES['image']['name'] != '') {

                $config['upload_path'] = 'uploads/tour_packages/main/';
                $config['allowed_types'] = 'gif|jpg|png|jpeg';
                $config['max_size'] = $this->max_size;
                $this->load->library('upload', $config);
                if (!$this->upload->do_upload('image')) {
                    $error = $this->upload->display_errors();
                } else {
                    $data = array('upload_data' => $this->upload->data());
                    $file_name_image = $data['upload_data']['file_name'];
                    $extension = $data['upload_data']['file_ext'];
                    $config['source_image'] = 'uploads/tour_packages/main/' . $file_name_image;
                    $config['new_image'] = 'uploads/tour_packages/thumb/' . $file_name_image;
                    $config['width'] = $this->thumb_width;
                    $config['height'] = $this->thumb_height;
                    $config['maintain_ratio'] = FALSE;
                    $config['quality'] = '100';
                    $this->image_lib->initialize($config);
                    $this->image_lib->resize();
                    $this->image_lib->clear();
                    if ($data['upload_data']['image_height'] > $this->main_height || $data['upload_data']['image_width'] > $this->main_width) {
                        $config['image_library'] = 'gd2';
                        $config['source_image'] = 'uploads/tour_packages/main/' . $file_name_image;
                        $config['new_image'] = 'uploads/tour_packages/main/' . $file_name_image;
                        $config['width'] = $this->main_width;
                        $config['height'] = $this->main_height;
                        $config['maintain_ratio'] = TRUE;
                        $this->image_lib->initialize($config);
                        $this->image_lib->resize();
                    }
                    @unlink('./uploads/tour_packages/main/' . $this->input->post('old_tour_packages_image'));
                    @unlink('./uploads/tour_packages/thumb/' . $this->input->post('old_tour_packages_image'));
                }
            } else {
                $file_name_image = $this->input->post('old_tour_packages_image');
            }
            //image end
            if ($error) {
                $data['error'] = $error;
                $condition = array('tour_packages_id' => $id);
                $data['tour_packages_data'] = $this->obj_tour_packages->get_all($condition);
                $data["tour_packages_id"] = $id;
                $data["row"] = $row;
                $this->load->view('admin/tour_packages/edit', $data);
            } else {
                $this->session->set_userdata('tour_packages_msg', 'Sucessfully updated');
                $datas = array('tour_packages_image' => $file_name_image);
                $condition = array('tour_packages_id' => $id);
                //exit;
                $this->obj_tour_packages->edit($condition, $datas);
                $data["row"] = $row;
                redirect('admin/tour_packages/edit_main_image/' . $id . '/' . $row);
            }
        }
    }

    function delete($condition = array()) {
        // Delete Product image

        $img = $this->obj_tour_packages->get_all($condition);
        @unlink('uploads/tour_packages/main/' . $img[0]['tour_packages_image']);
        @unlink('uploads/tour_packages/thumb/' . $img[0]['tour_packages_image']);
        $this->obj_tour_packages->delete($condition);
    }

    function delete_all($row = 0) {
        // Delete Product image
        $check_all = $this->input->post('check');
        $row = $this->input->post('row');
        $per_page = $this->input->post('per_page');
        $tour_packages_count = $this->input->post('tour_packages_count');
        $i = 0;
        if ($this->input->post('delete')) {
            if ($check_all) {
                foreach ($check_all as $value) {

                    $condition = array('tour_packages_id' => $value);

                    $this->delete($condition);
                    $i++;
                }
            }
        }
        if ($this->input->post('activate')) {
            if ($check_all) {
                foreach ($check_all as $value) {

                    $condition = array('tour_packages_id' => $value);

                    $datas = array(
                        'user_login_active_status' => 2,
                    );
                    $this->obj_login->edit($condition, $datas);
                    $i++;
                }
            }
        }
        if ($this->input->post('deactivate')) {

            if ($check_all) {
                foreach ($check_all as $value) {
                    $condition = array('tour_packages_id' => $value);
                    $datas = array('user_login_active_status' => 4);
                    $this->obj_login->edit($condition, $datas);
                    $i++;
                }
            }
        }
        $user_profile_active_status = $this->input->post('user_profile_active_status');
        $redirect_function = 'index';
        if ($user_profile_active_status == 3) {
            $redirect_function = 'homepage';
        }

        if ($this->session->userdata('tour_packages_created_date_from') || $this->session->userdata('tour_packages_created_date_to')) {
            $redirect_function = 'search';
        }
        if ($i == $tour_packages_count && $row != 0) {
            $redirect_page = $row - $per_page;
            redirect('admin/tour_packages/' . $redirect_function . '/' . $user_profile_active_status);
        } else {
            redirect('admin/tour_packages/' . $redirect_function . '/' . $user_profile_active_status . '/' . $row);
        }
    }

    function update_order() {
        $tour_packages_id = $this->input->post('tour_packages_id');
        $tour_packages_order = $this->input->post('tour_packages_order');
        $condition = array('tour_packages_id' => $tour_packages_id);
        $data_array = array('tour_packages_display_order' => $tour_packages_order);
        $this->obj_tour_packages->edit($condition, $data_array);
    }

    function update_homepage() {
        $tour_packages_id = $this->input->post('tour_packages_id');
        $tour_packages_status = $this->input->post('tour_packages_homepage_status');
        $condition = array('tour_packages_id' => $tour_packages_id);
        $data_array = array('tour_packages_homepage_status' => $tour_packages_status);
        $this->obj_tour_packages->edit($condition, $data_array);
    }

    function update_featured() {
        $tour_packages_id = $this->input->post('tour_packages_id');
        $tour_packages_status = $this->input->post('tour_packages_homepage_status');
        $condition = array();
        $data_array = array('tour_packages_featured_status' => 'N');
        $this->obj_tour_packages->edit($condition, $data_array);
        $conditions = array('tour_packages_id' => $tour_packages_id);
        $data_array = array('tour_packages_featured_status' => 'Y');
        $this->obj_tour_packages->edit($conditions, $data_array);
    }

    function update_status() {
        $tour_packages_id = $this->input->post('tour_packages_id');
        $tour_packages_status = $this->input->post('tour_packages_status');
        $condition = array('tour_packages_id' => $tour_packages_id);
        $data_array = array('tour_packages_status' => $tour_packages_status);
        $this->obj_tour_packages->edit($condition, $data_array);
    }

    function update_profile_status() {
        $tour_packages_id = $this->input->post('tour_packages_id');
        $profile_status = $this->input->post('profile_status');
        $condition = array('tour_packages_id' => $tour_packages_id);
        $data_array = array('user_login_active_status' => $profile_status);
        $this->obj_tour_packages->edit($condition, $data_array);
    }

}


text:
import click

from noscrapy import Queue, Scraper, Store

@click.group()
def cli():
    pass

@cli.command(name='show')
def show_sitemaps():
    store = Store()
    for sitemap in store.get_all_sitemaps():
        print(sitemap.id)

@cli.command(name='print')
@click.argument('name')
def print_sitemap(name):
    store = Store()
    sitemap = store.get_sitemap(name)
    print(sitemap)

@cli.command(name='data')
@click.argument('name')
def data_sitemap(name):
    store = Store()
    for row in store.get_sitemap_data(name):
        print(row)

@cli.command(name='rescrape')
@click.argument('name')
def rescrape_sitemap(name):
    queue = Queue()
    store = Store()
    store.reset_sitemap_data_db(name)
    sitemap = store.get_sitemap(name)
    scraper = Scraper(queue, sitemap, store)
    scraper.run()

@cli.command(name='app')
def app():
    from noscrapy.app import create_app
    app = create_app()
    app.run(debug=True)


text:
<?php

namespace Stfalcon\Bundle\EventBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;

/**
 * This is the class that loads and manages your bundle configuration
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 */
class StfalconEventExtension extends Extension
{
    /**
     * {@inheritDoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $container->setParameter('stfalcon_event.config', $config);

        $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        // @todo винести адмінку в окремий конфіг
        $loader->load('services.xml');
    }
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using DCM.Entities;
using DCM.Enums;

namespace DCM.Factories
{
    public class Companies : IDisposable
    {
        private static PlayerCompany _playerCompany;
        private static List<AICompany> _AICompanies;
        private static List<ContinentItem> _continentItems;

        private static Companies instance;

        /// <summary>
        /// Current instance of companies class.
        /// </summary>
        private Companies()
        {
            // Empty constructor for deserlization purposes.
        }

        /// <summary>
        /// Stores all of the players information about his current game and assets.
        /// </summary>
        public PlayerCompany PlayerCompany
        {
            get { return _playerCompany; }
            set { _playerCompany = value; }
        }

        /// <summary>
        /// Stores list of fake A.I. players that will compete with the player.
        /// </summary>
        public List<AICompany> AICompanies
        {
            get { return _AICompanies; }
            set { _AICompanies = value; }
        }

        /// <summary>
        /// Current instance of company manager instance.
        /// </summary>
        public static Companies Instance
        {
            get { return instance; }
            set { instance = value; }
        }

        /// <summary>
        /// List of possible continents that companies may be based from.
        /// </summary>
        public List<ContinentItem> ContinentItems
        {
            get { return _continentItems; }
            set { _continentItems = value; }
        }

        #region IDisposable Members

        public void Dispose()
        {
            instance = null;
        }

        #endregion

        /// <summary>
        /// Creates a new instance of the companies manager class.
        /// </summary>
        public static void Initialize(string bName, string pName, Int64 monies)
        {
            //Creates new instance of companies object.
            if (instance != null)
            {
                instance.Dispose();
            }

            if (instance != null)
            {
                throw new Exception("Companies object already initialized!");
            }

            instance = new Companies();

            // Creates player company and associated AI companies to compete with the player.
            _playerCompany = new PlayerCompany(bName, pName, monies);

            // TODO: Initialize AI players from here.
            _AICompanies = new List<AICompany>();

            // Initialize continent names and paths to images.
            string ImagePath = string.Format("{0}{1}Data{1}Earth{1}", Application.StartupPath,
                                             Path.DirectorySeparatorChar);
            _continentItems = new List<ContinentItem>
                                  {
                                      new ContinentItem(Continents.All, ImagePath + "worldmap_default.jpg"),
                                      new ContinentItem(Continents.Africa, ImagePath + "worldmap_africa.jpg"),
                                      new ContinentItem(Continents.Antarctica, ImagePath + "worldmap_antarctica.jpg"),
                                      new ContinentItem(Continents.Eurasia, ImagePath + "worldmap_eurasia.jpg"),
                                      new ContinentItem(Continents.NorthAmerica, ImagePath + "worldmap_northamerica.jpg"),
                                      new ContinentItem(Continents.Oceania, ImagePath + "worldmap_oceania.jpg"),
                                      new ContinentItem(Continents.SouthAmerica, ImagePath + "worldmap_southamerica.jpg")
                                  };
        }
    }
}


text:
require "amq/client/entity"
require "amq/client/queue"
require "amq/client/exchange"

module AMQ
  module Client
    class Channel

      #
      # Behaviors
      #

      extend RegisterEntityMixin
      include Entity
      extend ProtocolMethodHandlers

      register_entity :queue,    AMQ::Client::Queue
      register_entity :exchange, AMQ::Client::Exchange

      #
      # API
      #

      class ChannelOutOfBadError < StandardError # TODO: inherit from some AMQP error class defined in amq-protocol or use it straight away.
        def initialize(max, given)
          super("Channel max is #{max}, #{given} given.")
        end
      end

      DEFAULT_REPLY_TEXT = "Goodbye".freeze

      attr_reader :id

      attr_reader :exchanges_awaiting_declare_ok, :exchanges_awaiting_delete_ok
      attr_reader :queues_awaiting_declare_ok, :queues_awaiting_delete_ok, :queues_awaiting_bind_ok, :queues_awaiting_unbind_ok, :queues_awaiting_purge_ok, :queues_awaiting_consume_ok, :queues_awaiting_cancel_ok, :queues_awaiting_get_response

      attr_accessor :flow_is_active

      def initialize(connection, id)
        super(connection)

        @id        = id
        @exchanges = Hash.new
        @queues    = Hash.new
        @consumers = Hash.new

        reset_state!

        # 65536 is here for cases when channel is opened without passing a callback in,
        # otherwise channel_mix would be nil and it causes a lot of needless headaches.
        # lets just have this default. MK.
        channel_max = if @connection.open?
                        @connection.channel_max || 65536
                      else
                        65536
                      end

        if channel_max != 0 && !(0..channel_max).include?(id)
          raise ChannelOutOfBadError.new(channel_max, id)
        end
      end

      def consumers
        @consumers
      end # consumers

      # @return  [Array<Queue>]   Collection of queues that were declared on this channel.
      def queues
        @queues.values
      end

      # @return  [Array<Exchange>]  Collection of exchanges that were declared on this channel.
      def exchanges
        @exchanges.values
      end

      # AMQP connection this channel belongs to.
      #
      # @return [AMQ::Client::Connection] Connection this channel belongs to.
      def connection
        @connection
      end # connection

      # @group Channel lifecycle

      # Opens AMQP channel.
      #
      # @api public
      def open(&block)
        @connection.send_frame(Protocol::Channel::Open.encode(@id, AMQ::Protocol::EMPTY_STRING))
        @connection.channels[@id] = self
        self.status = :opening

        self.redefine_callback :open, &block
      end

      # Closes AMQP channel.
      #
      # @api public
      def close(reply_code = 200, reply_text = DEFAULT_REPLY_TEXT, class_id = 0, method_id = 0, &block)
        @connection.send_frame(Protocol::Channel::Close.encode(@id, reply_code, reply_text, class_id, method_id))

        self.redefine_callback :close, &block
      end

      # @endgroup

      # @group Message acknowledgements

      # Acknowledge one or all messages on the channel.
      #
      # @api public
      # @see http://bit.ly/htCzCX AMQP 0.9.1 protocol documentation (Section 1.8.3.13.)
      def acknowledge(delivery_tag, multiple = false)
        @connection.send_frame(Protocol::Basic::Ack.encode(self.id, delivery_tag, multiple))

        self
      end # acknowledge(delivery_tag, multiple = false)

      # Reject a message with given delivery tag.
      #
      # @api public
      # @see http://bit.ly/htCzCX AMQP 0.9.1 protocol documentation (Section 1.8.3.14.)
      def reject(delivery_tag, requeue = true)
        @connection.send_frame(Protocol::Basic::Reject.encode(self.id, delivery_tag, requeue))

        self
      end # reject(delivery_tag, requeue = true)

      # Notifies AMQ broker that consumer has recovered and unacknowledged messages need
      # to be redelivered.
      #
      # @return [Channel]  self
      #
      # @note RabbitMQ as of 2.3.1 does not support basic.recover with requeue = false.
      # @see http://bit.ly/htCzCX AMQP 0.9.1 protocol documentation (Section 1.8.3.16.)
      # @api public
      def recover(requeue = true, &block)
        @connection.send_frame(Protocol::Basic::Recover.encode(@id, requeue))

        self.redefine_callback :recover, &block
        self
      end # recover(requeue = false, &block)

      # @endgroup

      # @group QoS and flow handling

      # Requests a specific quality of service. The QoS can be specified for the current channel
      # or for all channels on the connection.
      #
      # @note RabbitMQ as of 2.3.1 does not support prefetch_size.
      # @api public
      def qos(prefetch_size = 0, prefetch_count = 32, global = false, &block)
        @connection.send_frame(Protocol::Basic::Qos.encode(@id, prefetch_size, prefetch_count, global))

        self.redefine_callback :qos, &block
        self
      end # qos(prefetch_size = 4096, prefetch_count = 32, global = false, &block)

      # Asks the peer to pause or restart the flow of content data sent to a consumer.
      # This is a simple flowcontrol mechanism that a peer can use to avoid overflowing its
      # queues or otherwise finding itself receiving more messages than it can process. Note that
      # this method is not intended for window control. It does not affect contents returned to
      # Queue#get callers.
      #
      # @param [Boolean] active Desired flow state.
      #
      # @see http://bit.ly/htCzCX AMQP 0.9.1 protocol documentation (Section 1.5.2.3.)
      # @api public
      def flow(active = false, &block)
        @connection.send_frame(Protocol::Channel::Flow.encode(@id, active))

        self.redefine_callback :flow, &block
        self
      end # flow(active = false, &block)

      # @return [Boolean]  True if flow in this channel is active (messages will be delivered to consumers that use this channel).
      #
      # @api public
      def flow_is_active?
        @flow_is_active
      end # flow_is_active?

      # @endgroup

      # @group Transactions

      # Sets the channel to use standard transactions. One must use this method at least
      # once on a channel before using #tx_tommit or tx_rollback methods.
      #
      # @api public
      def tx_select(&block)
        @connection.send_frame(Protocol::Tx::Select.encode(@id))

        self.redefine_callback :tx_select, &block
        self
      end # tx_select(&block)

      # Commits AMQP transaction.
      #
      # @api public
      def tx_commit(&block)
        @connection.send_frame(Protocol::Tx::Commit.encode(@id))

        self.redefine_callback :tx_commit, &block
        self
      end # tx_commit(&block)

      # Rolls AMQP transaction back.
      #
      # @api public
      def tx_rollback(&block)
        @connection.send_frame(Protocol::Tx::Rollback.encode(@id))

        self.redefine_callback :tx_rollback, &block
        self
      end # tx_rollback(&block)

      # @endgroup

      # @group Error handling

      # Defines a callback that will be executed when channel is closed after
      # channel-level exception.
      #
      # @api public
      def on_error(&block)
        self.define_callback(:error, &block)
      end

      # @endgroup

      #
      # Implementation
      #

      def register_exchange(exchange)
        raise ArgumentError, "argument is nil!" if exchange.nil?

        @exchanges[exchange.name] = exchange
      end # register_exchange(exchange)

      # Finds exchange in the exchanges cache on this channel by name. Exchange only exists in the cache if
      # it was previously instantiated on this channel.
      #
      # @param [String] name Exchange name
      # @return [AMQ::Client::Exchange] Exchange (if found)
      # @api plugin
      def find_exchange(name)
        @exchanges[name]
      end

      def register_queue(queue)
        raise ArgumentError, "argument is nil!" if queue.nil?

        @queues[queue.name] = queue
      end # register_queue(queue)

      def find_queue(name)
        @queues[name]
      end

      def reset_state!
        @flow_is_active                = true

        @queues_awaiting_declare_ok    = Array.new
        @exchanges_awaiting_declare_ok = Array.new

        @queues_awaiting_delete_ok     = Array.new

        @exchanges_awaiting_delete_ok  = Array.new
        @queues_awaiting_purge_ok      = Array.new
        @queues_awaiting_bind_ok       = Array.new
        @queues_awaiting_unbind_ok     = Array.new
        @queues_awaiting_consume_ok    = Array.new
        @queues_awaiting_cancel_ok     = Array.new

        @queues_awaiting_get_response  = Array.new

        @callbacks                     = Hash.new
      end # reset_state!

      def handle_connection_interruption(method = nil)
        self.reset_state!
      end # handle_connection_interruption

      def handle_open_ok(open_ok)
        self.status = :opened
        self.exec_callback_once_yielding_self(:open, open_ok)
      end

      def handle_close_ok(close_ok)
        self.status = :closed
        self.exec_callback_once_yielding_self(:close, close_ok)
      end

      def handle_close(channel_close)
        self.status = :closed
        self.exec_callback_yielding_self(:error, channel_close)

        self.handle_connection_interruption(channel_close)
      end

      self.handle(Protocol::Channel::OpenOk) do |connection, frame|
        channel = connection.channels[frame.channel]
        channel.handle_open_ok(frame.decode_payload)
      end

      self.handle(Protocol::Channel::CloseOk) do |connection, frame|
        method   = frame.decode_payload
        channels = connection.channels

        channel  = channels[frame.channel]
        channels.delete(channel)
        channel.handle_close_ok(method)
      end

      self.handle(Protocol::Channel::Close) do |connection, frame|
        method   = frame.decode_payload
        channels = connection.channels
        channel  = channels[frame.channel]

        channel.handle_close(method)
      end

      self.handle(Protocol::Basic::QosOk) do |connection, frame|
        channel = connection.channels[frame.channel]
        channel.exec_callback(:qos, frame.decode_payload)
      end

      self.handle(Protocol::Basic::RecoverOk) do |connection, frame|
        channel = connection.channels[frame.channel]
        channel.exec_callback(:recover, frame.decode_payload)
      end

      self.handle(Protocol::Channel::FlowOk) do |connection, frame|
        channel  = connection.channels[frame.channel]
        method   = frame.decode_payload

        channel.flow_is_active = method.active
        channel.exec_callback(:flow, method)
      end

      self.handle(Protocol::Tx::SelectOk) do |connection, frame|
        channel = connection.channels[frame.channel]
        channel.exec_callback(:tx_select, frame.decode_payload)
      end

      self.handle(Protocol::Tx::CommitOk) do |connection, frame|
        channel = connection.channels[frame.channel]
        channel.exec_callback(:tx_commit, frame.decode_payload)
      end

      self.handle(Protocol::Tx::RollbackOk) do |connection, frame|
        channel = connection.channels[frame.channel]
        channel.exec_callback(:tx_rollback, frame.decode_payload)
      end
    end # Channel
  end # Client
end # AMQ


text:
This directory contains artifacts required for importing
The Covid19 data collected by Google Health into Data Commons.

## About the Dataset

### Overview

Google Health collected, reconciled, and uniformed the COVID data from [The COVID Tracking Project](https://github.com/COVID19Tracking/covid-tracking-data), [Johns Hopkins University](https://github.com/CSSEGISandData/COVID-19), [California Health and Human Services](https://data.chhs.ca.gov/dataset/healthcare-facility-bed-types-and-counts) for research and prediction use.

### Coverage

The US dataset contains data points from 51 states (including one special: D.C) and 3143 counties and cities, coded using common Data Commons dcids; the dates range from 2020-1-22 to latest day.

### Variables

The dataset contains observations for the following variables:
- dcs:CumulativeCount_MedicalTest_COVID_19
- dcs:CumulativeCount_MedicalTest_COVID_19_Positive
- dcs:CumulativeCount_MedicalTest_COVID_19_Negative
- dcs:CumulativeCount_MedicalConditionIncident_COVID_19_PatientRecovered
- dcs:CumulativeCount_MedicalConditionIncident_COVID_19_PatientDeceased
- dcs:Count_MedicalConditionIncident_COVID_19_PatientHospitalized
- dcs:CumulativeCount_MedicalConditionIncident_COVID_19_PatientHospitalized
- dcs:Count_MedicalConditionIncident_COVID_19_PatientInICU
- dcs:CumulativeCount_MedicalConditionIncident_COVID_19_PatientInICU
- dcs:Count_MedicalConditionIncident_COVID_19_PatientOnVentilator
- dcs:CumulativeCount_MedicalConditionIncident_COVID_19_PatientOnVentilator

## Artifacts:

- [Google_Health_COVID19_US.csv](Google_Health_COVID19_US.csv): the cleaned CSV generated from Google Health pipeline.
- [Google_Health_COVID19_US.tmcf](Google_Health_COVID19_US.tmcf): the mapping file (Template MCF).


text:
var typeOf = require('type-of');
var extend = require('extend');
var Delegate = require('dom-delegate');
var store = require('store');

// a bad toggleClass method
var toggleClass = require('./utils/toggle_class.js');

// a possibly good string escaping method
var HTMLEscape = require('./utils/html_escape.js');

var InspectorJSON = function( params ){

	params = params || {};
	var defaults = {
		element: 'body',
		debug: false,
		collapsed: true,
		url: location.pathname
	};

	params = extend( defaults, params );
	// if the supplied element isn't an element, try to select it by ID
	if( typeOf( params.element ) !== 'element' ) params.element = document.getElementById( params.element );

	var collapse_states = store.get( params.url +':inspectorJSON/collapse_states' ) || {};
	this.el = params.element;
	this.el.className += ' inspector-json viewer';

	// Delegate the click event for collapse/uncollapse of JSON levels
	this.event_delegator = new Delegate( this.el );
	this.event_delegator.on( 'click', 'li.object > a, li.array > a', function( e ){
		e.preventDefault();
		var parent = this.parentNode;
		var path = parent.getAttribute('data-path');
		toggleClass( parent, 'collapsed' );
		if( !/\bcollapsed\b/ig.exec( parent.className ) ){
			collapse_states[path] = true;
		}
		else {
			delete collapse_states[path];
		}
		store.set( params.url +':inspectorJSON/collapse_states', collapse_states );
	});

	// Create the JSON Viewer on the specified element
	this.view = function( json ){

		var start, end;

		if( params.debug ){
			start = new Date().getTime();
		}

		// Create markup from a value
		var processItem = function( item, parent, key, path ){

			var type = typeOf( item );
			var parent_type = typeOf( parent );
			var markup = '';

			// Create a string representation of the JSON path to this value
			if( parent_type === 'array' ){
				path += '['+ key +']';
			}
			else if( parent_type === 'object' ){
				path += '.'+ key;
			}
			else {
				path = key || 'this';
			}

			// Start the

			if( parent ){
				markup += ( collapse_states[path] || !params.collapsed || ( type !== 'object' && type !== 'array' ) ) ?
					'
' :
					'
';
			}

			// Generate markup by value type. Recursion for arrays and objects.
			if( type === 'object' ){
				if( key ){
					markup += ''+ key + '';
				}
				markup += '
';
				for( key in item ){
					markup += processItem( item[key], item, key, path );
				}
				markup += '
';
			}
			else if( type === 'array' ){
				if( key ){
					markup += ''+ key +'Array('+ item.length +')';
				}
				markup += '
';
				for( var i in item ){
					markup += processItem( item[i], item, i, path );
				}
				markup += '
';
			}
			else if( type === 'string' ){
				markup += ''+ key + '"'+ HTMLEscape( item ) +'"';
			}
			else if( type === 'number' ){
				markup += ''+ key + '<var>'+ item.toString() +'</var>';
			}
			else if( type === 'boolean' ){
				markup += ''+ key + ''+ item.toString() + '';
			}
			else if( type === 'null' ){
				markup += ''+ key + 'null';
			}

			// End the

			if( parent ){
				markup += '
';
			}

			return markup;

		};

		if( typeOf( json ) === 'string' ){
			json = JSON.parse( json );
		}

		var root = processItem( json );
		this.el.innerHTML = root;

		if( params.debug ){
			end = new Date().getTime();
			console.log('Inspector JSON: Rendered in '+ ( end - start ) +'ms');
		}

	};

	// LEAVE NO EVIDENCE!!!
	this.destroy = function(){

		this.event_delegator.off();
		this.el.innerHTML = '';

	};

	// if json is supplied, view it immediately
	if( !params.json ){
		try {
			params.json = JSON.parse( this.el.textContent || this.el.innerText );
		}
		catch( err ){
			if( params.debug ){
				console.log('Inspector JSON: Element contents are not valid JSON');
			}
		}
	}
	if( params.json ){
		this.view( params.json );
	}

};

module.exports = InspectorJSON;


text:
require 'rails_helper'

RSpec.describe "spree/vendors/new", type: :view do
  before(:each) do
    assign(:spree_vendor, Spree::Vendor.new(
      :name => "MyString",
      :address1 => "MyString",
      :address2 => "MyString",
      :city => "MyString",
      :state => "MyString",
      :country => "MyString",
      :phone => "MyString",
      :fax => "MyString",
      :active => false,
      :leadtimedays => 1
    ))
  end

  it "renders new spree_vendor form" do
    render

    assert_select "form[action=?][method=?]", spree_vendors_path, "post" do

      assert_select "input#spree_vendor_name[name=?]", "spree_vendor[name]"

      assert_select "input#spree_vendor_address1[name=?]", "spree_vendor[address1]"

      assert_select "input#spree_vendor_address2[name=?]", "spree_vendor[address2]"

      assert_select "input#spree_vendor_city[name=?]", "spree_vendor[city]"

      assert_select "input#spree_vendor_state[name=?]", "spree_vendor[state]"

      assert_select "input#spree_vendor_country[name=?]", "spree_vendor[country]"

      assert_select "input#spree_vendor_phone[name=?]", "spree_vendor[phone]"

      assert_select "input#spree_vendor_fax[name=?]", "spree_vendor[fax]"

      assert_select "input#spree_vendor_active[name=?]", "spree_vendor[active]"

      assert_select "input#spree_vendor_leadtimedays[name=?]", "spree_vendor[leadtimedays]"
    end
  end
end


text:
var createSpec = require('spec-js');

function trigger(eventNames, event){
    var gameLoop = this,
        eventNames = eventNames.split(' ');

    if(eventNames.length > 1){
        eventNames.forEach(function(eventName){
            gameLoop.trigger(eventName, event);
        });
    }

    var eventName = eventNames.pop();

    if(this._events[eventName]){
        this._events[eventName].forEach(function(callback){
            callback(event);
        });
    }
}

function on(eventNames, callback){
    var gameLoop = this,
        eventNames = eventNames.split(' ');

    if(eventNames.length > 1){
        eventNames.forEach(function(eventName){
            gameLoop.on(eventName, callback);
        });
    }

    var eventName = eventNames[0],
        events = this._events[eventName] = this._events[eventName] || [];

    events.push(callback);
}

function gameLoop(zole){
    if(zole._run){
        zole.trigger('step', zole);
        setTimeout(function(){
            gameLoop(zole, new Date())
        }, 10);
    }
}

function renderLoop(zole){
    if(zole._run){
        zole.trigger('frame', zole);
        window.requestAnimationFrame(function(timestamp){
            renderLoop(zole, timestamp)
        });
    }
}

function startGame(){
    this._run = true;
    gameLoop(this);
}

function startRender(){
    this._run = true;
    renderLoop(this);
}

function pause(){
    this._run = true;
}

function GameLoop(context){
    this._events = {};
    this.context = context;
}
GameLoop.prototype.on = on;
GameLoop.prototype.pause = pause;
GameLoop.prototype.trigger = trigger;

function ProcessLoop(context){
}
ProcessLoop = createSpec(ProcessLoop, GameLoop);
ProcessLoop.prototype.start = startGame;

function RenderLoop(context){
}
RenderLoop = createSpec(RenderLoop, GameLoop);
RenderLoop.prototype.start = startRender;

module.exports = {
    ProcessLoop: ProcessLoop,
    RenderLoop: RenderLoop
};


text:
package com.dremio.exec.expr.fn.hll;

import org.apache.calcite.sql.SqlAggFunction;
import org.apache.calcite.sql.SqlFunction;
import org.apache.calcite.sql.SqlFunctionCategory;
import org.apache.calcite.sql.SqlIdentifier;
import org.apache.calcite.sql.SqlKind;
import org.apache.calcite.sql.parser.SqlParserPos;
import org.apache.calcite.sql.type.OperandTypes;
import org.apache.calcite.sql.type.ReturnTypes;
import org.apache.calcite.sql.type.SqlTypeName;

public class HyperLogLog {

  public static final int HLL_VARBINARY_SIZE = 65536;

  public static class SqlHllDecodeOperator extends SqlFunction {
    public SqlHllDecodeOperator() {
      super(new SqlIdentifier("HLL_DECODE", SqlParserPos.ZERO), ReturnTypes.BIGINT_NULLABLE, null, OperandTypes.BINARY, null, SqlFunctionCategory.USER_DEFINED_FUNCTION);
    }

    @Override
    public boolean equals(final Object other) {
      return other instanceof SqlHllDecodeOperator;
    }

    @Override
    public int hashCode() {
      return 3;
    }

  }

  public static class SqlHllAggFunction extends SqlAggFunction {
    public SqlHllAggFunction() {
      super("HLL",
        null,
        SqlKind.OTHER_FUNCTION,
        ReturnTypes.explicit(SqlTypeName.VARBINARY, HLL_VARBINARY_SIZE),
        null,
        OperandTypes.ANY,
        SqlFunctionCategory.USER_DEFINED_FUNCTION,
        false,
        false
      );
    }
  }

  public static class SqlHllMergeAggFunction extends SqlAggFunction {
    public SqlHllMergeAggFunction() {
      super("HLL_MERGE",
        null,
        SqlKind.OTHER_FUNCTION,
        ReturnTypes.explicit(SqlTypeName.VARBINARY, HLL_VARBINARY_SIZE),
        null,
        OperandTypes.BINARY,
        SqlFunctionCategory.USER_DEFINED_FUNCTION,
        false,
        false
      );
    }
  }

  public static class SqlNdvAggFunction extends SqlAggFunction {
    public SqlNdvAggFunction() {
      super("NDV",
        null,
        SqlKind.OTHER_FUNCTION,
        ReturnTypes.BIGINT,
        null,
        OperandTypes.ANY,
        SqlFunctionCategory.USER_DEFINED_FUNCTION,
        false,
        false
      );
    }
  }

}


text:
import ujson

filename = 'config.json'
vars = {}
def init():
    try:
        file = open(filename, 'r')
    except OSError:
        print('No config.json file')
        return
    json = file.read()
    file.close()
    json = json.replace('\n', '').replace('\t', '')
    json = ' '.join(json.split()) #substitute multiple spaces with one
    try:
        global vars
        vars = ujson.loads(json)
        print('config init')
    except ValueError:
        print("File config.json doesn't contain proper JSON.")

def get(name):
    global vars
    parts = name.split('.')
    value = vars[parts[0]]
    for part in parts[1:]:
        value = value[part]
    return value

def exists(name):
    try:
        get(name)
        return True
    except KeyError:
        return False

def save():
    try:
        file = open(filename, 'w')
    except OSError:
        print('No config.json file')
        return
    global vars
    json = ujson.dumps(vars)
    file.write(json)
    file.close()

if len(vars) == 0:
    init()


text:
<?php

namespace Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Entity\CareDrgRelatedCode
 *
 * InnoDB free: 11264 kB
 *
 * @ORM\Entity(repositoryClass="CareDrgRelatedCodeRepository")
 * @ORM\Table(name="care_drg_related_codes")
 */
class CareDrgRelatedCode
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $nr;

    /**
     * @ORM\Column(type="integer")
     */
    protected $group_nr;

    /**
     * @ORM\Column(type="string", length=15)
     */
    protected $code;

    /**
     * @ORM\Column(type="string", length=15)
     */
    protected $code_parent;

    /**
     * @ORM\Column(type="string", length=15)
     */
    protected $code_type;

    /**
     * @ORM\Column(type="integer")
     */
    protected $rank;

    /**
     * @ORM\Column(type="string", length=15)
     */
    protected $status;

    /**
     * @ORM\Column(type="text")
     */
    protected $history;

    /**
     * @ORM\Column(type="string", length=25)
     */
    protected $modify_id;

    /**
     * @ORM\Column(type="datetime")
     */
    protected $modify_time;

    /**
     * @ORM\Column(type="string", length=25)
     */
    protected $create_id;

    /**
     * @ORM\Column(type="datetime")
     */
    protected $create_time;

    public function __construct()
    {
    }

    /**
     * Set the value of nr.
     *
     * @param integer $nr
     * @return \Entity\CareDrgRelatedCode
     */
    public function setNr($nr)
    {
        $this->nr = $nr;

        return $this;
    }

    /**
     * Get the value of nr.
     *
     * @return integer
     */
    public function getNr()
    {
        return $this->nr;
    }

    /**
     * Set the value of group_nr.
     *
     * @param integer $group_nr
     * @return \Entity\CareDrgRelatedCode
     */
    public function setGroupNr($group_nr)
    {
        $this->group_nr = $group_nr;

        return $this;
    }

    /**
     * Get the value of group_nr.
     *
     * @return integer
     */
    public function getGroupNr()
    {
        return $this->group_nr;
    }

    /**
     * Set the value of code.
     *
     * @param string $code
     * @return \Entity\CareDrgRelatedCode
     */
    public function setCode($code)
    {
        $this->code = $code;

        return $this;
    }

    /**
     * Get the value of code.
     *
     * @return string
     */
    public function getCode()
    {
        return $this->code;
    }

    /**
     * Set the value of code_parent.
     *
     * @param string $code_parent
     * @return \Entity\CareDrgRelatedCode
     */
    public function setCodeParent($code_parent)
    {
        $this->code_parent = $code_parent;

        return $this;
    }

    /**
     * Get the value of code_parent.
     *
     * @return string
     */
    public function getCodeParent()
    {
        return $this->code_parent;
    }

    /**
     * Set the value of code_type.
     *
     * @param string $code_type
     * @return \Entity\CareDrgRelatedCode
     */
    public function setCodeType($code_type)
    {
        $this->code_type = $code_type;

        return $this;
    }

    /**
     * Get the value of code_type.
     *
     * @return string
     */
    public function getCodeType()
    {
        return $this->code_type;
    }

    /**
     * Set the value of rank.
     *
     * @param integer $rank
     * @return \Entity\CareDrgRelatedCode
     */
    public function setRank($rank)
    {
        $this->rank = $rank;

        return $this;
    }

    /**
     * Get the value of rank.
     *
     * @return integer
     */
    public function getRank()
    {
        return $this->rank;
    }

    /**
     * Set the value of status.
     *
     * @param string $status
     * @return \Entity\CareDrgRelatedCode
     */
    public function setStatus($status)
    {
        $this->status = $status;

        return $this;
    }

    /**
     * Get the value of status.
     *
     * @return string
     */
    public function getStatus()
    {
        return $this->status;
    }

    /**
     * Set the value of history.
     *
     * @param string $history
     * @return \Entity\CareDrgRelatedCode
     */
    public function setHistory($history)
    {
        $this->history = $history;

        return $this;
    }

    /**
     * Get the value of history.
     *
     * @return string
     */
    public function getHistory()
    {
        return $this->history;
    }

    /**
     * Set the value of modify_id.
     *
     * @param string $modify_id
     * @return \Entity\CareDrgRelatedCode
     */
    public function setModifyId($modify_id)
    {
        $this->modify_id = $modify_id;

        return $this;
    }

    /**
     * Get the value of modify_id.
     *
     * @return string
     */
    public function getModifyId()
    {
        return $this->modify_id;
    }

    /**
     * Set the value of modify_time.
     *
     * @param datetime $modify_time
     * @return \Entity\CareDrgRelatedCode
     */
    public function setModifyTime($modify_time)
    {
        $this->modify_time = $modify_time;

        return $this;
    }

    /**
     * Get the value of modify_time.
     *
     * @return datetime
     */
    public function getModifyTime()
    {
        return $this->modify_time;
    }

    /**
     * Set the value of create_id.
     *
     * @param string $create_id
     * @return \Entity\CareDrgRelatedCode
     */
    public function setCreateId($create_id)
    {
        $this->create_id = $create_id;

        return $this;
    }

    /**
     * Get the value of create_id.
     *
     * @return string
     */
    public function getCreateId()
    {
        return $this->create_id;
    }

    /**
     * Set the value of create_time.
     *
     * @param datetime $create_time
     * @return \Entity\CareDrgRelatedCode
     */
    public function setCreateTime($create_time)
    {
        $this->create_time = $create_time;

        return $this;
    }

    /**
     * Get the value of create_time.
     *
     * @return datetime
     */
    public function getCreateTime()
    {
        return $this->create_time;
    }

    public function __sleep()
    {
        return array('nr', 'group_nr', 'code', 'code_parent', 'code_type', 'rank', 'status', 'history', 'modify_id', 'modify_time', 'create_id', 'create_time');
    }
}


text:
__file__ = 'QC_v1'
__date__ = '6/16/2015'
__author__ = 'ABREZNIC'
import arcpy, datetime, os

output = "C:\\TxDOT\\Scripts\\javascript\\Guardrail\\Snake\\QC"
GET = "C:\\TxDOT\\Scripts\\javascript\\Guardrail\\Snake\\QC\\Analysis\\GET_20150629_QC.gdb\\GuardrailEndTreatments"
roadways = "Database Connections\\Connection to Comanche.sde\\TPP_GIS.APP_TPP_GIS_ADMIN.Roadways\\TPP_GIS.APP_TPP_GIS_ADMIN.TXDOT_Roadways"
offices = "Database Connections\\Connection to Comanche.sde\\TPP_GIS.APP_TPP_GIS_ADMIN.Facility\\TPP_GIS.APP_TPP_GIS_ADMIN.Office"

now = datetime.datetime.now()
curMonth = now.strftime("%m")
curDay = now.strftime("%d")
curYear = now.strftime("%Y")
arcpy.CreateFileGDB_management(output, "QC_GET" + curYear + curMonth + curDay)
werkspace = output + os.sep + "QC_GET" + curYear + curMonth + curDay + ".gdb"
print "Workspace created."

###############bad speed and accuracy##########
query = "(Speed = '0' OR Speed IS NULL) AND AccuracyFeet > 250"

badGET = werkspace + os.sep + "GET_BadSpdAcc"
arcpy.Select_analysis(GET, badGET, query)
print "Bad accuracy and speed records found."

#########cursor checks############

##### same lat, long check
list = []
latlongFreq = werkspace + os.sep + "LatLongFreq"
arcpy.Frequency_analysis(GET, latlongFreq, ["Latitude", "Longitude"])
cursor = arcpy.da.UpdateCursor(latlongFreq, ["FREQUENCY", "Latitude", "Longitude"])
for row in cursor:
    if row[0] == 1:
        cursor.deleteRow()
    else:
        identifier = str(row[1]) + str(row[2])
        list.append(identifier)
del cursor
print "Lat/Long Duplicates identified."

dupes = werkspace + os.sep + "DupeLatLong"
arcpy.Copy_management(GET, dupes)
cursor = arcpy.da.UpdateCursor(dupes, ["Latitude", "Longitude"])
for row in cursor:
    identifier = str(row[0]) + str(row[1])
    if identifier not in list:
        cursor.deleteRow()
del cursor
print "DupeLatLong feature class complete."

############txdot offices buffer############
officeBuff = werkspace + os.sep + "TxdotOfficeBuffer"
arcpy.Buffer_analysis(offices, officeBuff, ".1 Miles")
print "Office buffer created."

officeGET = werkspace + os.sep + "GET_officeTests"
arcpy.Clip_analysis(GET, officeBuff, officeGET)
print "Office GETs found."

############onsystem buffer############
query2 = "RTE_CLASS = '1'"

onsystem = werkspace + os.sep + "OnSystemRoadways"
arcpy.Select_analysis(roadways, onsystem, query2)
print "OnSystem roads isolated."

onsysBuff = werkspace + os.sep + "OnSystemBuffer"
arcpy.Buffer_analysis(onsystem, onsysBuff, "125 Feet")
print "Roads buffer created."

onsysGET = werkspace + os.sep + "GET_offRoadways"
arcpy.Erase_analysis(badGET, onsysBuff, onsysGET)
print "Road GETs found."

print "that's all folks!!"


text:
package jp.co.acroquest.endosnipe.data.util;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import jp.co.acroquest.endosnipe.common.util.ResourceUtil;
import jp.co.acroquest.endosnipe.common.util.StreamUtil;
import junit.framework.TestCase;

/**
 * {@link ZipUtil} のためのテストクラスです。

 *
 * @author y-komori
 */
public class ZipUtilTest extends TestCase
{
    private static final int BUF_SIZE = 8192;

    /**
     * 圧縮と解凍のテストを行います。

     */
    public void testZipAndUnzip()
    {
        ByteArrayOutputStream out = null;
        BufferedReader br1 = null;
        BufferedReader br2 = null;
        try
        {
            // 圧縮処理
            String path = "javelin_010k.jvn";
            File file = ResourceUtil.getResourceAsFile(getClass(), path);
            out = new ByteArrayOutputStream(BUF_SIZE);
            ZipUtil.createZip(out, new FileInputStream(file), path);
            byte[] zippedArray = out.toByteArray();
            StreamUtil.closeStream(out);

            // 展開処理とオリジナルとの比較

            // 展開したストリーム
            InputStream is = ZipUtil.unzipFromByteArray(new ByteArrayInputStream(zippedArray));
            br1 = new BufferedReader(new InputStreamReader(is));
            // オリジナルのストリーム
            br2 = new BufferedReader(new FileReader(file));

            String line1;
            String line2;
            int lineCount = 1;
            while ((line1 = br1.readLine()) != null)
            {
                line2 = br2.readLine();
                assertEquals("line:" + lineCount++, line2, line1);
            }
        }
        catch (FileNotFoundException ex)
        {
            fail(ex.getMessage());
        }
        catch (IOException ex)
        {
            fail(ex.getMessage());
        }
        finally
        {
            StreamUtil.closeStream(out);
            StreamUtil.closeStream(br1);
            StreamUtil.closeStream(br2);
        }
    }
}


text:
$:.unshift(File.join(File.dirname(__FILE__), "..", "lib"))
gem 'moo'
require 'moo'
require 'rspec'

RSpec.configure do |c|
  c.alias_example_to(:they)
  c.color_enabled = true
  c.formatter = 'documentation'
end


text:
package concurrency;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.DoubleStream;

/**
 * Order of the output can't be determined as all are printed separate threads
 *
 */

public class UsingThreadPoolSimple {
    public static void main(String[] args) {
        ExecutorService service = Executors.newFixedThreadPool(10);
        DoubleStream.of(3.14159,2.71828) // b1
                .forEach(c -> service.submit( // b2
                        () -> System.out.println(10*c))); // b3
        service.execute(() -> System.out.println("Printed")); // b4
    }
}