text:
'use strict';

// Rutas
// -----
// Definimos as rutas para o controlador
angular.module('adminApp').config(['$routeProvider',
    function($routeProvider){
        $routeProvider.
            when('/apartments', {
                templateUrl: 'assets/js/admin/views/apartments/index.html',
                controller: 'ApartmentsIndexCtrl',
                resolve: {
                    Apartments: function(ApartmentService) {
                        return ApartmentService.query().$promise;
                    },
                    Countries: function(CountryService) {
                        return CountryService.query().$promise;
                    }
                }
            }).
            when('/apartments/create', {
                templateUrl: 'assets/js/admin/views/apartments/form.html',
                controller: 'ApartmentsFormCtrl',
                resolve: {
                    Apartment: function(ApartmentService, $rootScope) {
                        return new ApartmentService({services: [], user: $rootScope.user._id});
                    },
                    Spots: function(SpotService) {
                        return SpotService.query().$promise;
                    },
                    Countries: function(CountryService) {
                        return CountryService.query().$promise;
                    },
                    Services: function(ServiceService) {
                        return ServiceService.query().$promise;
                    },
                    Owners: function(UserService) {
                        return UserService.query({group: 3}).$promise;
                    }
                }
            }).
            when('/apartments/edit/:id', {
                templateUrl: 'assets/js/admin/views/apartments/form.html',
                controller: 'ApartmentsFormCtrl',
                resolve: {
                    Apartment: function($rootScope, ApartmentService, $route) {
                        return ApartmentService.get({id: $route.current.params.id}).$promise;
                    },
                    Spots: function(SpotService) {
                        return SpotService.query().$promise;
                    },
                    Countries: function(CountryService) {
                        return CountryService.query().$promise;
                    },
                    Services: function(ServiceService) {
                        return ServiceService.query().$promise;
                    },
                    Owners: function(UserService) {
                        return UserService.query({group: 3}).$promise;
                    }
                }
            }).
            when('/apartments/apartments/:id', {
                templateUrl: 'assets/js/admin/views/apartments/apartments.html',
                controller: 'ApartmentsApartmentsCtrl',
                resolve: {
                    Apartment: function($rootScope, ApartmentService, $route) {
                        return ApartmentService.get({id: $route.current.params.id}).$promise;
                    }
                }
            }).
            when('/apartments/images/:id', {
                templateUrl: 'assets/js/admin/views/apartments/images.html',
                controller: 'ApartmentsImagesCtrl',
                resolve: {
                    Apartment: function($rootScope, ApartmentService, $route) {
                        return ApartmentService.get({id: $route.current.params.id}).$promise;
                    }
                }
            });
    }
]);

// ##Controladores
// Creamos os controladores necesarios para manexar as vistas

// ###Controlador da páxina inicial
// Controlador encargado de mostrar a páxina inicial
angular.module('adminApp').controller('ApartmentsIndexCtrl', function($rootScope, $filter, $flash, $scope, Apartments, Countries, ProvinceService, TownService) {
    // Definimos la sección actual
    $rootScope.current_section = 'apartments';

    // Definimos la lista de apartamentos
    $scope.apartments = Apartments;

    // Definimos los datos necesarios para la búsqueda
    $scope.search = $rootScope.apartment_search || {};
    $scope.countries = Countries;
    $scope.provinces = $scope.towns = [];

    // Gardamos a busqueda no rootscope
    $scope.$watch('search', function() {
        $rootScope.apartment_search = $scope.search;
    });

    // Evento para cargar as provincias o seleccionar o pais
    $scope.$watch('search.country', function(country) {
        if (country) {
            $scope.provinces = ProvinceService.query({country: country});
        } else {
            $scope.provinces = $scope.towns = [];
            delete($scope.search.country);
            delete($scope.search.province);
            delete($scope.search.town);
        }
    });

    // Evento para cargar as cidades o seleccionar a provincia
    $scope.$watch('search.province', function(province) {
        if (province) {
            $scope.towns = TownService.query({province: province});
        } else {
            $scope.towns = [];
            delete($scope.search.province);
            delete($scope.search.town);
        }
    });

    // Evento para remover o atributo da cidade se e igual a null
    $scope.$watch('search.town', function(town) {
        if ( ! town) {
            delete($scope.search.town);
        }
    });

    // Eliminar un apartamento
    $scope.deleteApartment = function($index) {
        if (confirm($filter('translate')('admin.are_you_sure'))) {
            $scope.apartments[$index].$delete(function() {
                $scope.apartments.splice($index, 1);
                $flash.set('success', $filter('translate')('admin.apartments.apartment_has_been_delete'));
                $flash.show();
            });
        }
    };
});

// ###Controlador do formulario
// Controlador encargado de crear/modificar bloques de apartamentos
angular.module('adminApp').controller('ApartmentsFormCtrl', function($rootScope, $scope, $translate, $filter, $flash, $location, Apartment, Spots, Countries, Services, ProvinceService, TownService, Owners) {
    // Definimos la sección actual
    $rootScope.current_section = 'apartments';

    // Definimos o idioma de edición por defecto
    $scope.active_language = $translate.use();

    // Definimos el apartamento en $scope
    $scope.apartment = Apartment;

    // Definimos os propietarios
    $scope.owners = Owners;

    // Definimos os emplazamentos
    $scope.spots = Spots;

    // Definimos os servicios dispoñibles
    $scope.services = Services;

    // Definimos os paises
    $scope.countries = Countries;

    // Definimos as provincias e cidades en blanco xa que só se cargarán o elexir os campos maiores
    $scope.provinces = $scope.towns = [];

    // Cambiar o idioma de edición
    $scope.setActiveLanguage = function(language) {
        $scope.active_language = language;
    };

    // Cargar as provincias relacionadas ó pais
    $scope.loadProvinces = function() {
        var country = $scope.apartment.country;
        if (country) {
            $scope.provinces = ProvinceService.query({country: country});
        } else {
            $scope.provinces = [];
            $scope.towns = [];
        }
    };

    // Cargar as cidades relacionadas a provincia
    $scope.loadTowns = function() {
        var province = $scope.apartment.province;
        if (province) {
            $scope.towns = TownService.query({province: province});
        } else {
            $scope.towns = [];
        }
    };

    // Definimos en el $scope que tipo de acción estamos realizando y
    // cargamos las provincias y ciudades
    if (Apartment._id) {
        $scope.action = 'editing';
        $scope.loadProvinces();
        $scope.loadTowns();
    } else {
        $scope.action = 'creating';
    }

    // Comprobar se o servizo está activo
    $scope.activedService = function($id) {
        if ($scope.apartment.services.indexOf($id) !== -1) {
            return true;
        }
        return false;
    };

    // Cambiar o estado do servizo
    $scope.toggleService = function($id) {
        if ($scope.activedService($id)) {
            var index = $scope.apartment.services.indexOf($id);
            $scope.apartment.services.splice(index, 1);
        } else {
            $scope.apartment.services.push($id);
        }
        $scope.form.$setDirty();
    };

    // Cancelamos a acción e volvemos atrás sen gardar ningún cambio
    $scope.cancel = function() {
        // Se o formulario foi modificado preguntamos ó
        // usuario se está seguro de cancelar.
        if ( ! $scope.form.$pristine) {
            if ( ! confirm($filter('translate')('admin.are_you_sure'))) {
                return false;
            }
        }
        window.history.back();
    };

    // Gardamos o apartamento
    $scope.saveApartment = function() {
        // Se é unha actualización executamos o método $update e se non, $save.
        if ($scope.apartment._id) {
            $scope.apartment.$update(function() {
                $flash.set('success', 'admin.changes_has_been_saved');
                $location.path('/apartments');
            });
        } else {
            $scope.apartment.$save(function() {
                $flash.set('success', 'admin.changes_has_been_saved');
                $location.path('/apartments');
            });
        }
    };

    // Mapa
    var map = null;
    var marker = null;
    // Coordenadas por defecto en España
    var coords = [40.41153868,-3.70362707];
    var zoom = 6;
    if ($scope.apartment.geoposition) {
        coords = $scope.apartment.geoposition.split(':')[0].split(',').map(function(a){return parseFloat(a);});
        zoom = parseInt($scope.apartment.geoposition.split(':')[1]);
    }

    var initMap = function() {
        var position = new google.maps.LatLng(coords[0], coords[1]);
        var mapOptions = {
            center: position,
            zoom: zoom,
            scrollwheel: false,
            mapTypeId: google.maps.MapTypeId.HYBRID
        };
        map = new google.maps.Map(document.getElementById('map'), mapOptions);
        marker = new google.maps.Marker({
            map: map,
            position: position,
            draggable: true,
            animation: google.maps.Animation.DROP
        });

        google.maps.event.addListener(marker, 'dragend', $scope.setCoords);
        google.maps.event.addListener(map, 'zoom_changed', function(){
            $scope.apartment.geoposition = $scope.apartment.geoposition.replace(/\:(.*)/, ':'+map.zoom);
            $scope.form.$setDirty();
            $scope.$apply();
        });
    };

    $scope.centerAndSetMarkerOnAddress = function() {
        // Se o usuario introduciu unha dirección na barra de busqueda,
        // buscamos esa dirección e se non, creamos a dirección a partir
        // dos datos do apartamento.
        var search_address = $scope.search_address;
        if ( ! search_address) {
            var country = $('#input-country option:selected').html();
            var province = $('#input-province option:selected').html();
            var town = $('#input-town option:selected').html();
            search_address = $scope.apartment.address+', '+town+', '+province+', '+country;
            $scope.search_address = search_address;
        }
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode({address: search_address}, function(results, status) {
            if (status === google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
                map.setZoom(16);
                marker.setPosition(results[0].geometry.location);
                $scope.apartment.geoposition = results[0].geometry.location.toString().slice(1).slice(0, -1).replace(' ', '')+':'+map.zoom;
                $scope.form.$setDirty();
                $scope.$apply();
            }
        });
    };

    $scope.setCoords = function(ev) {
        var coords = ev.latLng.toString().slice(1).slice(0, -1).replace(' ', '')+':'+map.zoom;
        $scope.apartment.geoposition = coords;
        $scope.form.$setDirty();
        $scope.$apply();
    };

    initMap();
});

angular.module('adminApp').controller('ApartmentsApartmentsCtrl', function($rootScope, $timeout, $filter, $flash, $location, $scope, Apartment, ApartmentService) {
    // Definimos a sección actual
    $rootScope.current_section = 'apartments';

    // Definimos a variable hasChanges para notificar a vista cando hay cambios.
    $scope.hasChanges = false;

    // Definimos o index do apartamento actual
    $scope.apartment_index = null;
    $scope.apartment = null;

    // Definimos o bloque de apartamentos
    $scope.apartment_block = Apartment;

    // E tamén os apartamentos do bloque de apartamentos
    $scope.apartments = Apartment.apartments || [];

    // Función para gardar o bloque de apartamentos na base de datos
    $scope.saveApartmentsBlock = function() {
        // Cargamos o bloque de apartamentos de novo por se sufriu algún cambio exterior
        ApartmentService.get({id: Apartment._id}).$promise.then(function(Apartment) {
            Apartment.apartments = $scope.apartments;
            Apartment.$update(function() {
                $flash.set('success', 'admin.changes_has_been_saved');
                window.history.back();
            });
        });
    };

    // Función para engadir un novo apartamento
    $scope.addApartment = function() {
        $scope.apartment = {
            seasons:[],
            closed:[]
        };
    };

    // Función para cancelar a creación / edición dun apartamento
    $scope.cancelApartment = function() {
        if ($scope.apartmentForm.$pristine || confirm($filter('translate')('admin.are_you_sure'))) {
            $scope.apartment = $scope.apartment_index = null;
        }
    };

    // Función para gardar o apartamento
    $scope.saveApartment = function() {
        if ($scope.apartment_index !== null) {
            $scope.apartments[$scope.apartment_index] = angular.copy($scope.apartment);
        } else {
            $scope.apartments.push(angular.copy($scope.apartment));
        }
        $scope.apartment = $scope.apartment_index = null;
        $scope.apartmentForm.$setPristine();
        $scope.hasChanges = true;
    };

    // Función para editar un apartamento
    $scope.editApartment = function($index) {
        $scope.apartment = angular.copy($scope.apartments[$index]);
        $scope.apartment_index = $index;
    };

    // Función para eliminar un apartamento
    $scope.deleteApartment = function() {
        if (confirm($filter('translate')('admin.are_you_sure'))) {
            $scope.apartments.splice($scope.apartment_index, 1);
            $scope.apartment = $scope.apartment_index = null;
        }
    };

    // Función para duplicar un apartamento (moi util para as tarifas)
    $scope.duplicateApartment = function() {
        var apartment = angular.copy($scope.apartment);
        $scope.apartment_index = null;
        $scope.apartment = null;
        $timeout(function(){
            $scope.apartment = apartment;
            $scope.$apply();
        }, 100);
    };

    // Definimos que non se está a engadir ningunha data de peche ou ningunha tarifa
    $scope.season_index = $scope.closed_index = null;
    $scope.season = $scope.closed = null;

    // Engadimos unha nova tarifa
    $scope.addSeason = function() {
        $scope.season = {};
    };

    // Cancelamos a creación / edición dunha temporada
    $scope.cancelSeason = function() {
        $scope.season = null;
        $scope.season_index = null;
    };

    // Gardar os datos da temporada no apartamento
    $scope.saveSeason = function() {
        if ($scope.season_index !== null) {
            $scope.apartment.seasons[$scope.season_index] = angular.copy($scope.season);
        } else {
            $scope.apartment.seasons.push($scope.season);
        }
        $scope.season = $scope.season_index = null;
        $scope.apartmentForm.$setDirty();
    };

    // Editamos unha temporada
    $scope.editSeason = function($index) {
        $scope.season_index = $index;
        $scope.season = {};
        $scope.season = angular.copy($scope.apartment.seasons[$index]);
        $scope.renderSeasonDates();
    };

    // Eliminar unha temporada existente
    $scope.deleteSeason = function($index) {
        if (confirm($filter('translate')('admin.are_you_sure'))) {
            $scope.apartment.seasons.splice($index, 1);
        }
    };

    // Engadimos unha nova data de peche
    $scope.addClosed = function() {
        $scope.closed = {};
    };

    // Cancelamos a creación / edición dunha data de peche
    $scope.cancelClosed = function() {
        $scope.closed = null;
        $scope.closed_index = null;
    };

    // Gardar os datos da temporada de peche no apartamento
    $scope.saveClosed = function() {
        if ($scope.closed_index !== null) {
            $scope.apartment.closed[$scope.closed_index] = angular.copy($scope.closed);
        } else {
            $scope.apartment.closed.push($scope.closed);
        }
        $scope.closed = $scope.closed_index = null;
        $scope.apartmentForm.$setDirty();
    };

    // Editamos unha data de peche
    $scope.editClosed = function($index) {
        $scope.closed_index = $index;
        $scope.closed = {};
        $scope.closed = angular.copy($scope.apartment.closed[$index]);
        $scope.renderClosedDates();
    };

    // Eliminar unha data de peche existente
    $scope.deleteClosed = function($index) {
        if (confirm($filter('translate')('admin.are_you_sure'))) {
            $scope.apartment.closed.splice($index, 1);
        }
    };

    // Datepicker
    $scope.dateOptions = {
        startingDay: 1,
        showWeeks: false,
        showButtonBar: false
    };

    // Fix para o render das datas a hora de editar as temporadas
    $scope.renderSeasonDates = function() {
        angular.element($('#input-season-from')).controller('ngModel').$setViewValue(new Date($scope.season.from));
        angular.element($('#input-season-from')).controller('ngModel').$render();
        angular.element($('#input-season-to')).controller('ngModel').$setViewValue(new Date($scope.season.to));
        angular.element($('#input-season-to')).controller('ngModel').$render();
    };

    // Fix para o render das datas a hora de editar as datas de peche
    $scope.renderClosedDates = function() {
        angular.element($('#input-closed-from')).controller('ngModel').$setViewValue(new Date($scope.closed.from));
        angular.element($('#input-closed-from')).controller('ngModel').$render();
        angular.element($('#input-closed-to')).controller('ngModel').$setViewValue(new Date($scope.closed.to));
        angular.element($('#input-closed-to')).controller('ngModel').$render();
    };

    // Cancelamos a acción e voltamos atrás sen gardar ningún cambio
    $scope.cancel = function() {
        // Se o formulario foi modificado preguntamos ó
        // usuario se está seguro de cancelar.
        if ($scope.hasChanges) {
            if ( ! confirm($filter('translate')('admin.are_you_sure'))) {
                return false;
            }
        }
        window.history.back();
    };
});

angular.module('adminApp').controller('ApartmentsImagesCtrl', function($rootScope, $scope, $filter, $flash, $location, Apartment, ApartmentService) {
    // Definimos a sección actual
    $rootScope.current_section = 'apartments';

    // Definimos o apartamento e as imaxes
    $scope.apartment = Apartment;
    $scope.images = Apartment.images || [];
    $scope.uploading = [];

    // Gardamos os arquivos que se van a subir nun array para mostralos
    $scope.uploadStart = function(files) {
        $scope.uploading = files;
    };

    // Función para eliminar unha imaxe
    $scope.deleteImage = function($index) {
        if (confirm($filter('translate')('admin.are_you_sure'))) {
            $scope.images.splice($index, 1);
        }
    };

    // Callback para cando termina de subir unha imaxe
    $scope.uploadComplete = function(response) {
        var images = [];
        $.each(response.data, function(index, item) {
            images.push({
                file: item
            });
        });
        $scope.images = $scope.images.concat(images);
    };

    // Función para gardar os datos na base de datos
    $scope.saveImages = function() {
        // Cargamos o bloque de apartamentos de novo por se sufriu algún cambio exterior
        ApartmentService.get({id: Apartment._id}).$promise.then(function(Apartment) {
            Apartment.images = $scope.images;
            Apartment.$update(function() {
                $flash.set('success', 'admin.changes_has_been_saved');
                window.history.back();
            })
        });
    };

    // Función para cancelar e voltar atrás
    $scope.cancel = function() {
        if ( ! confirm($filter('translate')('admin.are_you_sure'))) {
            return false;
        }
        window.history.back();
    };
});


text:
package com.intellij.uiDesigner.core;

import java.awt.*;
import java.util.ArrayList;

/**
 * public for test purposes
 * @noinspection AbstractMethodCallInConstructor,RedundantCast
 */
public abstract class DimensionInfo {
  private final int[] myCell;
  private final int[] mySpan;
  protected final LayoutState myLayoutState;
  private final int[] myStretches;
  private final int[] mySpansAfterElimination;
  private final int[] myCellSizePolicies;
  private final int myGap;

  public DimensionInfo(final LayoutState layoutState, final int gap){
    if (layoutState == null){
      throw new IllegalArgumentException("layoutState cannot be null");
    }
    if (gap < 0){
      throw new IllegalArgumentException("invalid gap: " + gap);
    }
    myLayoutState = layoutState;
    myGap = gap;

    myCell = new int[layoutState.getComponentCount()];
    mySpan = new int[layoutState.getComponentCount()];

    for (int i = 0; i < layoutState.getComponentCount(); i++) {
      final GridConstraints c = layoutState.getConstraints(i);
      myCell[i] = getOriginalCell(c);
      mySpan[i] = getOriginalSpan(c);
    }

    myStretches = new int[getCellCount()];
    for (int i = 0; i < myStretches.length; i++) {
      myStretches[i] = 1;
    }
    //TODO[anton,vova] handle stretches

    final ArrayList elimitated = new ArrayList();
    mySpansAfterElimination = (int[])mySpan.clone();
    Util.eliminate((int[])myCell.clone(), mySpansAfterElimination, elimitated);

    myCellSizePolicies = new int[getCellCount()];
    for (int i = 0; i < myCellSizePolicies.length; i++) {
      myCellSizePolicies[i] = getCellSizePolicyImpl(i, elimitated);
    }
  }

  public final int getComponentCount(){
    return myLayoutState.getComponentCount();
  }

  public final Component getComponent(final int componentIndex){
    return myLayoutState.getComponent(componentIndex);
  }

  public final GridConstraints getConstraints(int componentIndex) {
    return myLayoutState.getConstraints(componentIndex);
  }

  public abstract int getCellCount();

  public abstract int getPreferredWidth(int componentIndex);
  public abstract int getMinimumWidth(int componentIndex);
  public abstract DimensionInfo getDimensionInfo(GridLayoutManager grid);

  public final int getCell(final int componentIndex){
    return myCell[componentIndex];
  }

  public final int getSpan(final int componentIndex){
    return mySpan[componentIndex];
  }

  public final int getStretch(final int cellIndex){
    return myStretches[cellIndex];
  }

  protected abstract int getOriginalCell(GridConstraints constraints);
  protected abstract int getOriginalSpan(GridConstraints constraints);

  abstract int getSizePolicy(int componentIndex);

  abstract int getChildLayoutCellCount(final GridLayoutManager childLayout);

  public final int getGap(){
    return myGap;
  }

  public boolean componentBelongsCell(final int componentIndex, final int cellIndex) {
    final int componentStartCell = getCell(componentIndex);
    final int span = getSpan(componentIndex);
    return componentStartCell <= cellIndex && cellIndex < componentStartCell + span;
  }

  public final int getCellSizePolicy(final int cellIndex){
    return myCellSizePolicies[cellIndex];
  }

  private int getCellSizePolicyImpl(final int cellIndex, final ArrayList eliminatedCells){
    int policyFromChild = getCellSizePolicyFromInheriting(cellIndex);
    if (policyFromChild != -1) {
      return policyFromChild;
    }
    for (int i = eliminatedCells.size() - 1; i >= 0; i--) {
      if (cellIndex == ((Integer)eliminatedCells.get(i)).intValue()) {
        return GridConstraints.SIZEPOLICY_CAN_SHRINK;
      }
    }

    return calcCellSizePolicy(cellIndex);
  }

  private int calcCellSizePolicy(final int cellIndex) {
    boolean canShrink = true;
    boolean canGrow = false;
    boolean wantGrow = false;

    boolean weakCanGrow = true;
    boolean weakWantGrow = true;

    int countOfBelongingComponents = 0;

    for (int i = 0; i < getComponentCount(); i++) {
      if (!componentBelongsCell(i, cellIndex)){
        continue;
      }

      countOfBelongingComponents++;

      final int p = getSizePolicy(i);

      final boolean thisCanShrink = (p & GridConstraints.SIZEPOLICY_CAN_SHRINK) != 0;
      final boolean thisCanGrow = (p & GridConstraints.SIZEPOLICY_CAN_GROW) != 0;
      final boolean thisWantGrow = (p & GridConstraints.SIZEPOLICY_WANT_GROW) != 0;

      if (getCell(i) == cellIndex && mySpansAfterElimination[i] == 1) {
        canShrink &= thisCanShrink;
        canGrow |= thisCanGrow;
        wantGrow |= thisWantGrow;
      }

      if (!thisCanGrow) {
        weakCanGrow = false;
      }
      if (!thisWantGrow) {
        weakWantGrow = false;
      }
    }

    return
      (canShrink ? GridConstraints.SIZEPOLICY_CAN_SHRINK : 0) |
      (canGrow || (countOfBelongingComponents > 0 && weakCanGrow) ? GridConstraints.SIZEPOLICY_CAN_GROW : 0) |
      (wantGrow || (countOfBelongingComponents > 0 && weakWantGrow) ? GridConstraints.SIZEPOLICY_WANT_GROW : 0);
  }

  private int getCellSizePolicyFromInheriting(final int cellIndex) {
    int nonInheritingComponentsInCell = 0;
    int policyFromInheriting = -1;
    for(int i=getComponentCount() - 1; i >= 0; i--) {
      if (!componentBelongsCell(i, cellIndex)) {
        continue;
      }
      Component child = getComponent(i);
      GridConstraints c = getConstraints(i);
      Container container = findAlignedChild(child, c);
      if (container != null) {
        GridLayoutManager grid = (GridLayoutManager) container.getLayout();
        grid.validateInfos(container);
        DimensionInfo info = getDimensionInfo(grid);
        final int policy = info.calcCellSizePolicy(cellIndex - getOriginalCell(c));
        if (policyFromInheriting == -1) {
          policyFromInheriting = policy;
        }
        else {
          policyFromInheriting |= policy;
        }
      }
      else if (getOriginalCell(c) == cellIndex && getOriginalSpan(c) == 1 && !(child instanceof Spacer)) {
        nonInheritingComponentsInCell++;
      }
    }
    if (nonInheritingComponentsInCell > 0) {
      return -1;
    }
    return policyFromInheriting;
  }

  public static Container findAlignedChild(final Component child, final GridConstraints c) {
    if (c.isUseParentLayout() && child instanceof Container) {
      Container container = (Container) child;
      if (container.getLayout() instanceof GridLayoutManager) {
        return container;
      }
      else if (container.getComponentCount() == 1 && container.getComponent(0) instanceof Container) {
        // "use parent layout" also needs to work in cases where a grid is the only control in a non-grid panel
        // which is contained in a grid
        Container childContainer = (Container) container.getComponent(0);
        if (childContainer.getLayout() instanceof GridLayoutManager) {
          return childContainer;
        }
      }
    }
    return null;
  }

  protected final Dimension getPreferredSize(final int componentIndex){
    Dimension size = myLayoutState.myPreferredSizes[componentIndex];
    if (size == null) {
      size = Util.getPreferredSize(myLayoutState.getComponent(componentIndex), myLayoutState.getConstraints(componentIndex), true);
      myLayoutState.myPreferredSizes[componentIndex] = size;
    }
    return size;
  }

  protected final Dimension getMinimumSize(final int componentIndex){
    Dimension size = myLayoutState.myMinimumSizes[componentIndex];
    if (size == null) {
      size = Util.getMinimumSize(myLayoutState.getComponent(componentIndex), myLayoutState.getConstraints(componentIndex), true);
      myLayoutState.myMinimumSizes[componentIndex] = size;
    }
    return size;
  }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.solr.search;

import static java.lang.System.nanoTime;

import java.util.concurrent.TimeUnit;
import org.apache.lucene.index.QueryTimeout;
import org.apache.solr.common.params.CommonParams;
import org.apache.solr.request.SolrQueryRequest;

/**
 * Implementation of {@link QueryTimeout} that is used by Solr. It uses a ThreadLocal variable to
 * track the timeoutAt value for each request thread.
 */
public class SolrQueryTimeoutImpl implements QueryTimeout {
  /** The ThreadLocal variable to store the time beyond which, the processing should exit. */
  private static final ThreadLocal<Long> timeoutAt = new ThreadLocal<>();

  private static final SolrQueryTimeoutImpl instance = new SolrQueryTimeoutImpl();

  private SolrQueryTimeoutImpl() {}

  /** Return singleton instance */
  public static SolrQueryTimeoutImpl getInstance() {
    return instance;
  }

  /** The time (nanoseconds) at which the request should be considered timed out. */
  public static Long getTimeoutAtNs() {
    return timeoutAt.get();
  }

  @Override
  public boolean isTimeoutEnabled() {
    return getTimeoutAtNs() != null;
  }

  /** Return true if a timeoutAt value is set and the current time has exceeded the set timeOut. */
  @Override
  public boolean shouldExit() {
    Long timeoutAt = getTimeoutAtNs();
    if (timeoutAt == null) {
      // timeout unset
      return false;
    }
    return timeoutAt - nanoTime() < 0L;
  }

  /**
   * Sets or clears the time allowed based on how much time remains from the start of the request
   * plus the configured {@link CommonParams#TIME_ALLOWED}.
   */
  public static void set(SolrQueryRequest req) {
    long timeAllowed = req.getParams().getLong(CommonParams.TIME_ALLOWED, -1L);
    if (timeAllowed >= 0L) {
      set(timeAllowed - (long) req.getRequestTimer().getTime()); // reduce by time already spent
    } else {
      reset();
    }
  }

  /**
   * Sets the time allowed (milliseconds), assuming we start a timer immediately. You should
   * probably invoke {@link #set(SolrQueryRequest)} instead.
   */
  public static void set(long timeAllowed) {
    long time = nanoTime() + TimeUnit.NANOSECONDS.convert(timeAllowed, TimeUnit.MILLISECONDS);
    timeoutAt.set(time);
  }

  /** Cleanup the ThreadLocal timeout value. */
  public static void reset() {
    timeoutAt.remove();
  }

  @Override
  public String toString() {
    return "timeoutAt: " + getTimeoutAtNs() + " (System.nanoTime(): " + nanoTime() + ")";
  }
}


text:
import React from "react";
import useGoogleAnalyticsPageViewTracker from "../../hooks/useGoogleAnalyticsPageViewTracker";

const GoogleAnalyticsPageViewTracker = () => {
	useGoogleAnalyticsPageViewTracker();
	return null;
};

export default GoogleAnalyticsPageViewTracker;


text:
class Surplusmeter < Cask
  url 'http://www.skoobysoft.com/downloads/SurplusMeterv203.dmg'
  homepage 'http://www.skoobysoft.com/utilities/utilities.html#surplusmeter'
  version '2.0.3'
  sha1 '737fea8d51f1879f85ba65d4081808e023234445'
  link 'SurplusMeter.app'
end


text:
  -- Replace the block with entered character; delete the block contents on pressing Del or BS.
  -- This option works for vertical blocks with width >= 2.
local OptReplaceBlock = true

  -- Use Alt codes e.g. Alt+64 --> @. (This feature is still experimental).
local OptUseAltCodes = false

  -- Reset selection on cursor key moves (only with non-persistent blocks)
local OptCursorMoveResetsBlock = true

-- END OF OPTIONS ----------------------------------------------------------------------------------

local F = far.Flags
local band = (bit or bit64).band
local CharMap = {Space=" ", ShiftSpace=" ", Tab="\t",     BackSlash="\\",
                 Add="+",   Subtract="-",   Multiply="*", Divide="/",     Decimal="."}
local KeyMap = {Num2="Down", Num4="Left", Num6="Right", Num8="Up", NumDel="Del", ShiftIns="CtrlV", ShiftNum0="CtrlV"}

Event {
  group="EditorInput";
  action=function(Rec)
    if Rec.EventType ~= F.KEY_EVENT then return false end

    local EI = editor.GetInfo()
    if not (EI and EI.BlockType==F.BTYPE_COLUMN and band(EI.CurState,F.ECSTATE_LOCKED)==0) then return false end

    local uc = Rec.UnicodeChar
    local altchar = OptUseAltCodes and not Rec.KeyDown and Rec.VirtualKeyCode==18 and uc~="" and uc~="\0" and uc
    local key = not altchar and far.InputRecordToName(Rec)
    key = KeyMap[key] or key

    if OptCursorMoveResetsBlock and band(EI.Options,F.EOPT_PERSISTENTBLOCKS)==0 then
      if key=="Left" or key=="Right" or key=="Up" or Key=="Down" then return false end
    end

    if not (altchar or key=="CtrlV" or (Rec.KeyDown and band(Rec.ControlKeyState,0x0F)==0)) then return false end
    local cur = editor.GetString()
    local BlockWidth = cur and cur.SelStart>0 and cur.SelEnd-cur.SelStart+1
    if not (BlockWidth and (OptReplaceBlock or BlockWidth<=1)) then return false end

    local char = altchar or key and (CharMap[key] or key:match("^.$"))
    local text = char
    if key=="CtrlV" then
      local clip = far.PasteFromClipboard()
      text = clip and clip:match("^([^\r\n]*)\r?\n?$")
      if not text then return false end
    end
    local textlen = text and text:len() or 0

    local delblock = OptReplaceBlock and BlockWidth>1
    if delblock and not (text or key=="Del" or key=="BS") then return false end

    if not (text or key=="Del" or key=="BS" or key=="Left" or key=="Right" or key=="Up" or key=="Down") then return false end

    if (key=="BS" or key=="Left") and EI.CurPos==1 then return true end

    if key=="Up" then
      if EI.CurLine==1 then return true end
      if EI.CurLine==EI.BlockStartLine then return false end
    elseif key=="Down" then
      if EI.CurLine==EI.TotalLines then return true end
      local line = editor.GetString(nil,EI.CurLine+1)
      if not line or line.SelStart <= 0 then return false end
    end

    local lnum = EI.BlockStartLine
    local clean = true
    local BlockStartRealPos, BlockStartTabPos
    while true do
      local line = editor.GetString(nil,lnum)
      if not line or line.SelStart <= 0 then break end
      BlockStartRealPos = BlockStartRealPos or line.SelStart
      BlockStartTabPos = BlockStartTabPos or editor.RealToTab(nil,lnum,BlockStartRealPos)
      local pos = editor.TabToReal(nil,lnum,EI.CurTabPos)
      local s, len, newS = line.StringText, line.StringLength, nil
      if delblock then
        if key == "Del" or key == "BS" then
          if line.SelStart <= len then newS = s:sub(1,line.SelStart-1)..s:sub(line.SelEnd+1) end
        elseif text then
          if line.SelStart > len+1 then newS = s..(" "):rep(line.SelStart-len-1)..text
          else newS = s:sub(1,line.SelStart-1)..text..s:sub(line.SelEnd+1)
          end
        end
      else
        if key == "Del" then
          if pos <= len then newS = s:sub(1,pos-1)..s:sub(pos+1) end
        elseif key == "BS" then
          if pos <= len+1 then newS = s:sub(1,pos-2)..s:sub(pos) end
        elseif text then
          if pos > len+1 then newS = s..(" "):rep(pos-len-1)..text
          else newS = s:sub(1,pos-1)..text..s:sub(pos+(EI.Overtype~=0 and textlen or 0))
          end
        end
      end
      if newS then
        if clean then editor.UndoRedo(nil,F.EUR_BEGIN); clean=false; end
        editor.SetString(nil, lnum, newS)
      end
      lnum = lnum + 1
    end
    if not clean then editor.UndoRedo(nil,F.EUR_END) end

    local textlen = text and text:len() or 0
    local realX, tabX, newY
    if delblock then
      realX = BlockStartRealPos + textlen
      tabX = BlockStartTabPos + textlen
      newY = EI.CurLine
    else
      realX = math.max(1, EI.CurPos + ((key=="Right") and 1 or (key=="BS" or key=="Left") and -1 or textlen))
      tabX = editor.RealToTab(nil, EI.CurLine, realX)
      newY = math.max(1, EI.CurLine + (key=="Up" and -1 or key=="Down" and 1 or 0))
    end
    editor.SetPosition(nil, newY, realX)
    editor.Select(nil, "BTYPE_COLUMN", EI.BlockStartLine, tabX, 1, lnum-EI.BlockStartLine)
    editor.Redraw()
    return true
  end;
}


text:
using System;
using System.Collections.Generic;
using System.Drawing;

namespace MeshRenderer.Core
{
    public class ColorManager
    {
        // Change or add as many colors as you like...
        private static Color[] regionColors = {
            Color.FromArgb(20,   0, 255,   0),
            Color.FromArgb(20, 255, 255,   0),
            Color.FromArgb(20, 255,   0,   0),
            Color.FromArgb(20,   0,   0, 255)
        };

        /// <summary>
        /// Gets a color scheme with black background.
        /// </summary>
        public static ColorManager Default()
        {
            var colors = new ColorManager();

            colors.Background = Color.FromArgb(0, 0, 0);
            colors.Point = new SolidBrush(Color.Green);
            colors.SteinerPoint = new SolidBrush(Color.Peru);
            colors.Triangle = new SolidBrush(Color.Black);
            colors.Line = new Pen(Color.FromArgb(30, 30, 30));
            colors.Segment = new Pen(Color.DarkBlue);
            colors.VoronoiLine = new Pen(Color.FromArgb(40, 50, 60));

            return colors;
        }

        /// <summary>
        /// Gets a color scheme with white background.
        /// </summary>
        public static ColorManager LightScheme()
        {
            var colors = new ColorManager();

            colors.Background = Color.White;
            colors.Point = new SolidBrush(Color.FromArgb(60, 80, 120));
            colors.SteinerPoint = new SolidBrush(Color.DarkGreen);
            colors.Triangle = new SolidBrush(Color.FromArgb(230, 240, 250));
            colors.Line = new Pen(Color.FromArgb(150, 150, 150));
            colors.Segment = new Pen(Color.SteelBlue);
            colors.VoronoiLine = new Pen(Color.FromArgb(160, 170, 180));

            return colors;
        }

        internal Color background;
        internal SolidBrush point;
        internal SolidBrush steinerPoint;
        internal SolidBrush triangle;
        internal Pen line;
        internal Pen segment;
        internal Pen voronoiLine;

        internal SolidBrush[] regions;
        internal Dictionary<int, int> regionMap;

        #region Public methods

        /// <summary>
        /// Setup a region map.
        /// </summary>
        /// <param name="partition">Mesh partition (size = number of triangles in mesh)</param>
        /// <param name="size">Number of partitions / regions.</param>
        public void MakeRegionMap(int[] partition, int size)
        {
            if (regions == null || regions.Length != size)
            {
                int n = regionColors.Length;

                regions = new SolidBrush[size];

                for (int j = 0; j < size; j++)
                {
                    regions[j] = new SolidBrush(regionColors[j % n]);
                }
            }

            if (regionMap == null)
            {
                regionMap = new Dictionary<int, int>(size);
            }
            else
            {
                regionMap.Clear();
            }

            int k = 0;
            for (int i = 0; i < partition.Length; i++)
            {
                if (!regionMap.ContainsKey(partition[i]))
                {
                    regionMap.Add(partition[i], k++);
                }
            }
        }

        /// <summary>
        /// Get the color defined for given region.
        /// </summary>
        public Brush GetRegionBrush(int region)
        {
            if (regionMap == null)
            {
                return triangle;
            }

            int k;
            if (regionMap.TryGetValue(region, out k))
            {
                return regions[k];
            }

            return triangle;
        }

        #endregion

        #region Public properties

        public Color Background
        {
            get { return background; }
            set { background = value; }
        }

        public SolidBrush Point
        {
            get { return point; }
            set
            {
                if (point != null) point.Dispose();
                point = value;
            }
        }

        public SolidBrush SteinerPoint
        {
            get { return steinerPoint; }
            set
            {
                if (steinerPoint != null) steinerPoint.Dispose();
                steinerPoint = value;
            }
        }

        public SolidBrush Triangle
        {
            get { return triangle; }
            set
            {
                if (triangle != null) triangle.Dispose();
                triangle = value;
            }
        }

        public Pen Line
        {
            get { return line; }
            set
            {
                if (line != null) line.Dispose();
                line = value;
            }
        }

        public Pen Segment
        {
            get { return segment; }
            set
            {
                if (segment != null) segment.Dispose();
                segment = value;
            }
        }

        public Pen VoronoiLine
        {
            get { return voronoiLine; }
            set
            {
                if (voronoiLine != null) voronoiLine.Dispose();
                voronoiLine = value;
            }
        }

        #endregion
    }
}


text:
package org.elasticsearch.script.mustache;

import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.action.RestToXContentListener;
import org.elasticsearch.rest.action.search.RestMultiSearchAction;
import org.elasticsearch.rest.action.search.RestSearchAction;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.POST;

public class RestMultiSearchTemplateAction extends BaseRestHandler {

    private static final Set<String> RESPONSE_PARAMS;

    static {
        final Set<String> responseParams = new HashSet<>(
            Arrays.asList(RestSearchAction.TYPED_KEYS_PARAM, RestSearchAction.TOTAL_HIT_AS_INT_PARAM)
        );
        RESPONSE_PARAMS = Collections.unmodifiableSet(responseParams);
    }

    private final boolean allowExplicitIndex;

    public RestMultiSearchTemplateAction(Settings settings, RestController controller) {
        super(settings);
        this.allowExplicitIndex = MULTI_ALLOW_EXPLICIT_INDEX.get(settings);

        controller.registerHandler(GET, "/_msearch/template", this);
        controller.registerHandler(POST, "/_msearch/template", this);
        controller.registerHandler(GET, "/{index}/_msearch/template", this);
        controller.registerHandler(POST, "/{index}/_msearch/template", this);
        controller.registerHandler(GET, "/{index}/{type}/_msearch/template", this);
        controller.registerHandler(POST, "/{index}/{type}/_msearch/template", this);
    }

    @Override
    public String getName() {
        return "multi_search_template_action";
    }

    @Override
    public RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException {
        MultiSearchTemplateRequest multiRequest = parseRequest(request, allowExplicitIndex);
        return channel -> client.execute(MultiSearchTemplateAction.INSTANCE, multiRequest, new RestToXContentListener<>(channel));
    }

    /**
     * Parses a {@link RestRequest} body and returns a {@link MultiSearchTemplateRequest}
     */
    public static MultiSearchTemplateRequest parseRequest(RestRequest restRequest, boolean allowExplicitIndex) throws IOException {
        MultiSearchTemplateRequest multiRequest = new MultiSearchTemplateRequest();
        if (restRequest.hasParam("max_concurrent_searches")) {
            multiRequest.maxConcurrentSearchRequests(restRequest.paramAsInt("max_concurrent_searches", 0));
        }

        RestMultiSearchAction.parseMultiLineRequest(restRequest, multiRequest.indicesOptions(), allowExplicitIndex,
                (searchRequest, bytes) -> {
                    SearchTemplateRequest searchTemplateRequest = SearchTemplateRequest.fromXContent(bytes);
                    if (searchTemplateRequest.getScript() != null) {
                        searchTemplateRequest.setRequest(searchRequest);
                        multiRequest.add(searchTemplateRequest);
                    } else {
                        throw new IllegalArgumentException("Malformed search template");
                    }
                });
        return multiRequest;
    }

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

    @Override
    protected Set<String> responseParams() {
        return RESPONSE_PARAMS;
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Where In Queens</title>
    <meta name="viewport" content="width=device-width">
    <meta name="description" content="Queens, NY website that connects homeless and low-income residents with critical and life-saving resources" />
    <link rel="stylesheet" href="{{linksf_css}}">

      Feedback
      About


text:
package org.culturegraph.mf.stream.converter;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.culturegraph.mf.framework.StreamReceiver;
import org.culturegraph.mf.stream.converter.PojoDecoder.MetafactureSource;
import org.culturegraph.mf.stream.sink.EventList;
import org.culturegraph.mf.stream.sink.StreamValidator;
import org.junit.Test;

/**
 * Tests for {@link PojoDecoder}
 *
 * @author Thomas Seidel
 *
 */
public class PojoDecoderTest {

	private final static String firstFieldName = "firstField";
	private final static String secondFieldName = "secondField";
	private final static String firstFieldValue = "firstValue";
	private final static String secondFieldValue = "secondValue";

	private final static String innerPojoName = "innerPojo";

	private final static String metafactureSourceField = "metafactureSourceField";
	private final static String metafactureSourceName = "metafactureSourceName";
	private final static String metafactureSourceValue = "metafactureSourceValue";

	private final static String listFieldName = "listField";
	private final static String firstListFieldValue = "firstListFieldValue";
	private final static String secondListFieldValue = "secondListFieldValue";
	private final static String setFieldName = "setField";
	private final static String firstSetFieldValue = "firstSetFieldValue";
	private final static String secondSetFieldValue = "secondSetFieldValue";
	private final static String arrayFieldName = "arrayField";
	private final static String firstArrayFieldValue = "firstArrayFieldValue";
	private final static String secondArrayFieldValue = "secondArrayFieldValue";

	private final static String mapFieldName = "mapField";
	private final static String firstMapFieldKey = "fistMapFieldKey";
	private final static String firstdMapFieldValue = "fistMapFieldValue";
	private final static String secondMapFieldKey = "secondMapFieldKey";
	private final static String secondMapFieldValue = "secondMapFieldKey";

	private static class EmptyPojo {
	}

	// Suppress warnings for unused fields or getters. The ObjectDecoder uses
	// them to access the values.
	private static class SimplePojo {
		private String firstField;
		@SuppressWarnings("unused")
		public String secondField;

		@SuppressWarnings("unused")
		public String getFirstField() {
			return firstField;
		}

		public void setFirstField(final String firstField) {
			this.firstField = firstField;
		}

	}

	// Suppress warnings for unused fields or getters. The ObjectDecoder uses
	// them to access the values.
	private static class NestedPojo {
		private SimplePojo innerPojo;

		@SuppressWarnings("unused")
		public SimplePojo getInnerPojo() {
			return innerPojo;
		}

		public final void setInnerPojo(final SimplePojo innerPojo) {
			this.innerPojo = innerPojo;
		}
	}

	// Suppress warnings for unused fields or getters. The ObjectDecoder uses
	// them to access the values.
	private static class NestedMetafactureSourcePojo {
		private MetafactureSource metafactureSourceField;

		@SuppressWarnings("unused")
		public MetafactureSource getMetafactureSourceField() {
			return metafactureSourceField;
		}

		public void setMetafactureSourceField(
				final MetafactureSource metafactureSourceField) {
			this.metafactureSourceField = metafactureSourceField;
		}

	}

	// Suppress warnings for unused fields or getters. The ObjectDecoder uses
	// them to access the values.
	private static class SimpleCollectionAndArrayPojo {
		private List<String> listField;
		private Set<String> setField;
		private String[] arrayField;
		private String firstField;

		@SuppressWarnings("unused")
		public List<String> getListField() {
			return listField;
		}

		public void setListField(final List<String> listField) {
			this.listField = listField;
		}

		@SuppressWarnings("unused")
		public Set<String> getSetField() {
			return setField;
		}

		public void setSetField(final Set<String> setField) {
			this.setField = setField;
		}

		@SuppressWarnings("unused")
		public String[] getArrayField() {
			return arrayField;
		}

		public void setArrayField(final String[] arrayField) {
			this.arrayField = arrayField;
		}

		@SuppressWarnings("unused")
		public String getFirstField() {
			return firstField;
		}

		public void setFirstField(final String firstField) {
			this.firstField = firstField;
		}

	}

	private static class SimpleMapPojo {
		private Map<String, String> mapField;

		@SuppressWarnings("unused")
		public Map<String, String> getMapField() {
			return mapField;
		}

		public void setMapField(final Map<String, String> mapField) {
			this.mapField = mapField;
		}
	}

	@Test
	public void shouldDecodeNullObject() {
		// create validator
		final EventList expected = new EventList();
		final StreamValidator validator = new StreamValidator(
				expected.getEvents());
		// decode null pojo and verify result
		final PojoDecoder<Object> pojoDecoder = new PojoDecoder<Object>();
		pojoDecoder.setReceiver(validator);
		pojoDecoder.process(null);
	}

	@Test
	public void shouldDecodeEmptyPojo() {
		// create pojo
		final EmptyPojo emptyPojo = new EmptyPojo();
		// create validator
		final EventList expected = new EventList();
		expected.startRecord("");
		expected.endRecord();
		final StreamValidator validator = new StreamValidator(
				expected.getEvents());
		// decode pojo and verify result
		final PojoDecoder<EmptyPojo> pojoDecoder = new PojoDecoder<EmptyPojo>();
		pojoDecoder.setReceiver(validator);
		pojoDecoder.process(emptyPojo);
	}

	@Test
	public void shouldDecodeSimplePojo() {
		// create pojo
		final SimplePojo simplePojo = new SimplePojo();
		simplePojo.setFirstField(firstFieldValue);
		simplePojo.secondField = secondFieldValue;
		// create validator
		final EventList expected = new EventList();
		expected.startRecord("");
		expected.literal(firstFieldName, firstFieldValue);
		expected.literal(secondFieldName, secondFieldValue);
		expected.endRecord();
		final StreamValidator validator = new StreamValidator(
				expected.getEvents());
		// decode pojo and verify result
		final PojoDecoder<SimplePojo> pojoDecoder = new PojoDecoder<SimplePojo>();
		pojoDecoder.setReceiver(validator);
		pojoDecoder.process(simplePojo);
	}

	@Test
	public void shouldDecodeNestedPojo() {
		// create pojo
		final SimplePojo simplePojo = new SimplePojo();
		simplePojo.setFirstField(firstFieldValue);
		simplePojo.secondField = secondFieldValue;
		final NestedPojo nestedPojo = new NestedPojo();
		nestedPojo.setInnerPojo(simplePojo);
		// create validator
		final EventList expected = new EventList();
		expected.startRecord("");
		expected.startEntity(innerPojoName);
		expected.literal(firstFieldName, firstFieldValue);
		expected.literal(secondFieldName, secondFieldValue);
		expected.endEntity();
		expected.endRecord();
		final StreamValidator validator = new StreamValidator(
				expected.getEvents());
		// decode pojo and verify result
		final PojoDecoder<NestedPojo> pojoDecoder = new PojoDecoder<NestedPojo>();
		pojoDecoder.setReceiver(validator);
		pojoDecoder.process(nestedPojo);
	}

	@Test
	public void shouldDecodePojoWithMetafactureSource() {
		// create pojo
		final MetafactureSource metafactureSource = new MetafactureSource() {
			@Override
			public void sendToStream(final StreamReceiver streamReceiver) {
				streamReceiver.literal(metafactureSourceName,
						metafactureSourceValue);
			}
		};
		final NestedMetafactureSourcePojo nestedMetafactureSourcePojo = new NestedMetafactureSourcePojo();
		nestedMetafactureSourcePojo
				.setMetafactureSourceField(metafactureSource);
		// create validator
		final EventList expected = new EventList();
		expected.startRecord("");
		expected.startEntity(metafactureSourceField);
		expected.literal(metafactureSourceName, metafactureSourceValue);
		expected.endEntity();
		expected.endRecord();
		final StreamValidator validator = new StreamValidator(
				expected.getEvents());
		// decode pojo and verify result
		final PojoDecoder<NestedMetafactureSourcePojo> pojoDecoder = new PojoDecoder<NestedMetafactureSourcePojo>();
		pojoDecoder.setReceiver(validator);
		pojoDecoder.process(nestedMetafactureSourcePojo);
	}

	@Test
	public void shouldDecodeSimpleCollectionAndArrayPojo() {
		// create pojo
		final List<String> listField = Arrays.asList(firstListFieldValue,
				secondListFieldValue);
		final Set<String> setField = new HashSet<String>(Arrays.asList(
				firstSetFieldValue, secondSetFieldValue));
		final String[] arrayField = { firstArrayFieldValue,
				secondArrayFieldValue };
		final SimpleCollectionAndArrayPojo simpleCollectionAndArrayPojo = new SimpleCollectionAndArrayPojo();
		simpleCollectionAndArrayPojo.setListField(listField);
		simpleCollectionAndArrayPojo.setSetField(setField);
		simpleCollectionAndArrayPojo.setArrayField(arrayField);
		simpleCollectionAndArrayPojo.setFirstField(firstFieldValue);
		// create validator
		final EventList expected = new EventList();
		expected.startRecord("");
		expected.literal(listFieldName, firstListFieldValue);
		expected.literal(listFieldName, secondListFieldValue);
		expected.literal(setFieldName, firstSetFieldValue);
		expected.literal(setFieldName, secondSetFieldValue);
		expected.literal(arrayFieldName, firstArrayFieldValue);
		expected.literal(arrayFieldName, secondArrayFieldValue);
		expected.literal(firstFieldName, firstFieldValue);
		expected.endRecord();
		final StreamValidator validator = new StreamValidator(
				expected.getEvents());
		// decode pojo and verify result
		final PojoDecoder<SimpleCollectionAndArrayPojo> pojoDecoder = new PojoDecoder<SimpleCollectionAndArrayPojo>();
		pojoDecoder.setReceiver(validator);
		pojoDecoder.process(simpleCollectionAndArrayPojo);
	}

	@Test
	public void shouldDecodeSimpleMapPojo() {
		// create pojo
		final Map<String, String> mapField = new HashMap<String, String>();
		mapField.put(firstMapFieldKey, firstdMapFieldValue);
		mapField.put(secondMapFieldKey, secondMapFieldValue);
		final SimpleMapPojo simpleMapPojo = new SimpleMapPojo();
		simpleMapPojo.setMapField(mapField);
		// create validator
		final EventList expected = new EventList();
		expected.startRecord("");
		expected.startEntity(mapFieldName);
		expected.literal(firstMapFieldKey, firstdMapFieldValue);
		expected.literal(secondMapFieldKey, secondMapFieldValue);
		expected.endEntity();
		expected.endRecord();
		final StreamValidator validator = new StreamValidator(
				expected.getEvents());
		// decode pojo and verify result
		final PojoDecoder<SimpleMapPojo> pojoDecoder = new PojoDecoder<SimpleMapPojo>();
		pojoDecoder.setReceiver(validator);
		pojoDecoder.process(simpleMapPojo);
	}
}


text: Footprint of my mathematic lessons


text:
#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include "cmockery.h"

/* Define UNIT_TESTING so that the extension can skip declaring PG_MODULE_MAGIC */
#define UNIT_TESTING

/* include unit under test */
#include "../src/libchurl.c"

/* include mock files */
#include "mock/curl_mock.c"

/* test strings */
const char *uri_param = "pxf://localhost:51200/tmp/dummy1";
const char *read_string = "Hello World!\0";

void
test_set_curl_option(void **state)
{
	/* set up context with a curl_handle */
	churl_context *context = palloc0(sizeof(churl_context));

	context->curl_handle = (CURL *) palloc0(sizeof(CURL));

	/* set mock behavior for curl_easy_setopt */
	expect_value(curl_easy_setopt, curl, context->curl_handle);
	expect_value(curl_easy_setopt, option, CURLOPT_URL);
	will_return(curl_easy_setopt, CURLE_OK);

	set_curl_option(context, CURLOPT_URL, uri_param);

	/* cleanup */
	pfree(context->curl_handle);
	pfree(context);
}

void
curl_easy_setopt_test_helper(CURL * curl_handle, CURLoption in_option)
{
	expect_value(curl_easy_setopt, curl, curl_handle);
	expect_value(curl_easy_setopt, option, in_option);
	will_return(curl_easy_setopt, CURLE_OK);
}

void
curl_slist_append_test_helper(struct curl_slist *slist, char *header_string)
{
	expect_any(curl_slist_append, list);
	expect_string(curl_slist_append, string, header_string);
	will_return(curl_slist_append, slist);
}

void
test_churl_init_upload(void **state)
{
	CHURL_HEADERS headers = palloc0(sizeof(CHURL_HEADERS));

	/* set mock behavior for curl handle initialization */
	CURL	   *mock_curl_handle = palloc0(sizeof(CURL));

	will_return(curl_easy_init, mock_curl_handle);

	/* set mock behavior for all the set_curl_option calls */

	curl_slist_append_test_helper(NULL, "localhost:51200:127.0.0.1");

	/* set mock behavior for all the curl_easy_setopt calls */
	curl_easy_setopt_test_helper(mock_curl_handle, CURLOPT_RESOLVE);
	curl_easy_setopt_test_helper(mock_curl_handle, CURLOPT_URL);
	curl_easy_setopt_test_helper(mock_curl_handle, CURLOPT_VERBOSE);
	curl_easy_setopt_test_helper(mock_curl_handle, CURLOPT_ERRORBUFFER);
	curl_easy_setopt_test_helper(mock_curl_handle, CURLOPT_IPRESOLVE);
	curl_easy_setopt_test_helper(mock_curl_handle, CURLOPT_WRITEFUNCTION);
	curl_easy_setopt_test_helper(mock_curl_handle, CURLOPT_WRITEDATA);
	curl_easy_setopt_test_helper(mock_curl_handle, CURLOPT_HEADERFUNCTION);
	curl_easy_setopt_test_helper(mock_curl_handle, CURLOPT_HEADERDATA);
	curl_easy_setopt_test_helper(mock_curl_handle, CURLOPT_HTTPHEADER);
	curl_easy_setopt_test_helper(mock_curl_handle, CURLOPT_POST);
	curl_easy_setopt_test_helper(mock_curl_handle, CURLOPT_READFUNCTION);
	curl_easy_setopt_test_helper(mock_curl_handle, CURLOPT_READDATA);

	struct curl_slist *mock_curl_slist = palloc0(sizeof(struct curl_slist));

	curl_slist_append_test_helper(mock_curl_slist, "Content-Type: application/octet-stream");
	curl_slist_append_test_helper(mock_curl_slist, "Transfer-Encoding: chunked");
	curl_slist_append_test_helper(mock_curl_slist, "Expect: 100-continue");

	/* setup_multi_handle mock setup */

	CURLM	   *mock_multi_handle = palloc0(sizeof(CURLM));

	will_return(curl_multi_init, mock_multi_handle);

	expect_value(curl_multi_add_handle, multi_handle, mock_multi_handle);
	expect_value(curl_multi_add_handle, curl_handle, mock_curl_handle);
	will_return(curl_multi_add_handle, CURLM_OK);

	expect_value(curl_multi_perform, multi_handle, mock_multi_handle);
	expect_any(curl_multi_perform, running_handles);
	will_return(curl_multi_perform, CURLM_OK);

	CHURL_HANDLE handle = churl_init_upload(uri_param, headers);

	churl_context *context = (churl_context *) handle;

	assert_true(context->upload == true);
	assert_true(context->curl_error_buffer[0] == 0);
	assert_true(context->download_buffer != NULL);
	assert_true(context->upload_buffer != NULL);
	assert_true(context->curl_handle != NULL);
	assert_true(context->multi_handle != NULL);
	assert_true(context->last_http_reponse == NULL);
	assert_true(context->curl_still_running == 0);

	/* tear down */
	pfree(headers);
	pfree(handle);
}

void
test_churl_init_download(void **state)
{
	CHURL_HEADERS headers = palloc0(sizeof(CHURL_HEADERS));

	/* set mock behavior for curl handle initialization */
	CURL	   *mock_curl_handle = palloc0(sizeof(CURL));

	will_return(curl_easy_init, mock_curl_handle);

	/* set mock behavior for all the set_curl_option calls */

	curl_slist_append_test_helper(NULL, "localhost:51200:127.0.0.1");

	/* set mock behavior for all the curl_easy_setopt calls */
	curl_easy_setopt_test_helper(mock_curl_handle, CURLOPT_RESOLVE);
	curl_easy_setopt_test_helper(mock_curl_handle, CURLOPT_URL);
	curl_easy_setopt_test_helper(mock_curl_handle, CURLOPT_VERBOSE);
	curl_easy_setopt_test_helper(mock_curl_handle, CURLOPT_ERRORBUFFER);
	curl_easy_setopt_test_helper(mock_curl_handle, CURLOPT_IPRESOLVE);
	curl_easy_setopt_test_helper(mock_curl_handle, CURLOPT_WRITEFUNCTION);
	curl_easy_setopt_test_helper(mock_curl_handle, CURLOPT_WRITEDATA);
	curl_easy_setopt_test_helper(mock_curl_handle, CURLOPT_HEADERFUNCTION);
	curl_easy_setopt_test_helper(mock_curl_handle, CURLOPT_HEADERDATA);
	curl_easy_setopt_test_helper(mock_curl_handle, CURLOPT_HTTPHEADER);

	/* setup_multi_handle mock setup */

	CURLM	   *mock_multi_handle = palloc0(sizeof(CURLM));

	will_return(curl_multi_init, mock_multi_handle);

	expect_value(curl_multi_add_handle, multi_handle, mock_multi_handle);
	expect_value(curl_multi_add_handle, curl_handle, mock_curl_handle);
	will_return(curl_multi_add_handle, CURLM_OK);

	expect_value(curl_multi_perform, multi_handle, mock_multi_handle);
	expect_any(curl_multi_perform, running_handles);
	will_return(curl_multi_perform, CURLM_OK);

	/* function call */

	CHURL_HANDLE handle = churl_init_download(uri_param, headers);

	churl_context *context = (churl_context *) handle;

	/* test assertions */
	assert_true(context->upload == false);
	assert_true(context->curl_error_buffer[0] == 0);
	assert_true(context->download_buffer != NULL);
	assert_true(context->upload_buffer != NULL);
	assert_true(context->curl_handle != NULL);
	assert_true(context->multi_handle != NULL);
	assert_true(context->last_http_reponse == NULL);

	/* tear down */
	pfree(headers);
	pfree(handle);
}

/*  wrapper function to enable sideeffect testing with multiple parameters */
void
write_callback_wrapper(churl_context * user_context)
{
	write_callback(read_string, sizeof(char), strlen(read_string) + 1, user_context);
}

void
test_churl_read(void **state)
{

	int			READ_LEN = 32;

	;
	/* context setup */
	CHURL_HANDLE handle = palloc0(sizeof(CHURL_HANDLE));
	churl_context *context = (churl_context *) handle;
	CURLM	   *mock_multi_handle = palloc0(sizeof(CURLM));

	context->download_buffer = palloc0(sizeof(churl_buffer));

	context->multi_handle = mock_multi_handle;
	context->curl_still_running = 1;
	context->upload = 0;
	context->download_buffer->top = 0;
	context->download_buffer->bot = 0;
	context->download_buffer->ptr = palloc0(sizeof(READ_LEN));
	context->download_buffer->max = READ_LEN;

	/* buffer to read into */
	char		buf[READ_LEN];

	/* mock behavior setup */

	/* set up curl_multi_fdset mock behavior */
	expect_value(curl_multi_fdset, multi_handle, mock_multi_handle);
	expect_any(curl_multi_fdset, read_fd_set);
	expect_any(curl_multi_fdset, write_fd_set);
	expect_any(curl_multi_fdset, exc_fd_set);
	expect_any(curl_multi_fdset, max_fd);
	will_assign_value(curl_multi_fdset, max_fd, 1);
	will_return(curl_multi_fdset, CURLM_OK);

	/* set up select mock behavior */
	expect_value(select, nfds, 2);
	expect_any(select, read_fds);
	expect_any(select, write_fds);
	expect_any(select, except_fds);
	expect_any(select, timeout);
	will_return(select, 1);

	/* set up curl_multi_perform mock behavior */
	/* this function invokes callback functions which are handled by */
	/* write_callback_wrapper */
	expect_value(curl_multi_perform, multi_handle, mock_multi_handle);
	expect_any(curl_multi_perform, running_handles);
	will_assign_value(curl_multi_perform, running_handles, 0);
	will_return_with_sideeffect(curl_multi_perform, CURLM_OK, write_callback_wrapper, context);

	/* function call */
	size_t		buffer_offset = churl_read(handle, buf, 32);

	/* test assertions */
	assert_true(context->curl_still_running == 0);
	assert_true(strcmp(buf, read_string) == 0);
	assert_true(buffer_offset == 13);
	assert_true(context->download_buffer->bot == 13);
	assert_true(context->download_buffer->bot == context->download_buffer->top);
}

int
main(int argc, char *argv[])
{
	cmockery_parse_arguments(argc, argv);

	const		UnitTest tests[] = {
		unit_test(test_set_curl_option),
		unit_test(test_churl_init_upload),
		unit_test(test_churl_init_download),
		unit_test(test_churl_read)
	};

	MemoryContextInit();

	return run_tests(tests);
}


text:
<?php
namespace WScore\Repository\Relations;

use WScore\Repository\Assembly\Collection;
use WScore\Repository\Entity\EntityInterface;
use WScore\Repository\Helpers\HelperMethods;
use WScore\Repository\Query\QueryInterface;
use WScore\Repository\Repository\RepositoryInterface;

abstract class AbstractRelation implements RelationInterface
{
    /**
     * @var RepositoryInterface
     */
    protected $sourceRepo;

    /**
     * @var RepositoryInterface
     */
    protected $targetRepo;

    /**
     * @var EntityInterface[]
     */
    protected $sourceEntities;

    /**
     * @var array
     */
    protected $convert;

    /**
     * @var array
     */
    protected $condition = [];

    /**
     * @return RepositoryInterface
     */
    public function getTargetRepository()
    {
        return $this->targetRepo;
    }

    /**
     * @param RepositoryInterface $repository
     * @return array
     */
    protected function makeConversion(RepositoryInterface $repository)
    {
        $convert = [];
        foreach($repository->getKeyColumns() as $k) {
            $convert[$k] = $k;
        }
        return $convert;
    }

    /**
     * @param EntityInterface[] ...$sourceEntity
     * @return RelationInterface
     */
    public function withEntity(...$sourceEntity)
    {
        $self = clone $this;
        $self->sourceEntities = $sourceEntity;

        return $self;
    }

    /**
     * @param array $key
     * @return $this
     */
    public function setCondition(array $key)
    {
        $this->condition = $key;
        return $this;
    }

    /**
     * @return int
     */
    public function count()
    {
        return $this->query()->count();
    }

    /**
     * @param array $keys
     * @return Collection
     */
    public function collect(array $keys = [])
    {
        $query = $this->query();
        $found = $query ? $query->select($keys)->fetchAll() : [];
        return $this->targetRepo->newCollection($found, $this);
    }

    /**
     * extract keys for querying entity.
     *
     * @param EntityInterface $entity
     * @param $conversion
     * @return array
     */
    protected function extractKeys($entity, $conversion)
    {
        $data = $entity->toArray();
        $keys = HelperMethods::filterDataByKeys($data, array_flip($conversion));
        $keys = HelperMethods::convertDataKeys($keys, $conversion);

        return $keys;
    }

    /**
     * @return QueryInterface
     */
    abstract public function query();
}


text:
String.prototype.replaceAt=function(index, character)
{
	return this.substr(0, index) + character + this.substr(index+character.length);
}

//"Tape class"
function Tape(alphabet, blank, pos, tapeContent)
{
	//data
	this.alphabet= alphabet;
	this.blankSymbol= blank;
	this.pos= pos;
	this.tapeContent= tapeContent;

	this.alphabetCopy= alphabet;
	this.blankSymbolCopy= blank;
	this.posCopy= pos;
	this.tapeContentCopy= tapeContent;

	this.reset = function()
	{
		this.alphabet= this.alphabetCopy;
		this.blankSymbol= this.blankSymbolCopy;
		this.pos= this.posCopy;
		this.tapeContent= this.tapeContentCopy;
	}

	//methods
	this.moveRight= function (){
		var tapeLength= (this.tapeContent).length;
		if(this.pos == tapeLength - 1)
			this.tapeContent= this.tapeContent.concat(this.blankSymbol);
		this.pos= this.pos + 1;

	}
	this.moveLeft= function (){
		if(this.pos == 0)
			this.tapeContent= this.blankSymbol.concat(this.tapeContent);
		else
			this.pos= this.pos - 1;

	}
	//Writes symbol on the tape, at the current position
	this.write= function(Symbol){
		this.tapeContent= this.tapeContent.replaceAt(this.pos, Symbol);
	}
	//returns current position tape contents
	this.read= function(){
		return this.tapeContent.charAt(this.pos);
	}
	//Show Tape
	this.show= function(){
		document.write("Tape Alphabet:
");
		for(var j= 0; j < alphabet.length; j++)
		{

			document.write(j + ": " + alphabet[j] + "; " + "
");
		}
		document.write("Blank Symbol: " + this.blankSymbol + "
" );
		document.write("Current Pos: " + this.pos + "
" );
		document.write("Tape Content: ")
		for(var i= 0; i < tapeContent.length; i++)
		{
			document.write(tapeContent[i]);

		}
		document.write("
");
	}

}

var stepReturn = 2;

var steper = null;

var time = 0;

var timer = null;

var running = false;

//"TuringMachine class"
function TuringMachine(tape, transitionsTable, initialState, finalStates)
{
	this.tape= tape;
	this.transitionsTable= transitionsTable;
	this.initialState= initialState;
	this.finalStates= finalStates;
	this.currentState= initialState;
	this.stepNumber= 0;

	this.tapeCopy= tape;
	this.transitionsTableCopy= transitionsTable;
	this.initialStateCopy= initialState;
	this.finalStatesCopy= finalStates;
	this.currentStateCopy= initialState;

	this.reset = function()
	{
		this.tape= this.tapeCopy;
		this.transitionsTable= this.transitionsTableCopy;
		this.initialState= this.initialStateCopy;
		this.finalStates= this.finalStatesCopy;
		this.currentState= this.currentStateCopy;
		this.stepNumber= 0;

		stepReturn = 2;

		(this.tape).reset();
	}

	this.stop = function()
	{
		clearInterval(steper);

		clearInterval(timer);

		time = 0;

		this.reset();

		running = false;

		document.getElementById("runButton").disabled = false;
		document.getElementById("stopButton").disabled = true;
		document.getElementById("pauseButton").disabled = true;
	}

	this.pause = function()
	{
		clearInterval(steper);

		clearInterval(timer);

		running = false;

		document.getElementById("pauseButton").disabled = true;
		document.getElementById("resumeButton").disabled = false;
	}

	this.resume = function()
	{
		this.run();

		running = true;

		document.getElementById("pauseButton").disabled = false;
		document.getElementById("resumeButton").disabled = true;
	}

	this.step= function(){

		stepReturn = 2;

		var stepResult = document.getElementById('output');

		var stepString= "";
		for(var k= 0; k < (this.tape).tapeContent.length; k++)
		{
			if(k == (this.tape).pos)
				stepString += "" + (this.tape).tapeContent[k] + "";
			else
				stepString += "" + (this.tape).tapeContent[k] + "";
		}
		stepString += "
";

		stepResult.insertAdjacentHTML('beforeend', stepString);

		var i;
		document.getElementById('animation').innerHTML ="";
		var elements = new Array();
		elements = stepString.split("");
		var size = 40;
		var padding = '';
		var anim = true;
		if(elements.length>21 && elements.length<42){
			size = 20;
			padding = "padding-left:5px;padding-bottom:5px;"
		}
		else if(elements.length>42){
			anim = false;
			console.log("anim false");
		}
		if(anim == false){
			document.getElementById('animation').style.fontSize="large";
			document.getElementById('animation').innerHTML="Input too long!";}
		else{
			for(i=0;i<elements.length-1;i++){
				if(elements[i].indexOf("red")> -1)
					document.getElementById('animation').innerHTML += '
' + elements[i] +'
';
				else
					document.getElementById('animation').innerHTML += '
' + elements[i] +'
';

			};
		}
		//obtain symbol on the current tape position
		var currentSymbolOnTape= (this.tape).read();

		var nextState;
		var nextSymbol;
		var nextDirection;

		var transitionFound= false;

		for(var i= 0; i < transitionsTable.length; i++)
		{
			if((transitionsTable[i].currentState == this.currentState) &&  (transitionsTable[i].scanSymbol == currentSymbolOnTape))
			{
				nextState= transitionsTable[i].nextState;
				nextSymbol= transitionsTable[i].printSymbol;
				nextDirection= transitionsTable[i].direction;

				//write on current tape position "nextSymbol"
				(this.tape).write(nextSymbol);

				transitionFound= true;

				break;
			}
		}

		if(transitionFound)
		{
			//update "currentState" after transition
			this.currentState= nextState;

			this.stepNumber += 1;

			$('#nsteps').html(this.stepNumber);

			//check if a final state have been reached.
			for(var j= 0; j < (this.finalStates).length; j++)
			{
				if(finalStates[j] == this.currentState)
				{

					stepString= "" + "Success: finished in a final state!" + "
";
					//stepString+= "" + "Number of steps= " + this.stepNumber + "
";
					stepResult.insertAdjacentHTML('beforeend', stepString);

					colorNode(turingMachine.currentState);

					$('#currentstep').html(this.currentState);

					stepReturn = 1;
				}
			}

			//update tape position after transition
			if(nextDirection == 'R')
			{
				(this.tape).moveRight();
			}
			else if(nextDirection == 'L')
			{
				(this.tape).moveLeft();
			}
		}
		else
		{
			stepString = "" + "Failure: did not finish on a final state! " + "
";
			//stepString+= "" + "Number of steps= " + this.stepNumber + "
";
			stepResult.insertAdjacentHTML('beforeend', stepString);

			colorNode(turingMachine.currentState);

			$('#currentstep').html(this.currentState);

			stepReturn = 0;
		}

		colorNode(turingMachine.currentState);

		$('#currentstep').html(this.currentState);

		if($("#chkBreakpoints").is(":checked"))
		{
			var j = 0;

			while(j < breakpoints.length)
			{
				if(breakpoints[j].type == "state")
				{
					if(breakpoints[j].where.length > 1)
					{
						if(this.currentState == breakpoints[j].where[breakpoints[j].sequencer])
						{
							breakpoints[j].incrementSequencer();
						}
						else
						{
							breakpoints[j].resetSequencer();
						}

						if(breakpoints[j].sequencer == breakpoints[j].where.length)
						{
							breakpoints[j].resetSequencer();

							breakpoints[j].incrementCounter();

							if(breakpoints[j].counter == breakpoints[j].times)
							{
								$('#output').append("Breakpoint!" + " Current State: " + this.currentState + "; Message: " + breakpoints[j].message + "
");

								turingMachine.pause();
							}
						}
					}
					else
					{
						if(this.currentState == breakpoints[j].where)
						{
							breakpoints[j].incrementCounter();

							if(breakpoints[j].counter == breakpoints[j].times)
							{
								$('#output').append("Breakpoint!" + " Current State: " + this.currentState + "; Message: " + breakpoints[j].message + "
");

								turingMachine.pause();
							}
						}
					}
				}
				else
				{
					if(breakpoints[j].type == "inputPosition")
					{
						if(breakpoints[j].where.length > 1)
						{
							if(this.tape.pos == breakpoints[j].where[breakpoints[j].sequencer])
							{
								breakpoints[j].incrementSequencer();
							}
							else
							{
								breakpoints[j].resetSequencer();
							}

							if(breakpoints[j].sequencer == breakpoints[j].where.length)
							{
								breakpoints[j].resetSequencer();

								breakpoints[j].incrementCounter();

								if(breakpoints[j].counter == breakpoints[j].times)
								{
									$('#output').append("Breakpoint!" + " Current State: " + this.currentState + "; Message: " + breakpoints[j].message + "
");

									turingMachine.pause();
								}
							}
						}
						else
						{
							if(this.tape.pos == breakpoints[j].where)
							{
								breakpoints[j].incrementCounter();

								if(breakpoints[j].counter == breakpoints[j].times)
								{
									$('#output').append("Breakpoint!" + " Current Tape Position: " + this.tape.pos + "; Message: " + breakpoints[j].message + "
");

									turingMachine.pause();
								}
							}
						}
					}
				}

				j++;
			}
		}
	}
	this.runNsteps= function(numberOfSteps){
	}
	this.run= function(){

		document.getElementById("runButton").disabled = true;
		document.getElementById("stopButton").disabled = false;
		document.getElementById("pauseButton").disabled = false;

		clearInterval(timer);

		running = true;

		var timeNull = 0;
		var timeWait = 750;
		var timeBetween = 0;
		if($("#chkRealTime").is(":checked")){
			timeBetween = timeNull;
		}
		else{
			timeBetween = timeWait;
		}
		steper = setInterval(function ()
		{
			if (stepReturn != 2)
			{
				clearInterval(steper);
				clearInterval(timer);

				turingMachine.reset();

				document.getElementById("runButton").disabled = false;
				document.getElementById("stopButton").disabled = true;
				document.getElementById("pauseButton").disabled = true;

				running = false;

				time = 0;

				if(currentInput < inputs.length)
				{
					//create Tape
					tape= new Tape(alphabetSet, blankSymbolInput, 0, inputs[currentInput]);

					currentInput++;

					//tape.show();

					//create Turing Machine
					turingMachine= new TuringMachine(tape, data, initialStateInput, finalStates);

					//turingMachine.show();

					turingMachine.run();

					running = true;
				}
				else
				{
					if(currentInput == inputs.length)
					{
						currentInput = 0;

						//create Tape
						tape= new Tape(alphabetSet, blankSymbolInput, 0, inputs[currentInput]);

						currentInput++;

						//tape.show();

						//create Turing Machine
						turingMachine= new TuringMachine(tape, data, initialStateInput, finalStates);

						//turingMachine.show();
					}
				}
			}
			else
			{
				turingMachine.step();
				var elem = document.getElementById('output');
				elem.scrollTop = elem.scrollHeight;
			}
		}, timeBetween);

		timer = setInterval(function ()
		{
			if (stepReturn != 2)
			{

			}
			else
			{
				var timeTemp = time + 0.01;
				time= Math.round(timeTemp*100)/100;
				$('#tsteps').html(time + " s");
			}
		}, 10);
	}

	this.changeSteper = function()
	{
		if(running == true)
		{
			clearInterval(steper);

			var timeNull = 0;
			var timeWait = 750;
			var timeBetween = 0;
			if($("#chkRealTime").is(":checked")){
				timeBetween = timeNull;
			}
			else{
				timeBetween = timeWait;
			}
			steper = setInterval(function ()
			{
				if (stepReturn != 2)
				{
					clearInterval(steper);
					clearInterval(timer);

					turingMachine.reset();

					document.getElementById("runButton").disabled = false;
					document.getElementById("stopButton").disabled = true;
					document.getElementById("pauseButton").disabled = true;

					running = false;

					time = 0;

					if(currentInput < inputs.length)
					{
						//create Tape
						tape= new Tape(alphabetSet, blankSymbolInput, 0, inputs[currentInput]);

						currentInput++;

						//tape.show();

						//create Turing Machine
						turingMachine= new TuringMachine(tape, data, initialStateInput, finalStates);

						//turingMachine.show();

						turingMachine.run();

						running = true;
					}
					else
					{
						if(currentInput == inputs.length)
						{
							currentInput = 0;

							//create Tape
							tape= new Tape(alphabetSet, blankSymbolInput, 0, inputs[currentInput]);

							currentInput++;

							//tape.show();

							//create Turing Machine
							turingMachine= new TuringMachine(tape, data, initialStateInput, finalStates);

							//turingMachine.show();
						}
					}
				}
				else
				{
					turingMachine.step();
					var elem = document.getElementById('output');
					elem.scrollTop = elem.scrollHeight;
				}
			}, timeBetween);
		}
	}

	this.show= function(){
		document.write("tape...
");
		document.write("Initial State= " + this.initialState + "!
");
		document.write("Final States:
");
		for(var j= 0; j < finalStates.length; j++)
		{
			document.write(finalStates[j] + "; ");
		}

		document.write("
");
		document.write("Current State: " + this.currentState + "!
");

		document.write("
Transitions Table:
");
		for(var i= 0; i < transitionsTable.length; i++)
		{
			document.write(i + ": " + "currentState= " + transitionsTable[i].currentState +
				"; nextState= " + transitionsTable[i].nextState +
				"; scanSymbol= " + transitionsTable[i].scanSymbol +
				"; printSymbol= " + transitionsTable[i].printSymbol +
				"; direction= " + transitionsTable[i].direction + "!
");
		}
		document.write("Current Step number= " + this.stepNumber + "!

");

	}

}

//"Transition Class"
function Transition(currentState, nextState, scanSymbol, printSymbol, direction)
{
	this.currentState= currentState;
	this.nextState= nextState;
	this.scanSymbol= scanSymbol;
	this.printSymbol= printSymbol;
	this.direction= direction;
}

// Breakpoint Class
function Breakpoint(type, where, times, message)
{
	this.type = type;
	this.where = where;
	this.times = times;
	this.message = message;

	this.counter = 0;
	this.sequencer = 0;

	this.resetCounter = function()
	{
		this.counter = 0;
	}

	this.incrementCounter = function()
	{
		this.counter = this.counter + 1;
	}

	this.resetSequencer = function()
	{
		this.sequencer = 0;
	}

	this.incrementSequencer = function()
	{
		this.sequencer = this.sequencer + 1;
	}
}


text:
%****m* munit/Applications
%
% NAME
%   MUnit Applications
%
% DESCRIPTION
%   The MUnit test framework consists of several applications
%   to execute and manage the test cases and test suites.
%   The application functions are categorized as:
%
%   * Drivers   -- execute test cases and test suites.
%   * Utilities -- manage test cases and test suites.
%
% TOOLBOX
%    munit/munit
%
% CATEGORY
%
%
%***
%****m* Applications/Drivers
%
% NAME
%   MUnit Drivers -- MUnit applications for executing test cases and test suites.
%
% DESCRIPTION
%   The MUnit driver applications are functions to be run from the
%   command shell to execute a test case or a test suite.
%
%   Driver applications include:
%     * run_tcase
%     * run_tsuite
%
%***
%****m* Applications/Utilities
%
% NAME
%   MUnit Utilities -- MUnit applications analyzing and listing test cases and suites.
%
% DESCRIPTION
%   The MUnit utility applications are functions to be run from the
%   command shell to analyze and list a test case or a test suite.
%
%   Utility applications include:
%     * list_tcase
%     * list_tsuite
%
%***

% AUTHOR
%   Charlie Cornish
%
% CREATION DATE
%
%
% COPYRIGHT
%
%
% CREDITS
%
%
% REVISION
%   $Revision: 85 $
%

%   $Id: MUnit_Applications.m 85 2005-02-15 04:27:04Z ccornish $


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

@Component({
  selector: 'app-detalhes',
  templateUrl: './detalhes.component.html',
  styleUrls: ['./detalhes.component.css']
})
export class DetalhesComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}


text:
package org.pac.games;

import org.pac.games.gui.BouncerSprite;
import org.pac.games.physics.BounceEngine;
import org.pac.games.physics.Bouncer;
import org.pac.games.physics.CollisionListener;
import org.pac.games.physics.CollisionInstance;
import org.pac.games.physics.MovingRectangle;
import java.awt.Color;
import java.awt.Graphics;
import java.util.LinkedList;

/**
 * A window that can serve as a base class for games which
 * use the BounceEngine (a simple physics engine).
 */
public class BounceGameWindow extends SimpleGameWindow
    implements CollisionListener{
    private static final long serialVersionUID = 34587892834L;
    private BounceEngine engine;
    private Color background = Color.WHITE;
    private LinkedList<BouncerSprite> sprites =
        new LinkedList<BouncerSprite>();
    public BounceGameWindow(BounceEngine engine){
        super();
        this.engine = engine;
        addUpdater(engine);
        engine.addListener(this);
        //put a sprite painter before this painter
        assert(getComponent().removePainter(this));
        getComponent().addPainter(
            new GamePainter(){
                public void paint(Graphics g){
                    g.setColor(background);
                    g.fillRect(0,0,getDisplayWidth(),getDisplayHeight());
                    for(BouncerSprite sprite:sprites)
                        sprite.paint(g);
                }
            }
        );
        getComponent().addPainter(this);
    }
    public BounceGameWindow(){
        this(new BounceEngine());
    }

    /**
     * Add a BouncerSprite to the physics engine and the screen.
     */
    public void addSprite(BouncerSprite sprite){
        engine.add(sprite);
        sprites.add(sprite);
    }
    /**
     * Remove a BouncerSprite from the physics engine and the screen.
     */
    public boolean removeSprite(BouncerSprite sprite){
        engine.remove(sprite);
        return sprites.remove(sprite);
    }
    /**
     * Add a MovingRectangle to the collision detection part of the
     * physics engine.
     */
    public void add(MovingRectangle rectangle){
        engine.add(rectangle);
    }
    /**
     * Remove a MovingRectangle from the collision detection part of the
     * physics engine.
     */
    public void remove(MovingRectangle rectangle){
        engine.remove(rectangle);
    }
    /**
     * Remove all sprites and rectangles from the physics engine and the
     * screen.
     */
    public void clear(){
        sprites.clear();
        engine.clear();
    }
    /**
     * Get the underlying BounceEngine (physics engine).
     */
    public BounceEngine getEngine(){
        return engine;
    }
    //bounce engine wrappers
    /**
     * Tell the physics engine to telleport 'b' to 'location'.
     */
    public void teleport(Bouncer b, MovingRectangle location){
        engine.teleport(b,location);
    }
    /**
     * Add an invisible 1pxl border to the physics engine.
     */
    public void addBounceBorder(double x, double y, double width, double height){
        engine.addBounceBorder(x,y,width,height);
    }

    //optional overloadables
    /**
     * A method to override (optionally) - this can update the game's state every
     * couple of seconds.
     * @see GameUpdater
     */
    public void update(double dt){}
    /**
     * A method to override (optionally) - this renders additional graphics on top of
     * the background and sprites (which are drawn automatically).
     * @see GamePainter
     */
    public void paint(Graphics g){}
    /**
     * A method to override (optionally) - this method is called whenever the
     * physics engine detects a collision.
     * @see CollisionListener
     */
    public void handleCollision(CollisionInstance instance){}
}


text:
let Scaffold = require('.');

class ClassScaffold extends Scaffold {

    constructor(className) {
        super();
        this.className = className;
        this.methodList = [];
        this.namespace = 'App/{className}';
    }

    /**
     * Sets the new namespace.
     *
     * @param namespace
     */
    setNamespace(namespace) {
        this.namespace = namespace;
    }

    /**
     * Adds a new method to the list.
     *
     * @param name
     * @param comment
     * @param params
     * @param body
     */
    addMethod(name, comment, params = [], body) {
        this.methodList.push({
            name: name,
            comment: comment,
            param: params.join(', '),
            body: body ? body : ""
        });
    }

    /**
     * Generate a class file.
     *
     * @param filePath
     */
    generateClass(filePath) {
        this.generateTemplate();
        this.bind({
            className: this.className,
            extendClass: this.extends,
            namespace: this.namespace
        });
        return this.generateFile(filePath);
    }

    /**
     * Generate and set the template for a given class.
     */
    generateTemplate() {
        let template = 'class @{className} {\n';

        this.methodList.forEach((method) => {
            template += '\n\t/**\n';
            template += `\t* ${method.comment}\n`;
            template += `\t**/\n`;
            template += `\t${method.name}(${method.param})`;
            template += ' {\n';
            template += `\t\t${method.body}\n`;
            template += `\t}\n`;
        });
        template += '}\n\n'
                + `namespace('${this.namespace}', @{className});`;
        this.setTemplate(template);
    }
}

module.exports = ClassScaffold;


text:
package im.actor.util.http

import java.nio.file.{ Files, Path }

import scala.concurrent._

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.HttpRequest
import akka.stream.Materializer
import akka.stream.io.SynchronousFileSink

class DownloadManager(implicit system: ActorSystem, materializer: Materializer) {
  implicit val ec: ExecutionContext = system.dispatcher

  val http = Http()

  def download(url: String): Future[(Path, Long)] = {
    val tempFileFuture = createTempFile()
    val responseFuture = http.singleRequest(HttpRequest(uri = url))

    for {
      filePath ← tempFileFuture
      response ← responseFuture
      size ← response.entity.dataBytes.runWith(SynchronousFileSink(filePath.toFile))
    } yield (filePath, size)
  }

  // FIXME: dispatcher for this
  private def createTempFile(): Future[Path] = {
    Future {
      blocking {
        Files.createTempFile("ActorDownloadManager", "")
      }
    }
  }
}


text:
using System.Web;
using System.Web.Mvc;
using Microsoft.Owin;
using Microsoft.Owin.Security;

namespace UniQode.Web.Controllers
{
    public abstract class OwinContextController : Controller
    {
        protected OwinContextController(IOwinContext owinContext = null, IAuthenticationManager authenticationManager = null)
        {
            _owinContext = owinContext;
            _authenticationManager = authenticationManager;
        }

        private readonly IOwinContext _owinContext;
        public IOwinContext OwinContext => _owinContext ?? HttpContext.GetOwinContext();

        private readonly IAuthenticationManager _authenticationManager;
        public IAuthenticationManager Authentication => _authenticationManager ?? OwinContext.Authentication;
    }
}


text:
namespace NEventStore.Contrib.Persistence.SqlDialects
{
	using System;

	public class FirebirdSqlDialect : CommonSqlDialect
	{
		public override string InitializeStorage
		{
			get { return FirebirdSqlStatements.InitializeStorage; }
		}

		public override string PersistCommit
		{
			get { return FirebirdSqlStatements.PersistCommits; }
		}

		public override string GetUndispatchedCommits
		{
			get { return FirebirdSqlStatements.GetUndispatchedCommits; }
		}

		public override string GetCommitsFromInstant
		{
			get { return FirebirdSqlStatements.GetCommitsFromInstant; }
		}

		public override string GetCommitsFromToInstant
		{
			get { return FirebirdSqlStatements.GetCommitsFromToInstant; }
		}

		public override string GetCommitsFromStartingRevision
		{
			get { return FirebirdSqlStatements.GetCommitsFromStartingRevision; }
		}

		public override string GetCommitsFromBucketAndCheckpoint
		{
			get
			{
				return FirebirdSqlStatements.GetCommitsFromBucketAndCheckpoint;
			}
		}

		public override string GetSnapshot
		{
			get { return FirebirdSqlStatements.GetSnapshot; }
		}

		public override string GetStreamsRequiringSnapshots
		{
			get { return FirebirdSqlStatements.GetStreamsRequiringSnapshots; }
		}

		public override string GetCommitsFromCheckpoint
		{
			get { return FirebirdSqlStatements.GetCommitsFromCheckpoint; }
		}

		public override bool IsDuplicate(Exception exception)
		{
			string message = exception.Message.ToUpperInvariant();
			return message.Contains("DUPLICATE") || message.Contains("UNIQUE") || message.Contains("CONSTRAINT");
		}

		public override string AppendSnapshotToCommit
		{
			get { return FirebirdSqlStatements.AppendSnapshotToCommit; }
		}
	}
}


text:
def f(x):
 return x # 1 space


text:
package org.mitallast.queue.transport.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.junit.Assert;
import org.junit.Test;
import org.mitallast.queue.common.BaseTest;
import org.mitallast.queue.common.codec.Codec;
import org.mitallast.queue.common.codec.Message;

import java.util.ArrayList;

public class CodecTest extends BaseTest {

    static {
        Codec.Companion.register(123, TestStreamable.class, TestStreamable.codec);
    }

    @Test
    public void testMessage() throws Exception {
        CodecEncoder encoder = new CodecEncoder();
        CodecDecoder decoder = new CodecDecoder(logging);

        ByteBuf buffer = Unpooled.buffer();
        encoder.encode(null, new TestStreamable(123123), buffer);

        ArrayList<Object> output = new ArrayList<>();
        decoder.decode(null, buffer, output);
        Assert.assertEquals(1, output.size());

        TestStreamable message = (TestStreamable) output.get(0);
        Assert.assertEquals(123123, message.value);
    }

    @Test
    public void testMessageEncodeBenchmark() throws Exception {
        CodecEncoder encoder = new CodecEncoder();

        ByteBuf buffer = Unpooled.directBuffer(1024);
        buffer.markWriterIndex();

        TestStreamable message = new TestStreamable(123123);

        int max = 100000000;
        long start = System.currentTimeMillis();
        for (int i = 0; i < max; i++) {
            buffer.resetWriterIndex();
            encoder.encode(null, message, buffer);
        }
        long end = System.currentTimeMillis();
        printQps("encode", max, start, end);
    }

    @Test
    public void testMessageDecodeBenchmark() throws Exception {
        CodecEncoder encoder = new CodecEncoder();
        CodecDecoder decoder = new CodecDecoder(logging);

        ByteBuf buffer = Unpooled.directBuffer(1024);
        encoder.encode(null, new TestStreamable(123123), buffer);

        ArrayList<Object> output = new ArrayList<>(1);

        int max = 100000000;
        long start = System.currentTimeMillis();
        for (int i = 0; i < max; i++) {
            buffer.readerIndex(0);
            decoder.decode(null, buffer, output);
            output.clear();
        }
        long end = System.currentTimeMillis();
        printQps("decode", max, start, end);
    }

    public static class TestStreamable implements Message {
        public static final Codec<TestStreamable> codec = Codec.Companion.of(
            TestStreamable::new,
            TestStreamable::value,
            Codec.Companion.longCodec()
        );

        private final long value;

        public TestStreamable(long value) {
            this.value = value;
        }

        public long value() {
            return value;
        }
    }
}


text:
import test from "tape";
import PouchDB from "pouchdb-core";
import securityPlugin from "../src/index.js";

const {Security} = securityPlugin;

test("security.admins and security.members are a security levels", (t) => {
	t.plan(2);
	let db = new PouchDB("tmpdb", { adapter: "memory" });
	let security = db.security();

	t.ok(security.admins instanceof Security.Level, "admins is a SecurityLevel instance");
	t.ok(security.members instanceof Security.Level, "members is a SecurityLevel instance");
});

test("removeAll() removes everything from the level", (t) => {
	t.plan(2);
	let db = new PouchDB("tmpdb", { adapter: "memory" });
	let security = db.security();
	let level = security.members;

	level.add({ names: [ "name" ], roles: [ "role" ] });
	t.notOk(level.isEmpty(), "level is not empty");
	level.removeAll();
	t.ok(level.isEmpty(), "level is empty");
});

test("add() merges in names and roles with existing without duplicates", (t) => {
	t.plan(1);
	let db = new PouchDB("tmpdb", { adapter: "memory" });
	let security = db.security();
	let level = security.members;
	level.set({ names: [ "name" ], roles: [ "role", "role3" ] });
	level.add({ names: [ "name", "name2" ], roles: [ "role", "role2" ] });
	t.deepEqual(level.toJSON(), {
		names: [ "name", "name2" ],
		roles: [ "role", "role3", "role2" ]
	}, "level has correct names and roles");
});

test("remove() removes names and roles from existing", (t) => {
	t.plan(1);
	let db = new PouchDB("tmpdb", { adapter: "memory" });
	let security = db.security();
	let level = security.members;
	level.set({ names: [ "name" ], roles: [ "role", "role3" ] });
	level.remove({ names: [ "name" ], roles: [ "role", "role2" ] });
	t.deepEqual(level.toJSON(), {
		names: [ ],
		roles: [ "role3" ]
	}, "level has correct names and roles");
});

test("set() overwrites existing", (t) => {
	t.plan(1);
	let db = new PouchDB("tmpdb", { adapter: "memory" });
	let security = db.security();
	let level = security.members;
	level.set({ names: [ "name" ], roles: [ "role", "role3" ] });
	level.set({ names: [ "name2" ], roles: [ "role", "role2" ] });
	t.deepEqual(level.toJSON(), {
		names: [ "name2" ],
		roles: [ "role", "role2" ]
	}, "level has correct names and roles");
});


text:
function parse(file) {
    return file.split(/\s+/).filter(notWhiteSpace).map(toLowerCase);

    function notWhiteSpace(str) {
        return str.match(/\S/);
    }
    function toLowerCase(str) {
        return str.toLowerCase();
    }
}

module.exports = {
    parse: parse
};


text:
<?php

namespace Google\Service\AndroidPublisher;

class Comment extends \Google\Model
{
  protected $developerCommentType = DeveloperComment::class;
  protected $developerCommentDataType = '';
  protected $userCommentType = UserComment::class;
  protected $userCommentDataType = '';

  /**
   * @param DeveloperComment
   */
  public function setDeveloperComment(DeveloperComment $developerComment)
  {
    $this->developerComment = $developerComment;
  }
  /**
   * @return DeveloperComment
   */
  public function getDeveloperComment()
  {
    return $this->developerComment;
  }
  /**
   * @param UserComment
   */
  public function setUserComment(UserComment $userComment)
  {
    $this->userComment = $userComment;
  }
  /**
   * @return UserComment
   */
  public function getUserComment()
  {
    return $this->userComment;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(Comment::class, 'Google_Service_AndroidPublisher_Comment');