text:
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

using System;
using System.Runtime.InteropServices;
using System.ComponentModel;

namespace Fusion.Mathematics
{
    /// <summary>
    /// Defines a two component vector, using half precision floating point coordinates.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    [Serializable]
    [TypeConverter(typeof(Fusion.Design.Half2Converter))]
    public struct Half2 : IEquatable<Half2>
    {
        /// <summary>
        /// Gets or sets the X component of the vector.
        /// </summary>
        /// <value>The X component of the vector.</value>
        public Half X;
        /// <summary>
        /// Gets or sets the Y component of the vector.
        /// </summary>
        /// <value>The Y component of the vector.</value>
        public Half Y;

        /// <summary>
        /// Initializes a new instance of the <see cref="Half2" /> structure.
        /// </summary>
        /// <param name="x">The X component.</param>
        /// <param name="y">The Y component.</param>
        public Half2(Half x, Half y)
        {
            this.X = x;
            this.Y = y;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Half2" /> structure.
        /// </summary>
        /// <param name="x">The X component.</param>
        /// <param name="y">The Y component.</param>
        public Half2(float x, float y)
        {
            this.X = new Half(x);
            this.Y = new Half(y);
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Half2" /> structure.
        /// </summary>
        /// <param name="x">The X component.</param>
        /// <param name="y">The Y component.</param>
        public Half2(ushort x, ushort y)
        {
            this.X = new Half(x);
            this.Y = new Half(y);
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Half2" /> structure.
        /// </summary>
        /// <param name="value">The value to set for both the X and Y components.</param>
        public Half2(Half value)
        {
            this.X = value;
            this.Y = value;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Half2" /> structure.
        /// </summary>
        /// <param name="value">Value to initialize X and Y components with.</param>
        public Half2(float value)
        {
            this.X = new Half(value);
            this.Y = new Half(value);
        }

        /// <summary>
        /// Performs an explicit conversion from <see cref="Vector2"/> to <see cref="Half2"/>.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns>The result of the conversion.</returns>
        public static implicit operator Half2(Vector2 value)
        {
            return new Half2(value.X, value.Y);
        }

        /// <summary>
        /// Performs an explicit conversion from <see cref="Half2"/> to <see cref="Vector2"/>.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns>The result of the conversion.</returns>
        public static implicit operator Vector2(Half2 value)
        {
            return new Vector2(value.X, value.Y);
        }

        /// <summary>
        /// Tests for equality between two objects.
        /// </summary>
        /// <param name="left">The first value to compare.</param>
        /// <param name="right">The second value to compare.</param>
        /// <returns>
        /// <c>true</c> if <paramref name="left" /> has the same value as <paramref name="right" />; otherwise, <c>false</c>.</returns>
        public static bool operator ==(Half2 left, Half2 right)
        {
            return Equals(ref left, ref right);
        }

        /// <summary>
        /// Tests for inequality between two objects.
        /// </summary>
        /// <param name="left">The first value to compare.</param>
        /// <param name="right">The second value to compare.</param>
        /// <returns>
        /// <c>true</c> if <paramref name="left" /> has a different value than <paramref name="right" />; otherwise, <c>false</c>.</returns>
        [return: MarshalAs(UnmanagedType.U1)]
        public static bool operator !=(Half2 left, Half2 right)
        {
            return !Equals(ref left, ref right);
        }

        /// <summary>
        /// Returns the hash code for this instance.
        /// </summary>
        /// <returns>A 32-bit signed integer hash code.</returns>
        public override int GetHashCode()
        {
            unchecked
            {
                return (X.GetHashCode() * 397) ^ Y.GetHashCode();
            }
        }

        /// <summary>
        /// Determines whether the specified object instances are considered equal.
        /// </summary>
        /// <param name="value1" />
        /// <param name="value2" />
        /// <returns>
        /// <c>true</c> if <paramref name="value1" /> is the same instance as <paramref name="value2" /> or
        /// if both are <c>null</c> references or if <c>value1.Equals(value2)</c> returns <c>true</c>; otherwise, <c>false</c>.</returns>
        public static bool Equals(ref Half2 value1, ref Half2 value2)
        {
            return ((value1.X == value2.X) && (value1.Y == value2.Y));
        }

        /// <summary>
        /// Returns a value that indicates whether the current instance is equal to the specified object.
        /// </summary>
        /// <param name="other">Object to make the comparison with.</param>
        /// <returns>
        /// <c>true</c> if the current instance is equal to the specified object; <c>false</c> otherwise.</returns>
        public bool Equals(Half2 other)
        {
            return ((this.X == other.X) && (this.Y == other.Y));
        }

        /// <summary>
        /// Returns a value that indicates whether the current instance is equal to a specified object.
        /// </summary>
        /// <param name="obj">Object to make the comparison with.</param>
        /// <returns>
        /// <c>true</c> if the current instance is equal to the specified object; <c>false</c> otherwise.</returns>
        public override bool Equals(object obj)
        {
            if (obj == null)
            {
                return false;
            }
            if (!ReferenceEquals(obj.GetType(), typeof(Half2)))
            {
                return false;
            }
            return this.Equals((Half2)obj);
        }
    }
}


text:
/*
 * This file contains unit tests for nextcellent gallery
 * The test will perform if you add the nextcellent=true parameter to the URL for the gallery plugin.
 */

var nxc_test = {

    post: {},

    testContent: 'This is the content of the unit test &#8211 post.  This is content after the more tag to make sure we a reading it.',
    testContent2: 'This is the content of the unit test &#8211 post.  This is content after the more tag to make sure we a reading it. - CHANGED',
    testContent3: 'This is the content of the unit test &#8211 post.  This is content after the more tag to make sure we a reading it. - CHANGED DRAFT',

    runTests: function() {
        nxc_test.isDraftsDrawerVisible = edcal.isDraftsDrawerVisible;

        edcal.setDraftsDrawerVisible(true, function() {
            nxc_test.startTests();
        });
    },

    startTests: function() {
        /*FZSM: this shouldn't be necessary, since we deal with css file before*/
        /*
        jQuery('head').append('<link>');
        css = jQuery('head').children(':last');
        css.attr({
            rel: 'stylesheet',
            type: 'text/css',
            href: edcal.plugin_url + '/lib/qunit.css'
        });
*/

        jQuery('#wpbody-content .wrap').append('

'); //append on bottom of admin page.

        jQuery('#edcal-qunit').append('
WordPress Nextcellent Gallery Unit Tests
' +
                                      '

' +
                                      '

' +
                                      '

' +
                                      '

' +
                                      '
test markup
');

        nxc_test.moveTests();
    },

    nxt_test1: function() {
        expect(1);
        ok(true,'simple test to check Qunit functionality');
        //for the moment I don't even know if the start function is about something, so I don't use it

    }, //End nextcellent test, the rest are examples!
    //One question: QUnit can be useful also for other things than Javascript?

    //Following are examples to take advantage as future reference (from editorial calendar plugin)
    getFirstDate: function() {
         var api = jQuery('#edcal_scrollable').scrollable();
         var items = api.getVisibleItems();

         return edcal.getDayFromDayId(items.eq(0).children('.edcal_row').children('.day:first').attr('id'));
    },

    getLastDate: function() {
         var api = jQuery('#edcal_scrollable').scrollable();
         var items = api.getVisibleItems();

         return edcal.getDayFromDayId(items.eq(edcal.weeksPref - 1).children('.edcal_row').children('.day:last').attr('id'));
    },

    moveTests: function() {
         var curSunday = edcal.nextStartOfWeek(Date.today()).add(-1).weeks();

         edcal.moveTo(Date.today());

         /*
          * We'll start of with a series of tests about moving the calendar around
          */
         test('Move to today and check visible dates', function() {
             expect(2);
             ok(nxc_test.getFirstDate().equals(curSunday.clone()), 'firstDate should match ' + curSunday);

             ok(nxc_test.getLastDate().equals(curSunday.clone().add(edcal.weeksPref).weeks().add(-1).days()),
                'lastDate should match ' + curSunday);
         });

         asyncTest('Move 1 week in the future and check visible dates', function() {
             expect(2);
             edcal.move(1, true, function() {
                 ok(nxc_test.getFirstDate().equals(curSunday.clone().add(1).weeks()), 'firstDate should match ' + curSunday);

                 ok(nxc_test.getLastDate().equals(curSunday.clone().add(edcal.weeksPref).weeks().add(-1).days().add(1).weeks()),
                    'lastDate should match ' + curSunday);

                 edcal.move(1, false, function() {
                     start();
                     nxc_test.testMoveFourWeeks();
                 });
             });
         });

         return;

    },

    testMoveFourWeeks: function() {
         var curSunday = edcal.nextStartOfWeek(Date.today()).add(-1).weeks();

         /*
          * Now we'll move 4 weeks into the future
          */
         asyncTest('Move 4 weeks in the future and check visible dates', function() {
             expect(2);

             edcal.move(4, true, function() {
                 ok(nxc_test.getFirstDate().equals(curSunday.clone().add(4).weeks()), 'firstDate should match ' + curSunday);

                 ok(nxc_test.getLastDate().equals(curSunday.clone().add(edcal.weeksPref).weeks().add(-1).days().add(4).weeks()),
                    'lastDate should match ' + curSunday);

                 edcal.move(4, false, function() {
                     start();
                     nxc_test.testMoveEightWeeks();
                 });
             });

         });
    },

    testMoveEightWeeks: function() {
         var curSunday = edcal.nextStartOfWeek(Date.today()).add(-1).weeks();

         /*
          * Now 8 weeks into the past
          */
         asyncTest('Move 8 weeks in the past and check visible dates', function() {
             expect(2);

             edcal.move(8, false, function() {
                 ok(nxc_test.getFirstDate().equals(curSunday.clone().add(-8).weeks()), 'firstDate should match ' + curSunday);

                 ok(nxc_test.getLastDate().equals(curSunday.clone().add(edcal.weeksPref).weeks().add(-1).days().add(-8).weeks()),
                    'lastDate should match ' + curSunday);

                 edcal.move(8, true, function() {
                     start();
                     nxc_test.testMoveToLast();
                 });
             });

         });
    },

    testMoveToLast: function() {
         if (edcal.lastPostDate === '-1') {
             /*
              * Then there aren't any posts and we can't go
              * to the last one so we just skip this test.
              */
             nxc_test.testCreatePost();
             return;
         }

         var d = Date.parseExact(edcal.lastPostDate, 'ddMMyyyy');
         var curSunday = edcal.nextStartOfWeek(d).add(-1).weeks();

         /*
          * Now move to the last post, get the post date, and make sure the post
          * is there with the correct ID.
          */
         asyncTest('Move to the last post', function() {
             expect(1);

             edcal.moveTo(d);
             edcal.getPosts(edcal.nextStartOfWeek(d).add(-3).weeks(),
                            edcal.nextStartOfWeek(d).add(edcal.weeksPref + 3).weeks(), function() {

                 equals(jQuery('#post-' + edcal.lastPostId).length, 1, 'The post should be added at ' +
                        d.toString(Date.CultureInfo.formatPatterns.longDate));

                 edcal.moveTo(Date.today());
                 start();
                 nxc_test.testCreatePost();
             });

         });
    },

    testCreatePost: function() {
         /*
          * Now we'll do a few tests about creating, modifying, and deleting posts.
          */

         asyncTest('Create a new post', function() {
             expect(3);

             nxc_test.post.title = 'Unit Test Post';
             nxc_test.post.content = nxc_test.testContent;
             nxc_test.post.status = 'draft';
             nxc_test.post.time = '10:00 AM';
             nxc_test.post.date = Date.today().add(7).days().toString(edcal.internalDateFormat);
             nxc_test.post.id = '0';

             edcal.savePost(nxc_test.post, false, false, function(res) {
                 if (!res.post) {
                     ok(false, 'There was an error creating the new post.');
                     start();
                     return;
                 }

                 equals(res.post.date, nxc_test.post.date, 'The resulting post should have the same date as the request');
                 equals(res.post.title, nxc_test.post.title, 'The resulting post should have the same title as the request');

                 equals(jQuery('#post-' + res.post.id).length, 1, 'The post should be added in only one place in the calendar.');

                 nxc_test.post = res.post;

                 start();

                 nxc_test.testGetPost();
             });
         });

    },

    testGetPost: function() {
         /*
          * We'll start by getting data about the post we've just created
          */

         asyncTest('Get post information', function() {
             expect(3);

             edcal.getPost(nxc_test.post.id, function(post) {
                 equals(post.date, nxc_test.post.date, 'The resulting post should have the same date as the request');
                 equals(post.title, nxc_test.post.title, 'The resulting post should have the same title as the request');
                 equals(post.content, nxc_test.testContent, 'The resulting post content should be the same as the test post content');

                 nxc_test.post = post;

                 start();

                 nxc_test.testMovePost();
             });
         });

    },

    testMovePost: function() {

         asyncTest('Change the date of an existing post', function() {
             expect(2);

             // We added the post one week in the future, now we will move it
             // one day after that.
             var newDate = Date.today().add(8).days().toString(edcal.internalDateFormat);

             edcal.doDrop(nxc_test.post.date, 'post-' + nxc_test.post.id, newDate, function(res) {

                 if (!res.post) {
                     ok(false, 'There was an error creating the new post.');
                     return;
                 }

                 equals(res.post.date, newDate, 'The resulting post should have the same date as the request');

                 equals(jQuery('#post-' + res.post.id).length, 1, 'The post should be added in only one place in the calendar.');

                 nxc_test.post = res.post;

                 start();

                 nxc_test.testMovePostOneWeek();
             });
         });

    },

    testMovePostOneWeek: function() {

         asyncTest('Make a second change to the date of an existing post', function() {
             expect(2);

             // We added the post one week in the future, now we will move it
             // one day after that.
             var newDate = Date.today().add(22).days().toString(edcal.internalDateFormat);

             edcal.doDrop(nxc_test.post.date, 'post-' + nxc_test.post.id, newDate, function(res) {

                 if (!res.post) {
                     ok(false, 'There was an error creating the new post.');
                     return;
                 }

                 equals(res.post.date, newDate, 'The resulting post should have the same date as the request');

                 equals(jQuery('#post-' + res.post.id).length, 1, 'The post should be added in only one place in the calendar.');

                 nxc_test.post = res.post;

                 start();

                 nxc_test.testMovePostDraft();
             });
         });

    },

    testMovePostDraft: function() {

         asyncTest('Move an existing post to the drafts drawer', function() {
             expect(2);

             edcal.doDrop(nxc_test.post.date, 'post-' + nxc_test.post.id, edcal.NO_DATE, function(res) {

                 if (!res.post) {
                     ok(false, 'There was an error creating the new post.');
                     return;
                 }

                 equals(res.post.date_gmt, edcal.NO_DATE, 'The resulting post should have the same date as the request and it was ' + res.post.date);

                 equals(jQuery('#post-' + res.post.id).length, 1, 'The post should be added in only one place in the calendar.');

                 nxc_test.post = res.post;

                 start();

                 nxc_test.testEditPostDraft();
             });
         });

    },

    testEditPostDraft: function() {

         asyncTest('Edit the content of a draft post', function() {
             expect(2);

             nxc_test.post.title = 'Unit Test Draft Post &#8211 Changed';
             nxc_test.post.content = nxc_test.testContent3;

             edcal.savePost(nxc_test.post, false, false, function(res)
                {
                    if (!res.post) {
                        ok(false, 'There was an error editing the post.');
                        start();
                        return;
                    }

                    equals(res.post.title, nxc_test.post.title, 'The resulting post should have the same title as the request');

                    equals(jQuery('#post-' + res.post.id).length, 1, 'The post should be added in only one place in the calendar.');

                    nxc_test.post = res.post;

                    start();

                    nxc_test.testMovePostDraftSchedule();

                });
         });
    },

    testMovePostDraftSchedule: function() {

         asyncTest('Move a post from the drafts drawer back to the calendar', function() {
             expect(2);

             // We added the post one week in the future, now we will move it
             // two days after that.
             var newDate = Date.today().add(23).days().toString(edcal.internalDateFormat);

             edcal.doDrop(edcal.NO_DATE, 'post-' + nxc_test.post.id, newDate, function(res) {

                 if (!res.post) {
                     ok(false, 'There was an error creating the new post.');
                     return;
                 }

                 equals(res.post.date, newDate, 'The resulting post should have the same date as the request and it was ' + res.post.date);

                 equals(jQuery('#post-' + res.post.id).length, 1, 'The post should be added in only one place in the calendar.');

                 nxc_test.post = res.post;

                 start();

                 nxc_test.testEditPost();
             });
         });

    },

    testEditPost: function() {

         asyncTest('Edit the content of an existing post and mark it as scheduled', function() {
             expect(2);

             nxc_test.post.title = 'Unit Test Post &#8211 Changed';
             nxc_test.post.content = nxc_test.testContent2;

             edcal.savePost(nxc_test.post, false, true, function(res)
                {
                    if (!res.post) {
                        ok(false, 'There was an error editing the post.');
                        start();
                        return;
                    }

                    equals(res.post.title, nxc_test.post.title, 'The resulting post should have the same title as the request');

                    equals(jQuery('#post-' + res.post.id).length, 1, 'The post should be added in only one place in the calendar.');

                    nxc_test.post = res.post;

                    start();

                    nxc_test.testGetAfterEdit();

                });
         });

    },

    testGetAfterEdit: function() {
         /*
          * Now we'll test to make sure our new post data still matches what we think it should
          */

         asyncTest('Get post information after editing', function() {
             expect(3);

             edcal.getPost(nxc_test.post.id, function(post) {
                 equals(post.date, nxc_test.post.date, 'The resulting post should have the same date as the request');
                 equals(post.title, nxc_test.post.title, 'The resulting post should have the same title as the request');
                 equals(post.content, nxc_test.testContent2, 'The resulting post content should be the same as the test post content');

                 nxc_test.post = post;

                 start();

                 nxc_test.testDateConflict();
             });
         });

    },

    testDateConflict: function() {
         asyncTest('Try to change a post date and fail because of a concurrency conflict', function() {
             expect(2);

             nxc_test.post.date = Date.today().add(-1).days().toString(edcal.internalDateFormat);

             /*
              * We added the post one week in the future, now we will move it
              * one day after that.
              */
             var newDate = Date.today().add(8).days().toString(edcal.internalDateFormat);

             edcal.changeDate(newDate, nxc_test.post, function(res)
                {
                    if (!res.post) {
                        ok(false, 'There was an error with the change date conflict.');
                        return;
                    }

                    equals(res.error, edcal.CONCURRENCY_ERROR, 'This move should show an exception because it is in conflict.');

                    equals(jQuery('#post-' + res.post.id).length, 1, 'The post should be added in only one place in the calendar.');

                    nxc_test.post = res.post;

                    start();

                    nxc_test.testDeletePost();

                });
         });

    },

    testDeletePost: function() {

         /*
          * The last step is to delete the post we made so
          * the test cleans up after itself.
          */
         asyncTest('Delete the post created for testing', function() {
             expect(1);

             edcal.deletePost(nxc_test.post.id, function(res)
                {
                    if (!res.post) {
                        ok(false, 'There was an error creating the new post.');
                        start();
                        return;
                    }

                    equals(jQuery('#post-' + res.post.id).length, 0, 'The post should now be deleted from the calendar.');
                    start();

                    nxc_test.testCreateDraftDrawerPost();

                });
         });
    },

    testCreateDraftDrawerPost: function() {
         /*
          * Now we'll create a new post in the drafts drawer
          */

         asyncTest('Create a new drafts drawer post', function() {
             expect(2);

             nxc_test.post.title = 'Unit Test Drafts Drawer Post';
             nxc_test.post.content = nxc_test.testContent;
             nxc_test.post.status = 'draft';
             nxc_test.post.time = edcal.NO_DATE;
             nxc_test.post.date = edcal.NO_DATE;
             nxc_test.post.id = '0';

             edcal.savePost(nxc_test.post, false, false, function(res) {
                 if (!res.post) {
                     ok(false, 'There was an error creating the new post.');
                     start();
                     return;
                 }

                 equals(res.post.title, nxc_test.post.title, 'The resulting post should have the same title as the request');

                 equals(jQuery('#post-' + res.post.id).length, 1, 'The post should be added in only one place in the calendar.');

                 nxc_test.post = res.post;

                 start();

                 nxc_test.testDeleteDraftDrawerPost();
             });
         });

    },

    testDeleteDraftDrawerPost: function() {

         /*
          * The last step is to delete the post we made so
          * the test cleans up after itself.
          */
         asyncTest('Delete the post created for drafts drawer testing', function() {
             expect(1);

             edcal.deletePost(nxc_test.post.id, function(res)
                {
                    if (!res.post) {
                        ok(false, 'There was an error creating the new post.');
                        start();
                        return;
                    }

                    equals(jQuery('#post-' + res.post.id).length, 0, 'The post should now be deleted from the calendar.');
                    start();

                    nxc_test.finishTests();

                });
         });
    },

    finishTests: function() {
        if (!nxc_test.isDraftsDrawerVisible) {
            /*
             * We need to make sure the drafts drawer is open because
             * we can use it in the tests so we open it when the tests
             * start if it isn't open already.  We want to close it at
             * the end if we opened it.
             */
            edcal.setDraftsDrawerVisible(false);
        }
    }
};

redpajama_set_name: RedPajamaGithub


text:
import os
import yaml
import numpy as np
import numpy.random as npr

from .generate_anchors import generate_anchors
from ..utils.cython_bbox import bbox_overlaps, bbox_intersections

# TODO: make fast_rcnn irrelevant
# >>>> obsolete, because it depends on sth outside of this project
from ..fast_rcnn.config import cfg
from ..fast_rcnn.bbox_transform import bbox_transform

# <<<< obsolete

DEBUG = False

def anchor_target_layer(rpn_cls_score, gt_boxes, gt_ishard, dontcare_areas, im_info, _feat_stride=[16, ],
                        anchor_scales=[4, 8, 16, 32]):
    """
    Assign anchors to ground-truth targets. Produces anchor classification
    labels and bounding-box regression targets.
    Parameters
    ----------
    rpn_cls_score: for pytorch (1, Ax2, H, W) bg/fg scores of previous conv layer
    gt_boxes: (G, 5) vstack of [x1, y1, x2, y2, class]
    gt_ishard: (G, 1), 1 or 0 indicates difficult or not
    dontcare_areas: (D, 4), some areas may contains small objs but no labelling. D may be 0
    im_info: a list of [image_height, image_width, scale_ratios]
    _feat_stride: the downsampling ratio of feature map to the original input image
    anchor_scales: the scales to the basic_anchor (basic anchor is [16, 16])
    ----------
    Returns
    ----------
    rpn_labels : (HxWxA, 1), for each anchor, 0 denotes bg, 1 fg, -1 dontcare
    rpn_bbox_targets: (HxWxA, 4), distances of the anchors to the gt_boxes(may contains some transform)
                            that are the regression objectives
    rpn_bbox_inside_weights: (HxWxA, 4) weights of each boxes, mainly accepts hyper param in cfg
    rpn_bbox_outside_weights: (HxWxA, 4) used to balance the fg/bg,
                            beacuse the numbers of bgs and fgs mays significiantly different
    """
    _anchors = generate_anchors(scales=np.array(anchor_scales))
    _num_anchors = _anchors.shape[0]

    if DEBUG:
        print 'anchors:'
        print _anchors
        print 'anchor shapes:'
        print np.hstack((
            _anchors[:, 2::4] - _anchors[:, 0::4],
            _anchors[:, 3::4] - _anchors[:, 1::4],
        ))
        _counts = cfg.EPS
        _sums = np.zeros((1, 4))
        _squared_sums = np.zeros((1, 4))
        _fg_sum = 0
        _bg_sum = 0
        _count = 0

    # allow boxes to sit over the edge by a small amount
    _allowed_border = 0
    # map of shape (..., H, W)
    # height, width = rpn_cls_score.shape[1:3]

    im_info = im_info[0]

    # Algorithm:
    #
    # for each (H, W) location i
    #   generate 9 anchor boxes centered on cell i
    #   apply predicted bbox deltas at cell i to each of the 9 anchors
    # filter out-of-image anchors
    # measure GT overlap

    assert rpn_cls_score.shape[0] == 1, \
        'Only single item batches are supported'

    # map of shape (..., H, W)
    # pytorch (bs, c, h, w)
    height, width = rpn_cls_score.shape[2:4]

    if DEBUG:
        print 'AnchorTargetLayer: height', height, 'width', width
        print ''
        print 'im_size: ({}, {})'.format(im_info[0], im_info[1])
        print 'scale: {}'.format(im_info[2])
        print 'height, width: ({}, {})'.format(height, width)
        print 'rpn: gt_boxes.shape', gt_boxes.shape
        print 'rpn: gt_boxes', gt_boxes

    # 1. Generate proposals from bbox deltas and shifted anchors
    shift_x = np.arange(0, width) * _feat_stride
    shift_y = np.arange(0, height) * _feat_stride
    shift_x, shift_y = np.meshgrid(shift_x, shift_y)  # in W H order
    # K is H x W
    shifts = np.vstack((shift_x.ravel(), shift_y.ravel(),
                        shift_x.ravel(), shift_y.ravel())).transpose()
    # add A anchors (1, A, 4) to
    # cell K shifts (K, 1, 4) to get
    # shift anchors (K, A, 4)
    # reshape to (K*A, 4) shifted anchors
    A = _num_anchors
    K = shifts.shape[0]
    all_anchors = (_anchors.reshape((1, A, 4)) +
                   shifts.reshape((1, K, 4)).transpose((1, 0, 2)))
    all_anchors = all_anchors.reshape((K * A, 4))
    total_anchors = int(K * A)

    # only keep anchors inside the image
    inds_inside = np.where(
        (all_anchors[:, 0] >= -_allowed_border) &
        (all_anchors[:, 1] >= -_allowed_border) &
        (all_anchors[:, 2] < im_info[1] + _allowed_border) &  # width
        (all_anchors[:, 3] < im_info[0] + _allowed_border)  # height
    )[0]

    if DEBUG:
        print 'total_anchors', total_anchors
        print 'inds_inside', len(inds_inside)

    # keep only inside anchors
    anchors = all_anchors[inds_inside, :]
    if DEBUG:
        print 'anchors.shape', anchors.shape

    # label: 1 is positive, 0 is negative, -1 is dont care
    # (A)
    labels = np.empty((len(inds_inside),), dtype=np.float32)
    labels.fill(-1)

    # overlaps between the anchors and the gt boxes
    # overlaps (ex, gt), shape is A x G
    overlaps = bbox_overlaps(
        np.ascontiguousarray(anchors, dtype=np.float),
        np.ascontiguousarray(gt_boxes, dtype=np.float))
    argmax_overlaps = overlaps.argmax(axis=1)  # (A)
    max_overlaps = overlaps[np.arange(len(inds_inside)), argmax_overlaps]
    gt_argmax_overlaps = overlaps.argmax(axis=0)  # G
    gt_max_overlaps = overlaps[gt_argmax_overlaps,
                               np.arange(overlaps.shape[1])]
    gt_argmax_overlaps = np.where(overlaps == gt_max_overlaps)[0]

    if not cfg.TRAIN.RPN_CLOBBER_POSITIVES:
        # assign bg labels first so that positive labels can clobber them
        labels[max_overlaps < cfg.TRAIN.RPN_NEGATIVE_OVERLAP] = 0

    # fg label: for each gt, anchor with highest overlap
    labels[gt_argmax_overlaps] = 1
    # fg label: above threshold IOU
    labels[max_overlaps >= cfg.TRAIN.RPN_POSITIVE_OVERLAP] = 1

    if cfg.TRAIN.RPN_CLOBBER_POSITIVES:
        # assign bg labels last so that negative labels can clobber positives
        labels[max_overlaps < cfg.TRAIN.RPN_NEGATIVE_OVERLAP] = 0

    # preclude dontcare areas
    if dontcare_areas is not None and dontcare_areas.shape[0] > 0:
        # intersec shape is D x A
        intersecs = bbox_intersections(
            np.ascontiguousarray(dontcare_areas, dtype=np.float),  # D x 4
            np.ascontiguousarray(anchors, dtype=np.float)  # A x 4
        )
        intersecs_ = intersecs.sum(axis=0)  # A x 1
        labels[intersecs_ > cfg.TRAIN.DONTCARE_AREA_INTERSECTION_HI] = -1

    # preclude hard samples that are highly occlusioned, truncated or difficult to see
    if cfg.TRAIN.PRECLUDE_HARD_SAMPLES and gt_ishard is not None and gt_ishard.shape[0] > 0:
        assert gt_ishard.shape[0] == gt_boxes.shape[0]
        gt_ishard = gt_ishard.astype(int)
        gt_hardboxes = gt_boxes[gt_ishard == 1, :]
        if gt_hardboxes.shape[0] > 0:
            # H x A
            hard_overlaps = bbox_overlaps(
                np.ascontiguousarray(gt_hardboxes, dtype=np.float),  # H x 4
                np.ascontiguousarray(anchors, dtype=np.float))  # A x 4
            hard_max_overlaps = hard_overlaps.max(axis=0)  # (A)
            labels[hard_max_overlaps >= cfg.TRAIN.RPN_POSITIVE_OVERLAP] = -1
            max_intersec_label_inds = hard_overlaps.argmax(axis=1)  # H x 1
            labels[max_intersec_label_inds] = -1  #

    # subsample positive labels if we have too many
    num_fg = int(cfg.TRAIN.RPN_FG_FRACTION * cfg.TRAIN.RPN_BATCHSIZE)
    fg_inds = np.where(labels == 1)[0]
    if len(fg_inds) > num_fg:
        disable_inds = npr.choice(
            fg_inds, size=(len(fg_inds) - num_fg), replace=False)
        labels[disable_inds] = -1

    # subsample negative labels if we have too many
    num_bg = cfg.TRAIN.RPN_BATCHSIZE - np.sum(labels == 1)
    bg_inds = np.where(labels == 0)[0]
    if len(bg_inds) > num_bg:
        disable_inds = npr.choice(
            bg_inds, size=(len(bg_inds) - num_bg), replace=False)
        labels[disable_inds] = -1
        # print "was %s inds, disabling %s, now %s inds" % (
        # len(bg_inds), len(disable_inds), np.sum(labels == 0))

    # bbox_targets = np.zeros((len(inds_inside), 4), dtype=np.float32)
    bbox_targets = _compute_targets(anchors, gt_boxes[argmax_overlaps, :])

    bbox_inside_weights = np.zeros((len(inds_inside), 4), dtype=np.float32)
    bbox_inside_weights[labels == 1, :] = np.array(cfg.TRAIN.RPN_BBOX_INSIDE_WEIGHTS)

    bbox_outside_weights = np.zeros((len(inds_inside), 4), dtype=np.float32)
    if cfg.TRAIN.RPN_POSITIVE_WEIGHT < 0:
        # uniform weighting of examples (given non-uniform sampling)
        # num_examples = np.sum(labels >= 0) + 1
        # positive_weights = np.ones((1, 4)) * 1.0 / num_examples
        # negative_weights = np.ones((1, 4)) * 1.0 / num_examples
        positive_weights = np.ones((1, 4))
        negative_weights = np.zeros((1, 4))
    else:
        assert ((cfg.TRAIN.RPN_POSITIVE_WEIGHT > 0) &
                (cfg.TRAIN.RPN_POSITIVE_WEIGHT < 1))
        positive_weights = (cfg.TRAIN.RPN_POSITIVE_WEIGHT /
                            (np.sum(labels == 1)) + 1)
        negative_weights = ((1.0 - cfg.TRAIN.RPN_POSITIVE_WEIGHT) /
                            (np.sum(labels == 0)) + 1)
    bbox_outside_weights[labels == 1, :] = positive_weights
    bbox_outside_weights[labels == 0, :] = negative_weights

    if DEBUG:
        _sums += bbox_targets[labels == 1, :].sum(axis=0)
        _squared_sums += (bbox_targets[labels == 1, :] ** 2).sum(axis=0)
        _counts += np.sum(labels == 1)
        means = _sums / _counts
        stds = np.sqrt(_squared_sums / _counts - means ** 2)
        print 'means:'
        print means
        print 'stdevs:'
        print stds

    # map up to original set of anchors
    labels = _unmap(labels, total_anchors, inds_inside, fill=-1)
    bbox_targets = _unmap(bbox_targets, total_anchors, inds_inside, fill=0)
    bbox_inside_weights = _unmap(bbox_inside_weights, total_anchors, inds_inside, fill=0)
    bbox_outside_weights = _unmap(bbox_outside_weights, total_anchors, inds_inside, fill=0)

    if DEBUG:
        print 'rpn: max max_overlap', np.max(max_overlaps)
        print 'rpn: num_positive', np.sum(labels == 1)
        print 'rpn: num_negative', np.sum(labels == 0)
        _fg_sum += np.sum(labels == 1)
        _bg_sum += np.sum(labels == 0)
        _count += 1
        print 'rpn: num_positive avg', _fg_sum / _count
        print 'rpn: num_negative avg', _bg_sum / _count

    # labels
    # pdb.set_trace()
    labels = labels.reshape((1, height, width, A))
    labels = labels.transpose(0, 3, 1, 2)
    rpn_labels = labels.reshape((1, 1, A * height, width)).transpose(0, 2, 3, 1)

    # bbox_targets
    bbox_targets = bbox_targets \
        .reshape((1, height, width, A * 4)).transpose(0, 3, 1, 2)

    rpn_bbox_targets = bbox_targets
    # bbox_inside_weights
    bbox_inside_weights = bbox_inside_weights \
        .reshape((1, height, width, A * 4)).transpose(0, 3, 1, 2)
    # assert bbox_inside_weights.shape[2] == height
    # assert bbox_inside_weights.shape[3] == width

    rpn_bbox_inside_weights = bbox_inside_weights

    # bbox_outside_weights
    bbox_outside_weights = bbox_outside_weights \
        .reshape((1, height, width, A * 4)).transpose(0, 3, 1, 2)
    # assert bbox_outside_weights.shape[2] == height
    # assert bbox_outside_weights.shape[3] == width

    rpn_bbox_outside_weights = bbox_outside_weights

    return rpn_labels, rpn_bbox_targets, rpn_bbox_inside_weights, rpn_bbox_outside_weights

def _unmap(data, count, inds, fill=0):
    """ Unmap a subset of item (data) back to the original set of items (of
    size count) """
    if len(data.shape) == 1:
        ret = np.empty((count,), dtype=np.float32)
        ret.fill(fill)
        ret[inds] = data
    else:
        ret = np.empty((count,) + data.shape[1:], dtype=np.float32)
        ret.fill(fill)
        ret[inds, :] = data
    return ret

def _compute_targets(ex_rois, gt_rois):
    """Compute bounding-box regression targets for an image."""

    assert ex_rois.shape[0] == gt_rois.shape[0]
    assert ex_rois.shape[1] == 4
    assert gt_rois.shape[1] == 5

    return bbox_transform(ex_rois, gt_rois[:, :4]).astype(np.float32, copy=False)


text:
Use `./configure && make` to configure and build `cadical` in the default
`build` sub-directory.

This will also build the library `libcadical.a` as well as the model based
tester `mobical`:

    build/cadical
    build/mobical
    build/libcadical.a

The header file of the library is in

    src/cadical.hpp

The build process requires GNU make.  Using the generated `makefile` with
GNU make compiles separate object files, which can be cached (for instance
with `ccache`).  In order to force parallel build you can use the '-j'
option either for 'configure' or with 'make'.  If the environment variable
'MAKEFLAGS' is set, e.g., 'MAKEFLAGS=-j ./configure', the same effect
is achieved and the generated makefile will use those flags.

Options
-------

You might want to check out options of `./configure -h`, such as

    ./configure -c # include assertion checking code

    ./configure -l # include code to really see what the solver is doing

    ./configure -a # both above and in addition `-g` for debugging.

You can easily use multiple build directories, e.g.,

    mkdir debug; cd debug; ../configure -g; make

which compiles and builds a debugging version in the sub-directory `debug`,
since `-g` was specified as parameter to `configure`.  The object files,
the library and the binaries are all independent of those in the default
build directory `build`.

All source files reside in the `src` directory.  The library `libcadical.a`
is compiled from all the `.cpp` files except `cadical.cpp` and
`mobical.cpp`, which provide the applications, i.e., the stand alone solver
`cadical` and the model based tester `mobical`.

Manual Build
------------

If you can not or do not want to rely on our `configure` script nor on our
build system based on GNU `make`, then this is easily doable as follows.

    mkdir build
    cd build
    for f in ../src/*.cpp; do g++ -O3 -DNDEBUG -DNBUILD -c $f; done
    ar rc libcadical.a `ls *.o | grep -v ical.o`
    g++ -o cadical cadical.o -L. -lcadical
    g++ -o mobical mobical.o -L. -lcadical

Note that application object files are excluded from the library.
Of course you can use different compilation options as well.

Since `build.hpp` is not generated in this flow the `-DNBUILD` flag is
necessary though, which avoids dependency of `version.cpp` on `build.hpp`.
Consequently you will only get very basic version information compiled into
the library and binaries (guaranteed is in essence just the version number
of the library).

And if you really do not care about compilation time nor caching and just
want to build the solver once manually then the following also works.

    g++ -O3 -DNDEBUG -DNBUILD -o cadical `ls *.cpp | grep -v mobical`

Further note that the `configure` script provides some feature checks and
might generate additional compiler flags necessary for compilation.  You
might need to set those yourself or just use a modern C++11 compiler.

This manual build process using object files is fast enough in combination
with caching solutions such as `ccache`.  But it lacks the ability of our
GNU make solution to run compilation in parallel without additional parallel
process scheduling solutions.

Cross-Compilation
-----------------

We have preliminary support for cross-compilation using MinGW32 (only
tested for a Linux compilation host and Windows-64 target host at this
point).

There are two steps necessary to make this work.  First make
sure to be able to execute binaries compiled with the cross-compiler
directly.  Otherwise 'configure' does not work automatically and you
have to build manually (as described above).

For instance in order to use `wine` to execute the binaries first install
`wine` which for instance on Ubuntu just requires

    sudo apt install wine

Then on Linux you might want to look into the `binfmt_misc` module and
as root register the appropriate interpreter for `DOSWin`.

    cd /proc/sys/fs/binfmt_misc
    echo ':DOSWin:M::MZ::/usr/bin/wine:' > register

Finally simply tell the `configure` script to use the cross-compiler.

    CXX=i686-w64-mingw32-g++ ./configure -static -lpsapi && make cadical

Note the use of '-static', which was necessary for me since by default
`wine` did not find `libstdc++` if dynamically linked.  There is also
a dependency on the 'psapi' library. Also `mobical` does not compile with
MinGW32 due to too many Unix dependencies and thus only make 'cadical'.


text:
package org.fest.swing.driver;

import static org.fest.swing.edt.GuiActionRunner.execute;

import java.awt.Component;
import java.awt.Point;

import javax.annotation.Nonnull;

import org.fest.swing.annotation.RunsInEDT;
import org.fest.swing.edt.GuiTask;

/**
 * Sets the location of an AWT or Swing {@code Component}. This task is executed in the event dispatch thread (EDT.)
 *
 * @author Alex Ruiz
 */
final class ComponentMoveTask {
  @RunsInEDT
  static void moveComponent(final @Nonnull Component c, final @Nonnull Point location) {
    execute(new GuiTask() {
      @Override
      protected void executeInEDT() {
        c.setLocation(location);
      }
    });
  }

  private ComponentMoveTask() {}
}


text:
package mta.catsfeeder.controller;

import mta.catsfeeder.controller.request.OptionRequest;
import mta.catsfeeder.model.User;
import mta.catsfeeder.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

/**
 * Created by alexey on 3/25/15.
 */
@RestController
@RequestMapping(value = "/options")
@Transactional
public class UserOptionController {

    @Autowired
    IUserService userService;

    @RequestMapping(method = RequestMethod.POST)
    public ResponseEntity setOption(@RequestBody OptionRequest optionRequest,
                                      @CookieValue(value="token") String userToken) {

        User user = userService.getUser(userToken);

        userService.setOption(user, optionRequest.getKey(), optionRequest.getValue());

        return new ResponseEntity(HttpStatus.OK);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<database>

	<!-- INSTALL -->

	<action id="core_log_admin" label="Create table %s" string="{{PREFIX}}core_log_admin">

		<test eq="neq" value="{{PREFIX}}core_log_admin" label="Table %s exists"
			type="wrn" string="{{PREFIX}}core_log_admin">SHOW TABLES LIKE '{{PREFIX}}core_log_admin'</test>

		CREATE TABLE IF NOT EXISTS `{{PREFIX}}core_log_admin` (
			`id` SERIAL,
			`user_id` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
			`username` VARCHAR(255) NOT NULL DEFAULT '',
			`ip` VARCHAR(39) NOT NULL DEFAULT '0.0.0.0',
			`date` DATETIME NOT NULL,
			`type` TINYINT(1) UNSIGNED NOT NULL DEFAULT 0,
			`component` VARCHAR(40) NOT NULL DEFAULT '',
			`code` TINYINT(1) UNSIGNED NOT NULL DEFAULT 0,
			`message` VARCHAR(255) NOT NULL DEFAULT '',

			PRIMARY KEY (`id`),
			KEY `{{PREFIX}}core_log_admin_user_id_idx` (`user_id`),
			KEY `{{PREFIX}}core_log_admin_username_idx` (`username`),
			KEY `{{PREFIX}}core_log_admin_ip_idx` (`ip`),
			KEY `{{PREFIX}}core_log_admin_date_idx` (`date`),
			KEY `{{PREFIX}}core_log_admin_user_type_idx` (`type`),
			KEY `{{PREFIX}}core_log_admin_component_idx` (`component`),
			KEY `{{PREFIX}}core_log_admin_user_code_idx` (`code`)

		) ENGINE=MyISAM
		DEFAULT CHARSET=utf8 COLLATE utf8_bin ;
	</action>

	<!-- UPDATE -->

</database>


text:
<?php

namespace Omitsis\SampleAppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Response;

class DefaultController extends Controller
{
    /**
     * @Route("/")
     */
    public function indexAction()
    {
        return $this->render('OmitsisSampleAppBundle:Default:index.html.twig');
    }
}


text: let bar = SomeThing.Baz.bar;


text:
<?php

namespace Podlove\Model;

class GeoArea extends Base
{
}

GeoArea::property('id', 'INT NOT NULL AUTO_INCREMENT PRIMARY KEY');
GeoArea::property('geoname_id', 'INT', ['unique' => true]);
GeoArea::property('parent_id', 'INT');
GeoArea::property('code', 'VARCHAR(5)');
GeoArea::property('type', 'VARCHAR(255)');


text:
package org.redisson.connection;

import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;

import org.redisson.Config;
import org.redisson.MasterSlaveServersConfig;
import org.redisson.SentinelServersConfig;
import org.redisson.client.RedisClient;
import org.redisson.client.RedisConnection;
import org.redisson.client.RedisPubSubConnection;
import org.redisson.client.RedisPubSubListener;
import org.redisson.client.codec.StringCodec;
import org.redisson.client.protocol.RedisCommands;
import org.redisson.client.protocol.pubsub.PubSubType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SentinelConnectionManager extends MasterSlaveConnectionManager {

    private final Logger log = LoggerFactory.getLogger(getClass());

    private final List<RedisClient> sentinels = new ArrayList<RedisClient>();

    public SentinelConnectionManager(final SentinelServersConfig cfg, Config config) {
        init(config);

        final MasterSlaveServersConfig c = new MasterSlaveServersConfig();
        c.setRetryInterval(cfg.getRetryInterval());
        c.setRetryAttempts(cfg.getRetryAttempts());
        c.setTimeout(cfg.getTimeout());
        c.setLoadBalancer(cfg.getLoadBalancer());
        c.setPassword(cfg.getPassword());
        c.setDatabase(cfg.getDatabase());
        c.setMasterConnectionPoolSize(cfg.getMasterConnectionPoolSize());
        c.setSlaveConnectionPoolSize(cfg.getSlaveConnectionPoolSize());
        c.setSlaveSubscriptionConnectionPoolSize(cfg.getSlaveSubscriptionConnectionPoolSize());
        c.setSubscriptionsPerConnection(cfg.getSubscriptionsPerConnection());

        final Set<String> addedSlaves = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>());
        for (URI addr : cfg.getSentinelAddresses()) {
            RedisClient client = createClient(addr.getHost(), addr.getPort(), c.getTimeout());
            RedisConnection connection = client.connect();

            // TODO async
            List<String> master = connection.sync(RedisCommands.SENTINEL_GET_MASTER_ADDR_BY_NAME, cfg.getMasterName());
            String masterHost = master.get(0) + ":" + master.get(1);
            c.setMasterAddress(masterHost);
            log.info("master: {} added", masterHost);
//            c.addSlaveAddress(masterHost);

            // TODO async
            List<Map<String, String>> slaves = connection.sync(RedisCommands.SENTINEL_SLAVES, cfg.getMasterName());
            for (Map<String, String> map : slaves) {
                String ip = map.get("ip");
                String port = map.get("port");
                String flags = map.get("flags");

                if (flags.contains("s_down") || flags.contains("disconnected")) {
                    log.info("slave: {}:{} is disconnected. skipped, params: {}", ip, port, map);
                    continue;
                }

                log.info("slave: {}:{} added, params: {}", ip, port, map);
                c.addSlaveAddress(ip + ":" + port);
                String host = ip + ":" + port;
                addedSlaves.add(host);
            }

            client.shutdown();
            break;
        }

        init(c);

        monitorMasterChange(cfg, addedSlaves);
    }

    private void monitorMasterChange(final SentinelServersConfig cfg, final Set<String> addedSlaves) {
        final AtomicReference<String> master = new AtomicReference<String>();
        final Set<String> freezeSlaves = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>());

        for (final URI addr : cfg.getSentinelAddresses()) {
            RedisClient client = createClient(addr.getHost(), addr.getPort());
            sentinels.add(client);

            RedisPubSubConnection pubsub = client.connectPubSub();
            pubsub.addListener(new RedisPubSubListener<String>() {

                @Override
                public void onMessage(String channel, String msg) {
                    if ("+slave".equals(channel)) {
                        onSlaveAdded(addedSlaves, addr, msg);
                    }
                    if ("+sdown".equals(channel)) {
                        onSlaveDown(freezeSlaves, addr, msg);
                    }
                    if ("-sdown".equals(channel)) {
                        onSlaveUp(freezeSlaves, addr, msg);
                    }
                    if ("+switch-master".equals(channel)) {
                        onMasterChange(cfg, master, addr, msg);
                    }
                }

                @Override
                public void onPatternMessage(String pattern, String channel, String message) {
                }

                @Override
                public boolean onStatus(PubSubType type, String channel) {
                    if (type == PubSubType.SUBSCRIBE) {
                        log.info("subscribed to channel: {} from Sentinel {}:{}", channel, addr.getHost(), addr.getPort());
                    }
                    return true;
                }
            });

            pubsub.subscribe(StringCodec.INSTANCE, "+switch-master", "+sdown", "-sdown", "+slave");
        }
    }

    protected void onSlaveAdded(Set<String> addedSlaves, URI addr, String msg) {
        String[] parts = msg.split(" ");

        if (parts.length > 4
                 && "slave".equals(parts[0])) {
            String ip = parts[2];
            String port = parts[3];

            String slaveAddr = ip + ":" + port;

            // to avoid addition twice
            if (addedSlaves.add(slaveAddr)) {
                log.debug("Slave has been added - {}", slaveAddr);
                addSlave(ip, Integer.valueOf(port));
            }
        } else {
            log.warn("Invalid message: {} from Sentinel {}:{}", msg, addr.getHost(), addr.getPort());
        }
    }

    private void onSlaveDown(final Set<String> freezeSlaves, final URI addr, String msg) {
        String[] parts = msg.split(" ");

        if (parts.length > 4
                 && "slave".equals(parts[0])) {
            String ip = parts[2];
            String port = parts[3];

            String slaveAddr = ip + ":" + port;

            // to avoid freeze twice
            if (freezeSlaves.add(slaveAddr)) {
                log.debug("Slave has down - {}", slaveAddr);
                slaveDown(-1, ip, Integer.valueOf(port));
            }
        } else {
            log.warn("Invalid message: {} from Sentinel {}:{}", msg, addr.getHost(), addr.getPort());
        }
    }

    protected void onSlaveUp(Set<String> freezeSlaves, URI addr, String msg) {
        String[] parts = msg.split(" ");

        if (parts.length > 4
                 && "slave".equals(parts[0])) {
            String ip = parts[2];
            String port = parts[3];

            String slaveAddr = ip + ":" + port;
            if (freezeSlaves.remove(slaveAddr)) {
                log.debug("Slave has up - {}", slaveAddr);
                slaveUp(ip, Integer.valueOf(port));
            }
        } else {
            log.warn("Invalid message: {} from Sentinel {}:{}", msg, addr.getHost(), addr.getPort());
        }
    }

    private void onMasterChange(final SentinelServersConfig cfg,
            final AtomicReference<String> master, final URI addr, String msg) {
        String[] parts = msg.split(" ");

        if (parts.length > 3) {
            if (cfg.getMasterName().equals(parts[0])) {
                String ip = parts[3];
                String port = parts[4];

                String current = master.get();
                String newMaster = ip + ":" + port;
                if (!newMaster.equals(current)
                        && master.compareAndSet(current, newMaster)) {
                    log.debug("changing master from {} to {}", current, newMaster);
                    changeMaster(-1, ip, Integer.valueOf(port));
                }
            }
        } else {
            log.warn("Invalid message: {} from Sentinel {}:{}", msg, addr.getHost(), addr.getPort());
        }
    }

    @Override
    public void shutdown() {
        for (RedisClient sentinel : sentinels) {
            sentinel.shutdown();
        }

        super.shutdown();
    }
}


text:
using System;

namespace Microsoft.Recognizers.Text.Number
{
    [Flags]
    public enum NumberOptions
    {
        None = 0,
        PercentageMode = 1,
        ExperimentalMode = 2
    }
}


text:
package com.bugsnag.android;

import android.test.AndroidTestCase;
import android.test.suitebuilder.annotation.SmallTest;

/**
 * Created by alex on 16/3/25.
 */
public class MachineSampleTest extends AndroidTestCase {

    @SmallTest
    public void testSample() {
        System.out.println("asd");
    }
}


text:
#ifndef DSRPOSCN_H
#define DSRPOSCN_H

#include "dcmtk/config/osconfig.h"   /* make sure OS specific configuration is included first */

#include "dcmtk/dcmsr/dsdefine.h"

#include "dcmtk/ofstd/ofstring.h"
#include "dcmtk/ofstd/oflist.h"

/*---------------------*
 *  class declaration  *
 *---------------------*/

/** Class implementing a position counter to be used for iterating a tree of nodes
 */
class DCMTK_DCMSR_EXPORT DSRPositionCounter
{
  public:

    /** (default) constructor
     ** @param  flags  optional flags used to customize the processing of the counter.
     *                 These flags are only stored but not evaluated by this class.
     */
    DSRPositionCounter(const size_t flags = 0);

    /** copy constructor
     ** @param  counter  object to be copied
     */
    DSRPositionCounter(const DSRPositionCounter &counter);

    /** destructor
     */
    virtual ~DSRPositionCounter();

    /** assignment operator
     ** @param  counter  object to be copied
     ** @return reference to modified cursor (this object)
     */
    DSRPositionCounter &operator=(const DSRPositionCounter &counter);

    /** conversion operator that returns the position on the current level
     *  (0 if the position counter is invalid)
     */
    inline operator size_t () const
    {
        return Position;
    }

    /** pre-increment operator.  Increases the position on the current level by 1.
     *  Also makes the position counter valid if it was invalid before.
     */
    inline DSRPositionCounter &operator++()
    {
        ++Position;
        return *this;
    }

    /** pre-decrement operator.  Decreases the position on the current level by 1.
     *  This makes the position counter invalid if the position was 1 before.
     */
    inline DSRPositionCounter &operator--()
    {
        /* avoid underflow */
        if (Position > 0) --Position;
        return *this;
    }

    /** clear all member variables.
     *  The position counter becomes invalid afterwards (same state as after default
     *  construction).  Also see initialize().
     */
    void clear();

    /** initialize the position counter
     ** @param  valid  flag specifying whether the counter should be initialized as
     *                 valid (default) or invalid
     *  @param  flags  optional flags used to customize the processing of the counter.
     *                 These flags are only stored but not evaluated by this class.
     */
    void initialize(const OFBool valid = OFTrue,
                    const size_t flags = 0);

    /** check whether position counter is valid (i.e.\ has been initialized)
     ** @return OFTrue if valid, OFFalse otherwise
     */
    inline OFBool isValid() const
    {
        return (Position > 0);
    }

    /** go one level up, i.e.\ restore the position on the next upper level and forget
     *  about the current level
     ** @return OFTrue if successful, OFFalse otherwise
     */
    OFBool goUp();

    /** go one level down, i.e.\ store the position on the current level and start with
     *  1 on the new level
     ** @return OFTrue if successful, OFFalse otherwise
     */
    OFBool goDown();

    /** get specified flags that can be used to customize the counter
     ** @return flags used to customize the counter
     */
    inline size_t getFlags() const
    {
        return Flags;
    }

    /** get current level of the position counter.
     *  The top most (root) level is 1, the next lower level is 2, etc.
     ** @return number of the current level if valid, 0 otherwise
     */
    inline size_t getLevel() const
    {
        /* check for valid counter */
        return isValid() ? PositionList.size() + 1 : 0;
    }

    /** get string representing the current state of the position counter.
     *  See DSRTreeNodeCursor::getPosition() for details.
     ** @param  position   variable where the position string should be stored
     *  @param  separator  character used to separate the figures (default: '.')
     ** @return reference to the resulting position string (empty if invalid)
     */
    const OFString &getString(OFString &position,
                              const char separator = '.') const;

  private:

    /// current position within the current level
    size_t Position;
    /// list of position counters in upper levels
    OFList<size_t> PositionList;
    /// flags used to customize the counter
    size_t Flags;
};

#endif


text:
set -x
cat 111-array-individual-assigns.out | grep 100 || exit 1
exit 0


text:
package redrun.model.toolkit;

import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Drawable;
import org.lwjgl.opengl.GLSync;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Adam Mitchell
 *
 * Sets up the necessary locks and mechanisms to share the gl context
 * with this thread so fonts can be loaded while loading screen is painted in main
 */
public abstract class BackgroundLoader
{
  // CPU synchronization
  private final ReentrantLock lock = new ReentrantLock();
  // GPU synchronization
  @SuppressWarnings("unused")
  private GLSync fence;
  private Drawable drawable;

  private boolean running = true;;

  protected abstract Drawable getDrawable() throws LWJGLException;

  /**
   * starts a drawable gl context and loads the fonts
   *
   * @throws LWJGLException
   */
  public void start() throws LWJGLException
  {
    // The shared context must be created on the main thread.
    drawable = getDrawable();

    new Thread(new Runnable()
    {
      public void run()
      {
        System.out.println("-- Background Thread started --");
        try
        {
          // Make the shared context current in the worker thread
          drawable.makeCurrent();
        }
        catch (LWJGLException e)
        {
          throw new RuntimeException(e);
        }
        System.out.println("** Context Switched **");

        lock.lock();
        redrun.model.toolkit.FontTools.loadFonts();
        lock.unlock();
        System.out.println("-- Background Thread finished --");
        running = false;
      }
    }).start();
  }

  /**
   * @return true if still running
   */
  public boolean isRunning()
  {
    return running;
  }
}


text:
package com.selfcoders.talkingmobs;

import org.bukkit.ChatColor;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;

import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;

/**
 * Class providing methods to send mob messages to players
 */
public class Message {
    private final TalkingMobs plugin;
    private final Config messagesConfig;
    private final Config playersConfig;
    private HashMap<String, Long> lastMessage = new HashMap<>();

    /**
     * Possible event types
     */
    public enum EventType {
        /**
         * Mob has been attacked by a player
         */
        ATTACKED("attacked", true),
        /**
         * Mob is idle (Is just standing/walking/running around) -> Unused
         */
        IDLE("idle", true),
        /**
         * Player interacted with the mob (Right clicked on mob)
         */
        INTERACTED("interacted", true),
        /**
         * Mob has been killed
         */
        KILLED("killed", false),
        /**
         * Mob has been killed by a player
         */
        KILLED_PLAYER("killed_player", true),
        /**
         * Mob has been killed by something else (not a player)
         */
        KILLED_OTHER("killed_other", true),
        /**
         * Mob is looking at the player (and player is looking at the mob)
         */
        LOOKING("looking", true),
        /**
         * Mob has been spawned (Mob spawner, egg or another plugin by default, but can be configured in config.yml)
         */
        SPAWNED("spawned", true),
        /**
         * Mob has been tamed
         */
        TAMED("tamed", true);

        private String type;
        private boolean toggleable;

        EventType(String type, boolean toggleable) {
            this.type = type;
            this.toggleable = toggleable;
        }

        public String getType() {
            return type;
        }

        public boolean isToggleable() {
            return toggleable;
        }

        public static EventType fromString(String type) {
            for (EventType eventType : values()) {
                if (eventType.getType().equalsIgnoreCase(type)) {
                    return eventType;
                }
            }

            return null;
        }
    }

    /**
     * Initialize the message class
     *
     * @param pluginInstance The instance of this plugin ('this' in TalkingMobs class)
     */
    Message(TalkingMobs pluginInstance) {
        plugin = pluginInstance;

        messagesConfig = new Config(plugin, "messages.yml");
        playersConfig = new Config(plugin, "players.yml");
    }

    /**
     * Reload the messages
     */
    public void reloadConfig() {
        messagesConfig.reload();
        playersConfig.reload();
    }

    /**
     * Get a list of messages configured for the specified mob and event type
     *
     * @param mob       The entity of the mob for which the messages should be fetched
     * @param eventType The event type of the messages
     * @return A list of messages or null if there a none
     */
    private List<String> getMessages(Entity mob, EventType eventType) {
        List<String> messages;
        String mobTypeName = mob.getType().name().toLowerCase();

        messages = messagesConfig.getConfig().getStringList(mobTypeName + "." + eventType.getType());
        if (messages.size() == 0) {
            messages = messagesConfig.getConfig().getStringList("default." + eventType.getType());

            if (messages.size() == 0) {
                return null;
            }
        }

        return messages;
    }

    /**
     * Get a random message for the specified mob and event type
     *
     * @param mob       The entity of the mob for which the message should be fetched
     * @param eventType The event type of the message
     * @return A string containing the message
     */
    private String getMessage(Entity mob, EventType eventType) {
        String mobTypeName = mob.getType().name().toLowerCase();

        List<String> messages = getMessages(mob, eventType);

        if (messages == null) {
            plugin.getLogger().log(Level.INFO, "No messages for event ''{0}'' of mob ''{1}'' defined!", new Object[]{eventType.getType(), mobTypeName});
            return null;
        }

        Random randomGenerator = new Random();

        String message = plugin.getConfig().getString("messageFormat." + eventType.getType());

        if (message == null) {
            message = plugin.getConfig().getString("messageFormat.default");

            if (message == null) {
                message = "[&a%mobname%&r] %message%";
                plugin.getLogger().log(Level.INFO, "Message format for event type ''{0}'' not defined!", eventType.getType());
            }
        }

        message = message.replaceAll("%message%", messages.get(randomGenerator.nextInt(messages.size())));
        message = message.replaceAll("%mobname%", mobTypeName);
        message = message.replaceAll("%event%", eventType.getType());

        return message;
    }

    /**
     * Check whether the player has the permission to receive mob messages
     *
     * @param player The player which should be checked
     * @return True if the player has the permission, false otherwise
     */
    private boolean isAllowed(Player player) {
        return player.hasPermission(Permission.RECEIVE.permission());
    }

    /**
     * Check if talking mobs of the specified message type is enabled for the specified player
     *
     * @param player    The player for which the state should be checked
     * @param eventType The message type which should be checked
     * @return True if talking mobs of the specified type is enabled, false otherwise
     */
    public boolean isEnabled(Player player, EventType eventType) {
        // Check if all has been disabled
        if (!isEnabled(player)) {
            return false;
        }

        return playersConfig.getConfig().getBoolean(player.getName() + ".enabled." + eventType.getType(), true);
    }

    /**
     * Check if talking mobs is enabled for the specified player
     *
     * @param player The player for which the state should be checked
     * @return True if talking mobs is enabled, false otherwise
     */
    public boolean isEnabled(Player player) {
        return playersConfig.getConfig().getBoolean(player.getName() + ".enabled.all", true);
    }

    private boolean isSpamming(Entity mob, Player player, EventType eventType) {
        String key = String.valueOf(mob.getEntityId()) + "/" + String.valueOf(player.getEntityId()) + "/" + eventType.getType();
        Long now = System.currentTimeMillis();
        Long spamTimeout = plugin.getConfig().getLong("spam-timeout");

        Long previousMessage = lastMessage.get(key);

        if (previousMessage == null || now - previousMessage > spamTimeout) {
            lastMessage.put(key, now);
            return false;
        } else {
            lastMessage.put(key, now);
            return true;
        }
    }

    /**
     * Format the message and send it to the player
     * Formatting includes replacing %player% with the name of the player and translating color codes.
     *
     * @param player  The player which should receive the message
     * @param message The message to send
     */
    private void sendFormattedMessage(Player player, String message) {
        String formattedMessage = message.replaceAll("%player%", player.getName());
        formattedMessage = ChatColor.translateAlternateColorCodes('&', formattedMessage);
        player.sendMessage(formattedMessage);
    }

    /**
     * Send a mob message to the player
     *
     * @param mob       The mob which sends the message
     * @param player    The player which should receive the message
     * @param eventType The event type
     */
    public void sendMessage(Entity mob, Player player, EventType eventType) {
        String message = getMessage(mob, eventType);

        if (message == null) {
            return;
        }

        sendMessage(mob, player, eventType, message);
    }

    /**
     * Send a mob message to the player
     *
     * @param mob                The mob which sends the message
     * @param player             The player which should receive the message
     * @param originalEventType  The original event type which triggered this message
     * @param possibleEventTypes The event types of which to pick the first possible one for getting the message
     */
    public void sendMessage(Entity mob, Player player, EventType originalEventType, List<EventType> possibleEventTypes) {
        for (EventType eventType : possibleEventTypes) {
            if (getMessages(mob, eventType) == null) {
                continue;
            }

            String message = getMessage(mob, eventType);

            sendMessage(mob, player, originalEventType, message);
            return;
        }
    }

    /**
     * Send a mob message to all players
     *
     * @param mob       The mob which sends the message
     * @param eventType The event type
     */
    public void sendMessage(Entity mob, EventType eventType) {
        if (mob instanceof Player) {
            return;
        }

        if (!(mob instanceof LivingEntity)) {
            return;
        }

        String message = getMessage(mob, eventType);
        if (message == null) {
            return;
        }

        for (Player player : plugin.getServer().getOnlinePlayers()) {
            sendMessage(mob, player, eventType, message);
        }
    }

    /**
     * Send a mob message to all players
     *
     * @param mob                The mob which sends the message
     * @param originalEventType  The original event type which triggered this message
     * @param possibleEventTypes The event types of which to pick the first possible one for getting the message
     */
    public void sendMessage(Entity mob, EventType originalEventType, List<EventType> possibleEventTypes) {
        if (mob instanceof Player) {
            return;
        }

        if (!(mob instanceof LivingEntity)) {
            return;
        }

        for (EventType eventType : possibleEventTypes) {
            if (getMessages(mob, eventType) == null) {
                continue;
            }

            String message = getMessage(mob, eventType);

            for (Player player : plugin.getServer().getOnlinePlayers()) {
                sendMessage(mob, player, originalEventType, message);
            }

            return;
        }
    }

    /**
     * Send the given mob message to the player
     *
     * @param mob       The mob which sends the message
     * @param player    The player which should receive the message
     * @param eventType The event type
     * @param message   The message to send
     */
    private void sendMessage(Entity mob, Player player, EventType eventType, String message) {
        if (mob instanceof Player) {
            return;
        }

        if (!(mob instanceof LivingEntity)) {
            return;
        }

        if (!isAllowed(player)) {
            return;
        }

        if (!isEnabled(player, eventType)) {
            return;
        }

        if (isSpamming(mob, player, eventType)) {
            return;
        }

        double maxDistance = plugin.getConfig().getDouble("maxDistance");

        if (maxDistance > 0) {
            double distance = player.getLocation().distance(mob.getLocation());
            if (distance != Double.NaN && distance <= maxDistance) {
                sendFormattedMessage(player, message);
            }
        } else {
            sendFormattedMessage(player, message);
        }
    }

    /**
     * Enable or disable talking mobs of the specified message type for the specified player
     *
     * @param player    The player for which the state should be changed
     * @param eventType The event type of which the state should be set
     * @param state     The new state
     */
    public void setEnabled(Player player, EventType eventType, Boolean state) {
        playersConfig.getConfig().set(player.getName() + ".enabled." + eventType.getType(), state);
        playersConfig.getConfig().set(player.getName() + ".enabled.all", true);

        playersConfig.save();
    }

    /**
     * Enable or disable talking mobs for the specified player
     *
     * @param player The player for which the state should be changed
     * @param state  The new state
     */
    public void setEnabled(Player player, Boolean state) {
        playersConfig.getConfig().set(player.getName() + ".enabled.all", state);

        for (EventType eventType : EventType.values()) {
            if (!eventType.isToggleable()) {
                continue;
            }

            playersConfig.getConfig().set(player.getName() + ".enabled." + eventType.getType(), state);
        }

        playersConfig.save();
    }
}


text:
module Network.API.Shopify (
  module Network.API.Shopify.Types
  ) where

import Network.API.Shopify.Types


text:
import type * as Types from './contentfulApi.generated';

export type FooterQueryVariables = Types.Exact<{ [key: string]: never }>;

export type FooterQuery = {
  readonly sectionCollection:
    | {
        readonly items: ReadonlyArray<
          | {
              readonly blocksCollection:
                | {
                    readonly items: ReadonlyArray<
                      | {
                          readonly title: string | undefined;
                          readonly url: string | undefined;
                          readonly icon: string | undefined;
                        }
                      | {}
                      | undefined
                    >;
                  }
                | undefined;
            }
          | undefined
        >;
      }
    | undefined;
};


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Validation</title>

Validation

      Waffle allows validation of action methods by means of the
        org.codehaus.waffle.validation.ErrorsContext interface.  The mechanism is simple and straightforward:
        to validate each ActionMethod, the user will need to add a method with the identical signature to the ActionMethod being validated
        except for the additional first argument of type ErrorsContext. Waffle will inject automatically an instance of ErrorsContext to your method.

       Waffle allows the validation methods to be defined in two ways:

In a separate controller validator class, conventially named from the controller

In the same controller class

       Note: if the validator class is found, it takes precendence over the validation methods in the controller class.

Let's work through an example.  Given the ActionMethod "addToCart" in the ShoppingCartController, the simplest way
    to add validation is to add a new method with the additional ErrorsContext as the first argument.
    The ActionMethod ensures that the quantity does not exceed 10, if so a new error message is
    created and add to the ErrorsContext instance.

    <textarea class="java:nogutter:nocontrols" name="code">
      public class ShoppingCartController implements Serializable {
        private final MessageResources messageResources;
        private final Cart cart;

        public ShoppingCartController(MessageResources messageResources, Cart cart) {
          this.messageResources = messageResources;
          this.cart = cart;
        }

        // This ActionMethod handles the add to chart functionality
        public void addToCart(long itemId, int quantity) {
            // add to cart functionality
        }

         // This method handles the validation of the ActionMethod above
        public void addToCart(ErrorsContext errors, long itemId, int quantity) {
          if(quantity > 10) {
            String message = messageResources.getMessage("quantity.error");
            FieldError fieldError = new FieldError("quantity", quantity, message);
            errors.addFieldError(fieldError);
            return;
          }

          ...
        }
      }
    </textarea>

      Alternatively, Waffle allows for an external validation class following a naming convention.
      Suppose the ShoppingCartController is registered under the name "shoppingCart":

      You can register any POJO you would like as a Validator. The only requirement is that it should be registered with
      the the conventional suffix Validator (or a different suffix that can be configured via the

        org.codehaus.waffle.validation.ValidatorConfiguration).
      In other words the POJO registered under the name "fooValidator" would be the
      Validator for the controller registered under the name "foo".  The Validator class will need to provide a
      separate method for each ActionMethod requiring validation. The following is an example of such a
      Validator:

    <textarea class="java:nogutter:nocontrols" name="code">
      public class ShoppingCartControllerValidator {

        // This method handles the validation of the ActionMethod in the ShoppingCartController
        public void addToCart(ErrorsContext errors, long itemId, int quantity) {
          if(quantity > 10) {
            String message = messageResources.getMessage("quantity.error");
            FieldError fieldError = new FieldError("quantity", quantity, message);
            errors.addFieldError(fieldError);
            return;
          }

      }
    </textarea>

Note: the validator class does not need to extend any custom Waffle classes or interfaces.


text:
@interface MMBarricadeResponseSet ()

@property (nonatomic, strong) NSMutableArray *mutableResponseList;

@end

@implementation MMBarricadeResponseSet
@synthesize defaultResponse = _defaultResponse;

- (instancetype)init {
    return [self initWithRequestName:nil respondsToRequest:nil];
}

- (instancetype)initWithRequestName:(NSString *)requestName
                  respondsToRequest:(BOOL (^)(NSURLRequest *request, NSURLComponents *components))respondsToRequest {
    self = [super init];
    if (self != nil) {
        _mutableResponseList = [NSMutableArray array];
        _requestName = [requestName copy];
        _respondsToRequest = [respondsToRequest copy];
    }
    return self;
}

+ (instancetype)responseSetForRequestName:(NSString *)requestName
                        respondsToRequest:(BOOL (^)(NSURLRequest *request, NSURLComponents *components))respondsToRequest {
    return [[[self class] alloc] initWithRequestName:requestName respondsToRequest:respondsToRequest];
}

#pragma mark - Public

- (void)addResponse:(id<MMBarricadeResponse>)response {
    if (response) {
        [self.mutableResponseList addObject:response];
    }
}

- (void)createResponseWithBlock:(id<MMBarricadeResponse> (^)(void))creationBlock {
    if (creationBlock) {
        id<MMBarricadeResponse> response = creationBlock();
        [self addResponse:response];
    }
}

- (void)createResponseWithName:(NSString *)name
               populationBlock:(void (^)(MMBarricadeResponse *))populationBlock {

    MMBarricadeResponse *response = [[MMBarricadeResponse alloc] init];
    response.name = name;
    if (populationBlock) {
        populationBlock(response);
    }
    [self addResponse:response];
}

- (id<MMBarricadeResponse>)defaultResponse {
    if (_defaultResponse == nil) {
        return [self.allResponses firstObject];
    }
    return _defaultResponse;
}

- (void)setDefaultResponse:(id<MMBarricadeResponse>)defaultResponse {
    if ([self.allResponses containsObject:defaultResponse]) {
        _defaultResponse = defaultResponse;
    }
}

- (NSArray *)allResponses {
    return [self.mutableResponseList copy];
}

- (void)setAllResponses:(NSArray *)allResponses {
    if ([allResponses containsObject:self.defaultResponse] == NO) {
        _defaultResponse = nil;
    }
    self.mutableResponseList = [allResponses mutableCopy];
}

- (id<MMBarricadeResponse>)responseWithName:(NSString *)responseName {
    for (id<MMBarricadeResponse> response in self.allResponses) {
        if ([response.name isEqualToString:responseName]) {
            return response;
        }
    }
    return nil;
}

@end


text:
import stix
import stix.utils as utils
from stix.common import (
    GenericRelationshipList, RelatedObservable, StructuredTextList, Confidence,
    InformationSource
)
import stix.bindings.indicator as indicator_binding

class Sighting(stix.Entity):
    _namespace = "http://stix.mitre.org/Indicator-2"
    _binding = indicator_binding
    _binding_class = _binding.SightingType

    def __init__(self, timestamp=None, timestamp_precision=None, description=None):
        self.timestamp = timestamp or utils.dates.now()
        self.timestamp_precision = timestamp_precision
        self.description = description
        self.source = None
        self.reference = None
        self.confidence = None
        self.related_observables = RelatedObservables()

    @property
    def timestamp(self):
        return self._timestamp

    @timestamp.setter
    def timestamp(self, value):
        self._timestamp = utils.dates.parse_value(value)

    @property
    def description(self):
        """A single description about the contents or purpose of this object.

        Default Value: ``None``

        Note:
            If this object has more than one description set, this will return
            the description with the lowest ordinality value.

        Returns:
            An instance of
            :class:`.StructuredText`

        """
        return next(iter(self.descriptions), None)

    @description.setter
    def description(self, value):
        self.descriptions = value

    @property
    def descriptions(self):
        """A :class:`.StructuredTextList` object, containing descriptions about
        the purpose or intent of this object.

        This is typically used for the purpose of providing multiple
        descriptions with different classificaton markings.

        Iterating over this object will yield its contents sorted by their
        ``ordinality`` value.

        Default Value: Empty :class:`.StructuredTextList` object.

        Note:
            IF this is set to a value that is not an instance of
            :class:`.StructuredText`, an effort will ne made to convert it.
            If this is set to an iterable, any values contained that are not
            an instance of :class:`.StructuredText` will be be converted.

        Returns:
            An instance of
            :class:`.StructuredTextList`

        """
        return self._description

    @descriptions.setter
    def descriptions(self, value):
        self._description = StructuredTextList(value)

    def add_description(self, description):
        """Adds a description to the ``descriptions`` collection.

        This is the same as calling "foo.descriptions.add(bar)".

        """
        self.descriptions.add(description)

    @property
    def source(self):
        return self._source

    @source.setter
    def source(self, value):
        self._set_var(InformationSource, try_cast=False, source=value)

    @property
    def confidence(self):
        return self._confidence

    @confidence.setter
    def confidence(self, value):
        self._set_var(Confidence, confidence=value)

    def to_obj(self, return_obj=None, ns_info=None):
        super(Sighting, self).to_obj(return_obj=return_obj, ns_info=ns_info)

        if not return_obj:
            return_obj = self._binding_class()

        return_obj.timestamp = utils.dates.serialize_value(self.timestamp)
        return_obj.timestamp_precision = self.timestamp_precision
        return_obj.Reference = self.reference

        if self.source:
            return_obj.Source = self.source.to_obj(ns_info=ns_info)
        if self.confidence:
            return_obj.Confidence = self.confidence.to_obj(ns_info=ns_info)
        if self.descriptions:
            return_obj.Description = self.descriptions.to_obj(ns_info=ns_info)
        if self.related_observables:
            return_obj.Related_Observables = self.related_observables.to_obj(ns_info=ns_info)

        return return_obj

    def to_dict(self):
        return super(Sighting, self).to_dict()

    @classmethod
    def from_obj(cls, obj, return_obj=None):
        if not obj:
            return None

        if return_obj is None:
            return_obj = cls()

        return_obj.timestamp = obj.timestamp
        return_obj.timestamp_precision = obj.timestamp_precision
        return_obj.source = InformationSource.from_obj(obj.Source)
        return_obj.reference = obj.Reference
        return_obj.confidence = Confidence.from_obj(obj.Confidence)
        return_obj.descriptions = StructuredTextList.from_obj(obj.Description)
        return_obj.related_observables = RelatedObservables.from_obj(obj.Related_Observables)
        return return_obj

    @classmethod
    def from_dict(cls, d, return_obj=None):
        if not d:
            return None
        if return_obj is None:
            return_obj = cls()

        return_obj.timestamp = d.get('timestamp')
        return_obj.timestamp_precision = d.get('timestamp_precision')
        return_obj.source = InformationSource.from_dict(d.get('source'))
        return_obj.reference = d.get('reference')
        return_obj.confidence = Confidence.from_dict(d.get('confidence'))
        return_obj.descriptions = StructuredTextList.from_dict(d.get('description'))
        return_obj.related_observables = RelatedObservables.from_dict(d.get('related_observables'))
        return return_obj

class Sightings(stix.EntityList):
    _namespace = "http://stix.mitre.org/Indicator-2"
    _binding = indicator_binding
    _binding_class = _binding.SightingsType
    _contained_type = Sighting
    _binding_var = "Sighting"
    _inner_name = "sightings"

    def __init__(self, sightings_count=None, *args):
        super(Sightings, self).__init__(*args)
        self.sightings_count = sightings_count

    def __nonzero__(self):
        return super(Sightings, self).__nonzero__() or bool(self.sightings_count)

    @property
    def sightings_count(self):
        return self._sightings_count

    @sightings_count.setter
    def sightings_count(self, value):
        self._set_var(int, sightings_count=value)

    def to_obj(self, return_obj=None, ns_info=None):
        list_obj = super(Sightings, self).to_obj(return_obj=return_obj, ns_info=ns_info)
        list_obj.sightings_count = self.sightings_count
        return list_obj

    def to_dict(self):
        d = super(Sightings, self).to_dict()
        if self.sightings_count:
            d['sightings_count'] = self.sightings_count
        return d

    @classmethod
    def from_obj(cls, obj, return_obj=None):
        if not obj:
            return None
        if return_obj is None:
            return_obj = cls()

        super(Sightings, cls).from_obj(obj, return_obj=return_obj)
        return_obj.sightings_count = obj.sightings_count
        return return_obj

    @classmethod
    def from_dict(cls, dict_repr, return_obj=None):
        if not dict_repr:
            return None
        if return_obj is None:
            return_obj = cls()

        super(Sightings, cls).from_dict(dict_repr, return_obj=return_obj)
        return_obj.sightings_count = dict_repr.get('sightings_count')
        return return_obj

class RelatedObservables(GenericRelationshipList):
    _namespace = "http://stix.mitre.org/Indicator-2"
    _binding = indicator_binding
    _binding_class = _binding.RelatedObservablesType
    _binding_var = "Related_Observable"
    _contained_type = RelatedObservable
    _inner_name = "observables"


text:
VanilaGateway
=============

Sample gateway user interface to demonstrate Apache Airavata API capabilities.

An customized version of this code runs the IU Cyberinfrastructure Gateway


text:
<?php

namespace aplicacion\EmisionesBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use aplicacion\EmisionesBundle\Entity\Formapago;
use aplicacion\EmisionesBundle\Form\FormapagoType;

/**
 * Formapago controller.
 *
 */
class FormapagoController extends Controller
{

    /**
     * Lists all Formapago entities.
     *
     */
    public function indexAction($orden)
    {
        $em = $this->getDoctrine()->getManager();
        $orden=$em->getRepository('EmisionesBundle:Orden')->find($orden);
        $entities = $em->getRepository('EmisionesBundle:Formapago')->findBy(array('orden'=>$orden));

        return $this->render('EmisionesBundle:Formapago:index.html.twig', array(
            'entities' => $entities,
            'entity'=>$orden
        ));
    }
    /**
     * Creates a new Formapago entity.
     *
     */
    public function createAction(Request $request)
    {
        $entity = new Formapago();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('formapago_show', array('id' => $entity->getId())));
        }

        return $this->render('EmisionesBundle:Formapago:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Creates a form to create a Formapago entity.
     *
     * @param Formapago $entity The entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createCreateForm(Formapago $entity)
    {
        $form = $this->createForm(new FormapagoType(), $entity, array(
            'action' => $this->generateUrl('formapago_create'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Create'));

        return $form;
    }

    /**
     * Displays a form to create a new Formapago entity.
     *
     */
    public function newAction()
    {
        $entity = new Formapago();
        $form   = $this->createCreateForm($entity);

        return $this->render('EmisionesBundle:Formapago:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Finds and displays a Formapago entity.
     *
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('EmisionesBundle:Formapago')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Formapago entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return $this->render('EmisionesBundle:Formapago:show.html.twig', array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Displays a form to edit an existing Formapago entity.
     *
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('EmisionesBundle:Formapago')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Formapago entity.');
        }

        $editForm = $this->createEditForm($entity);
        $deleteForm = $this->createDeleteForm($id);

        return $this->render('EmisionesBundle:Formapago:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
    * Creates a form to edit a Formapago entity.
    *
    * @param Formapago $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(Formapago $entity)
    {
        $form = $this->createForm(new FormapagoType(), $entity, array(
            'action' => $this->generateUrl('formapago_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

        $form->add('submit', 'submit', array('label' => 'Update'));

        return $form;
    }
    /**
     * Edits an existing Formapago entity.
     *
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('EmisionesBundle:Formapago')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Formapago entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();

            return $this->redirect($this->generateUrl('formapago_edit', array('id' => $id)));
        }

        return $this->render('EmisionesBundle:Formapago:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }
    /**
     * Deletes a Formapago entity.
     *
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('EmisionesBundle:Formapago')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Formapago entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('formapago'));
    }

    /**
     * Creates a form to delete a Formapago entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('formapago_delete', array('id' => $id)))
            ->setMethod('DELETE')
            ->add('submit', 'submit', array('label' => 'Delete'))
            ->getForm()
        ;
    }
}


text:
package demoapp.dom.domain.objects.DomainObject.entityChangePublishing.metaAnnotOverridden.enabled.jdo;

import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;

import demoapp.dom._infra.values.ValueHolderRepository;

@Profile("demo-jdo")
@Service
public class DomainObjectEntityChangePublishingEnabledMetaAnnotOverriddenJdoEntities
extends ValueHolderRepository<String, DomainObjectEntityChangePublishingEnabledMetaAnnotOverriddenJdo> {

    protected DomainObjectEntityChangePublishingEnabledMetaAnnotOverriddenJdoEntities() {
        super(DomainObjectEntityChangePublishingEnabledMetaAnnotOverriddenJdo.class);
    }

    @Override
    protected DomainObjectEntityChangePublishingEnabledMetaAnnotOverriddenJdo newDetachedEntity(String value) {
        return new DomainObjectEntityChangePublishingEnabledMetaAnnotOverriddenJdo(value);
    }

}


text:
import os
from getout import create_app

if __name__ == "__main__":
    dirname = os.path.dirname(os.path.abspath(__file__))
    app = create_app(os.path.join(dirname, "local.py"))
    app.debug = True
    app.run()


text:
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="../orov-behaviors/orov-behavior.html">
<dom-module id="orov-newui-depth">

  <template>

LK

          {{formatDepth(depth)}}

            {{__('LK: ')}}
            {{target}}

        {{__(waterType)}}
         {{depthUnit}}

        {{__('VSI')}}

          <svg viewBox="0 0 100 100">
            <polygon id="upPolygon" points="0,100 50,0 100,100" style="fill:black;stroke:black;stroke-width:0"></polygon>
          </svg>

{{ change }}

          <svg viewBox="0 0 100 100">
            <polygon id="downPolygon" points="0,0 50,100 100,0 " style="fill:none;stroke:black;stroke-width:0"></polygon>
          </svg>

{{depthUnit}}{{__('/s')}}

  </template>

</dom-module>