text:
package joshie.harvest.crops.loot;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import joshie.harvest.api.crops.Crop;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.storage.loot.LootContext;
import net.minecraft.world.storage.loot.conditions.LootCondition;
import net.minecraft.world.storage.loot.functions.LootFunction;

import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

import static joshie.harvest.core.lib.HFModInfo.MODID;

public class SetCropType extends LootFunction {
    private static List<Crop> cropsList;
    private final String crop;

    @SuppressWarnings("WeakerAccess")
    public SetCropType(LootCondition[] conditionsIn, String crop) {
        super(conditionsIn);
        this.crop = crop;
    }

    @Override
    @Nonnull
    public ItemStack apply(@Nonnull ItemStack stack, @Nonnull Random rand, @Nonnull LootContext context) {
        if (crop.equals("randomCrop")) return random(true);
        if (crop.equals("randomSeed")) return random(false);
        ResourceLocation resource = crop.contains(":") ? new ResourceLocation(crop) : new ResourceLocation(MODID, crop);
        Crop theCrop = Crop.REGISTRY.get(resource);
        return theCrop.getCropStack(stack.stackSize);
    }

    public ItemStack random(boolean crop) {
        if (cropsList == null) {
            cropsList = new ArrayList<>(Crop.REGISTRY.values());
            cropsList.remove(Crop.NULL_CROP);
        }

        Collections.shuffle(cropsList);
        return crop ? cropsList.get(0).getCropStack(1) : cropsList.get(0).getSeedStack(1);
    }

    public static class Serializer extends LootFunction.Serializer<SetCropType> {
        public Serializer() {
            super(new ResourceLocation("hf_set_crop"), SetCropType.class);
        }

        public void serialize(@Nonnull JsonObject object, @Nonnull SetCropType functionClazz, @Nonnull JsonSerializationContext serializationContext) {
            object.addProperty("crop", functionClazz.crop);
        }

        @Nonnull
        public SetCropType deserialize(@Nonnull JsonObject object, @Nonnull JsonDeserializationContext deserializationContext, @Nonnull LootCondition[] conditionsIn) {
            return new SetCropType(conditionsIn, object.get("crop").getAsString());
        }
    }
}


text: __all__ = ['test_css_tokenizer', 'test_tokenize_document']

redpajama_set_name: RedPajamaGithub


text:
(function() {
  var Rcrtmnt;

  Rcrtmnt = (function() {
    function Rcrtmnt() {}

    Rcrtmnt.prototype.init = function() {
      var login, ui;
      ui = new Rcrtmnt.ui;
      login = new Rcrtmnt.login;
      ui.build();
      login.status();
      return this.bindEvents();
    };

    Rcrtmnt.prototype.bindEvents = function() {
      var login, ui;
      ui = new Rcrtmnt.ui;
      login = new Rcrtmnt.login;
      ui.bindEvents();
      return login.bindEvents();
    };

    Rcrtmnt.prototype.setStatus = function(v) {
      return this.variables.status = v;
    };

    Rcrtmnt.prototype.getStatus = function() {
      return this.variables.status;
    };

    Rcrtmnt.prototype.setEndDate = function(v) {
      return this.variables.endDate = v;
    };

    Rcrtmnt.prototype.getEndDate = function() {
      return this.variables.endDate;
    };

    Rcrtmnt.prototype.variables = {
      app_path: 'app/',
      tpl_path: 'app/views/tpl/',
      status: 0,
      endDate: ''
    };

    return Rcrtmnt;

  })();

  Rcrtmnt.ui = (function() {
    function ui() {
      var rr;
      rr = new Rcrtmnt;
      this.variables.app_path = rr.variables.app_path;
      this.variables.tpl_path = rr.variables.tpl_path;
    }

    ui.prototype.variables = {
      app_path: '',
      tpl_path: ''
    };

    ui.prototype.build = function() {
      return $('#exam-navigation').css({
        'display': 'hidden'
      });
    };

    ui.prototype.bindEvents = function() {
      var drop, logout, submit, ul, upload,
        _this = this;
      logout = $('#lnk-logout');
      logout.on('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        _this.reload();
        $('.rnd-user-nav').removeAttr('style');
        return $.post("" + _this.variables.app_path + "logout.php", {}, function(e) {
          return console.log(e);
        }).promise().always(function() {
          $('body').find('.overlay').fadeIn();
          return _this.reload();
        }).done(function() {
          return $('body').find('.overlay').fadeOut();
        });
      });
      $('#content').on('click', '#go-hard', function() {
        return _this.goHardCore();
      });
      $('#content').on('click', '.toggle-advanced', function(e) {
        var btnText;
        e.preventDefault();
        e.stopPropagation();
        btnText = $(this).text();
        if (btnText === 'toggle advanced') {
          $(this).text('toggle basic');
        } else {
          $(this).text('toggle advanced');
        }
        $(this).parents('.general').find('ol').slideToggle();
        return $(this).parents('.task-group').find('ul.advanced').slideToggle('fast', function() {
          var href, li, pos;
          li = $(this).find('li');
          href = li.attr('id');
          pos = li.offset().top - 100;
          return $('body').animate({
            scrollTop: pos
          }, 500, function() {
            return window.location.hash = href;
          });
        });
      });
      upload = $('#upload');
      submit = $('#submit');
      drop = $('#dropzone');
      ul = upload.find('ul');
      upload.find('.cancel').on('click', function(e) {
        e.preventDefault();
        return upload.toggleClass('show');
      });
      $('#lnk-submit').on('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        return upload.toggleClass('show');
      });
      upload.on('click', 'a.browse', function(e) {
        e.stopPropagation();
        e.preventDefault();
        return $('#browse').click();
      });
      submit.fileupload({
        dropZone: drop,
        add: function(e, data) {
          var jqXHR, tpl, util;
          util = new Rcrtmnt.util;
          tpl = $('

');
          tpl.find('p').text(data.files[0].name).append('' + util.formatFileSize(data.files[0].size) + '');
          data.context = tpl.appendTo(ul);
          tpl.find('span').on('click', function() {
            if (tpl.hasClass('working')) {
              jqXHR.abort();
            }
            return tpl.fadeOut(function() {
              return tpl.remove();
            });
          });
          return jqXHR = data.submit().done(function(re, status, jqXHR) {
            upload.find('.result').append(re);
            return setTimeout(function() {
              return upload.find('.result').html('');
            }, 3000);
          });
        },
        progress: function(e, data) {
          var progress;
          progress = parseInt(data.loaded / data.total * 100, 10);
          data.context.find('.progress-bar').css({
            width: "" + progress + "%"
          }).change();
          if (progress === 100) {
            return setTimeout(function() {
              return data.context.remove();
            }, 3000);
          }
        },
        fail: function(e, data) {
          return data.context.addClass('error');
        }
      });
      $(document).on('drop dragover', function(e) {
        return e.preventDefault();
      });
      $('#lnk-howto').on('click', function(e) {
        e.preventDefault();
        if ($('#howto').length <= 0) {
          return $.get("" + _this.variables.tpl_path + "howto.tpl").done(function(tpl) {
            return $('body').append(tpl);
          });
        } else {
          return $('#howto').remove();
        }
      });
      $('body').on('click', '#howto .close', function(e) {
        e.preventDefault();
        return $('#howto').remove();
      });
      return $('body').on('click', '#wrap', function(e) {
        e.preventDefault();
        return $('#howto').remove();
      });
    };

    ui.prototype.reload = function() {
      var rr;
      rr = new Rcrtmnt;
      if (rr.getStatus() !== 1) {
        return this.loggedOut();
      } else {
        return this.loggedIn();
      }
    };

    ui.prototype.renderTemplate = function(tpl, target) {
      return $.get(tpl, function(re) {
        return $(target).html(re);
      }).done(function() {
        return $(target).toggleClass('show');
      });
    };

    ui.prototype.clearForms = function(target) {
      return $(target).find('input').val('');
    };

    ui.prototype.isOnLoginPage = function() {
      var token;
      token = $('.rnd-form').find('button').text();
      if (token.length > 0) {
        return true;
      } else {
        return false;
      }
    };

    ui.prototype.isContentLoaded = function(node) {
      if ($.trim($(node).html()).length > 0) {
        return true;
      } else {
        return false;
      }
    };

    ui.prototype.loggedIn = function() {
      var form, isExamLoaded, onLogin, onLoginHack, rr, status,
        _this = this;
      rr = new Rcrtmnt;
      onLogin = this.isContentLoaded('.rnd-form');
      onLoginHack = this.isOnLoginPage();
      isExamLoaded = this.isContentLoaded('#content');
      status = rr.getStatus();
      if (onLogin === true && status === 1) {
        form = $('.rnd-form');
        form.css({
          top: "-" + (form.height()) + "px"
        });
        form.hide().empty();
      }
      if (onLogin === false && status === 1) {
        $('.rnd-user-nav').stop().removeAttr('style').css({
          display: 'block',
          top: '40px'
        });
      }
      if (status === 1 && isExamLoaded === false) {
        return $.get("" + this.variables.app_path + "exam.php").then(function(re) {
          re = JSON.parse(re);
          return $.get("" + _this.variables.app_path + "/views/exam-cache/" + re.division + ".html").done(function(exam) {
            $('#content').html(exam).fadeIn('fast').find('.advanced').slideToggle().parent().find('.toggle-advanced').slideToggle();
            return $.get("" + _this.variables.app_path + "duration.php").done(function(re) {
              var endDate;
              rr.setEndDate(re.end_date);
              endDate = rr.getEndDate();
              console.log(rr.getEndDate());
              return $('#countdown').countdown({
                date: endDate,
                render: function(data) {
                  return $(this.el).html(data.days + " days " + this.leadingZeros(data.hours, 2) + " hrs " + this.leadingZeros(data.min, 2) + " min " + this.leadingZeros(data.sec, 2) + " sec");
                }
              });
            });
          });
        });
      }
    };

    ui.prototype.goHardCore = function() {
      var btnAdvanced, btnAdvancedText, btnAdvancedTextCurrent;
      btnAdvanced = $('#go-hard');
      btnAdvancedText = 'Go Hard Core!';
      btnAdvancedTextCurrent = btnAdvanced.text();
      if (btnAdvancedTextCurrent === btnAdvancedText) {
        btnAdvanced.text('Go Basic!');
      } else {
        btnAdvanced.text(btnAdvancedText);
      }
      $('#content').find('article.advanced').slideToggle();
      return $('.general').find('.toggle-advanced').slideToggle();
    };

    ui.prototype.loggedOut = function() {
      var content, form, onLogin, rr, status, upload;
      rr = new Rcrtmnt;
      onLogin = this.isContentLoaded('.rnd-form');
      status = rr.getStatus();
      content = $('#content');
      if (status === 0 && onLogin === false) {
        this.renderTemplate("" + this.variables.tpl_path + "/login.tpl", '.rnd-form');
        $('.rnd-user-nav').stop().removeAttr('style').css('display', 'none');
        content.fadeOut().html('');
        form = $('.rnd-form');
        form.css({
          top: "" + (form.height()) + "px",
          display: 'block'
        });
      }
      if (status === 0 && (onLogin === false || onLogin === true)) {
        upload = $('#upload');
        if (upload.hasClass('show')) {
          return upload.toggleClass('show');
        }
      }
    };

    return ui;

  })();

  Rcrtmnt.login = (function() {
    function login() {
      var rr;
      rr = new Rcrtmnt;
      this.variables.app_path = rr.variables.app_path;
      this.variables.tpl_path = rr.variables.tpl_path;
    }

    login.prototype.variables = {
      app_path: '',
      tpl_path: ''
    };

    login.prototype.bindEvents = function() {
      var form,
        _this = this;
      form = $('.rnd-form');
      return form.on('click', '#btn-login', function(e) {
        var data, login, ui;
        e.preventDefault();
        login = $('#login');
        data = login.serializeArray();
        _this.submit(data);
        ui = new Rcrtmnt.ui;
        return ui.reload();
      });
    };

    login.prototype.submit = function(data) {
      var rr, ui;
      rr = new Rcrtmnt;
      ui = new Rcrtmnt.ui;
      return $.post("" + this.variables.app_path + "login.php", data, function(re) {
        console.log(re);
        if (re === 'true') {
          rr.setStatus(1);
          ui.clearForms('.rnd-form');
          return ui.loggedIn();
        }
      }).always(function() {
        return ui.reload();
      });
    };

    login.prototype.status = function() {
      var rr, ui,
        _this = this;
      rr = new Rcrtmnt;
      ui = new Rcrtmnt.ui;
      return $.get("" + rr.variables.app_path + "status.php", function(re) {
        if (re === 'true') {
          return rr.setStatus(1);
        } else {
          return rr.setStatus(0);
        }
      }).promise().done(function() {
        return setTimeout(function() {
          return _this.status();
        }, 3000);
      }).always(function() {
        return ui.reload();
      });
    };

    return login;

  })();

  Rcrtmnt.util = (function() {
    function util() {}

    util.prototype.formatFileSize = function(bytes) {
      if (typeof bytes !== 'number') {
        return false;
      }
      if (bytes >= 1000000000) {
        retunrn((bytes / 1000000000).toFixed(2) + ' GB');
      }
      if (bytes >= 1000000) {
        return (bytes / 1000000).toFixed(2) + ' MB';
      }
      return (bytes / 1000).toFixed(2) + ' KB';
    };

    return util;

  })();

  $(document).ready(function() {
    var rr;
    rr = new Rcrtmnt;
    return rr.init();
  });

}).call(this);


text:
package com.plivo.api.models.identity;

import com.plivo.api.models.base.Updater;
import retrofit2.Call;

public class IdentityUpdater extends Updater<IdentityUpdateResponse> {
  private String countryIso;
  private String alias;
  private String salutation;
  private String firstName;
  private String lastName;
  private String birthPlace;
  private String birthDate;
  private String nationality;
  private String idNationality;
  private String idIssueDate;
  private String businessName;
  private String idType;
  private String idNumber;
  private String addressLine1;
  private String addressLine2;
  private String city;
  private String region;
  private String postalCode;
  private String fiscalIdentificationCode;
  private String streetCode;
  private String municipalCode;
  private String subaccount;
  private String file;

  public IdentityUpdater( String id ){
    super(id);
  }

  public String countryIso() {
    return countryIso;
  }

  public String salutation() {
    return salutation;
  }

  public String firstName() {
    return firstName;
  }

  public String lastName() {
    return lastName;
  }

  public String birthPlace() {
    return birthPlace;
  }

  public String birthDate() {
    return birthDate;
  }

  public String nationality() {
    return nationality;
  }

  public String idNationality() {
    return idNationality;
  }

  public String idIssueDate() {
    return idIssueDate;
  }

  public String businessName() {
    return businessName;
  }

  public String idType() {
    return idType;
  }

  public String idNumber() {
    return idNumber;
  }

  public String addressLine1() {
    return addressLine1;
  }

  public String addressLine2() {
    return addressLine2;
  }

  public String city() {
    return city;
  }

  public String region() {
    return region;
  }

  public String postalCode() {
    return postalCode;
  }

  public String fiscalIdentificationCode() {
    return fiscalIdentificationCode;
  }

  public String streetCode() {
    return streetCode;
  }

  public String municipalCode() {
    return municipalCode;
  }

  public String subaccount() {
    return subaccount;
  }

  public String file() {
    return file;
  }

  public IdentityUpdater alias( String alias ){
    this.alias = alias;
    return this;
  }

  public IdentityUpdater countryIso( String countryIso ){
    this.countryIso = countryIso;
    return this;
  }

  public IdentityUpdater salutation( String salutation ){
    this.salutation = salutation;
    return this;
  }

  public IdentityUpdater firstName( String firstName ){
    this.firstName = firstName;
    return this;
  }

  public IdentityUpdater lastName( String lastName ){
    this.lastName = lastName;
    return this;
  }

  public IdentityUpdater birthPlace( String birthPlace ){
    this.birthPlace = birthPlace;
    return this;
  }

  public IdentityUpdater birthDate( String birthDate ){
    this.birthDate = birthDate;
    return this;
  }

  public IdentityUpdater nationality( String nationality ){
    this.nationality = nationality;
    return this;
  }

  public IdentityUpdater idNationality( String idNationality ){
    this.idNationality = idNationality;
    return this;
  }

  public IdentityUpdater idIssueDate( String idIssueDate ){
    this.idIssueDate = idIssueDate;
    return this;
  }

  public IdentityUpdater businessName( String businessName ){
    this.businessName = businessName;
    return this;
  }

  public IdentityUpdater idType( String idType ){
    this.idType = idType;
    return this;
  }

  public IdentityUpdater idNumber( String idNumber ){
    this.idNumber = idNumber;
    return this;
  }

  public IdentityUpdater addressLine1( String addressLine1 ){
    this.addressLine1 = addressLine1;
    return this;
  }

  public IdentityUpdater addressLine2( String addressLine2 ){
    this.addressLine2 = addressLine2;
    return this;
  }

  public IdentityUpdater city( String city ){
    this.city = city;
    return this;
  }

  public IdentityUpdater region( String region ){
    this.region = region;
    return this;
  }

  public IdentityUpdater postalCode( String postalCode ){
    this.postalCode = postalCode;
    return this;
  }

  public IdentityUpdater fiscalIdentificationCode( String fiscalIdentificationCode ){
    this.fiscalIdentificationCode = fiscalIdentificationCode;
    return this;
  }

  public IdentityUpdater streetCode( String streetCode ){
    this.streetCode = streetCode;
    return this;
  }

  public IdentityUpdater municipalCode( String municipalCode ){
    this.municipalCode = municipalCode;
    return this;
  }

  public IdentityUpdater subaccount( String subaccount ){
    this.subaccount = subaccount;
    return this;
  }

  public IdentityUpdater file( String file ){
    this.file = file;
    return this;
  }

  @Override
  protected Call<IdentityUpdateResponse> obtainCall() {
    return client().getApiService().identityUpdate(client().getAuthId(), id, this);
  }
}


text:
layout: page
title: Brewer Omega Llc. Seminar
date: 2016-05-24
author: Katherine Harrison
tags: weekly links, java
status: published
summary: Pellentesque gravida egestas rutrum. Pellentesque ullamcorper ultrices.
banner: images/banner/wedding.jpg
booking:
  startDate: 05/07/2018
  endDate: 05/12/2018
  ctyhocn: SLCDTHX
  groupCode: BOLS
published: true
---
Nullam congue mi ac cursus sollicitudin. Quisque sed dictum dui, non fermentum nibh. Duis ornare libero lectus, ac molestie felis efficitur congue. Donec vestibulum viverra leo sed suscipit. Maecenas suscipit quis ante vestibulum congue. Nunc a blandit arcu. Nulla facilisi.
Fusce accumsan nisl enim, eget maximus velit mattis eu. In cursus tincidunt congue. Nam metus dolor, laoreet quis vestibulum sit amet, semper quis metus. Praesent sed rhoncus risus. Integer et erat vitae ante mollis scelerisque et sed sem. Aenean eu hendrerit tellus. Ut quis porta lectus. Morbi ipsum neque, elementum et neque pellentesque, faucibus pellentesque turpis. Praesent pellentesque vel dui in varius. Suspendisse non sapien non augue tempus varius. Praesent risus lectus, efficitur non mi a, molestie finibus purus. Mauris euismod odio eu velit fermentum, at sollicitudin sapien luctus. Cras maximus pellentesque egestas.

1 Phasellus placerat sem in metus dapibus mollis
1 Quisque molestie nulla nec enim ultricies convallis
1 Suspendisse in metus nec nisi pretium venenatis
1 Etiam quis mi ac odio semper pulvinar
1 Ut ut purus fermentum, viverra est non, facilisis tortor.

Praesent volutpat sagittis ipsum. Nam ut arcu nisi. Aliquam venenatis magna a justo maximus pulvinar ut at metus. Sed tempus vel odio ac faucibus. Interdum et malesuada fames ac ante ipsum primis in faucibus. Sed malesuada pulvinar elit eu interdum. Ut vel nisl lorem. Mauris ultricies luctus odio vitae placerat. Aliquam scelerisque venenatis massa at pulvinar. Ut ac libero ac diam hendrerit semper a et lacus. Curabitur erat ligula, accumsan sit amet hendrerit et, iaculis vitae ante. Praesent auctor, turpis a semper accumsan, enim arcu semper eros, vel efficitur dui nulla nec mi. Proin mattis mauris in accumsan sodales. Vestibulum gravida velit vel sem rutrum, ac commodo ex gravida.


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>de.csc.kafka.tutorial</groupId>
    <artifactId>kafka-streaming</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>pom</packaging>
    <modules>
        <module>first-stuff</module>
    </modules>

</project>


text:
"""Widgets are used to perform filtering.
"""

from django.utils.text import capfirst

from datable.core.converters import BooleanConverter
from datable.core.converters import DateValueConverter
from datable.core.converters import DateTimeValueConverter
from datable.core.converters import StringValueConverter

from datable.core.filters import BooleanFilter
from datable.core.filters import DateFilter
from datable.core.filters import DateTimeFilter
from datable.core.filters import StringFilter

Minimum = 'min'

Maximum = 'max'

class Constraints(object):
    """This object defines how to change constraints of JS controls
    in the web UI; currently it is used by DateFilter"""
    def __init__(self, kind, name):
        self.kind = kind
        self.name = name

class Widget:

    label = None
    initialValue = None
    placeholder = None
    constraints = None

    converterClass = None
    converterKwargs = None
    converter = None

    filterClass = None
    filterKwargs = None
    filter = None

    templateName = None

    def __init__(self, name, converter=None, converterKwargs=None,
                 converterField=None, filter=None, filterField=None,
                 filterKwargs=None, label=None, initialValue=None,
                 placeholder=None, constraints=None, storage=None,
                 templateName=None):

        self.name = name
        self.converter = converter
        self.filter = filter

        # Label - used in export data
        if label is not None:
            self.label = label

        if self.label is None:
            self.label = capfirst(self.name.replace("_", " "))

        # HTML5 placeholder
        if placeholder is not None:
            self.placeholder = placeholder

        self.constraints = constraints

        if converterKwargs is not None:
            self.converterKwargs = converterKwargs

        if filterKwargs is not None:
            self.filterKwargs = filterKwargs

        # set converter and filter
        for argument, classVar, classClass, field, kwargs in [
            (converter, 'converter', self.converterClass,
             converterField, self.converterKwargs),
            (filter, 'filter', self.filterClass,
             filterField, self.filterKwargs)]:

            if argument is not None:
                setattr(self, classVar, argument)

            if field is None:
                field = self.name

            if getattr(self, classVar, None) is None:
                if classClass is None:
                    raise Exception(
                        "set %(a)sClass or pass %(a)s parameter" % (
                            dict(a=classVar)))
                kw = kwargs or {}
                setattr(self, classVar, classClass(field, **kw))

        if initialValue is not None:
            self.initialValue = initialValue

        self.initialValue_js = self.converter.valueToJS(self.initialValue)

        self.storage = storage

        if templateName is not None:
            self.templateName = templateName

    def existsIn(self, requestDict):
        """Does this widget exists in the requestDict?
        """
        return self.converter.existsIn(requestDict)

    def exportDescription(self, requestDict):
        """Get export description of this field.
        This is used when rendering a file with export data and we want to
        display a description of filters used in the file"""

        if self.existsIn(requestDict):
            return [self.label, self.converter.valueFromJS(requestDict)]

    def filterQuerySet(self, querySet, requestDict):
        """Perfom filtering, using this widget's value
        """
        if self.existsIn(requestDict):
            value = self.converter.valueFromJS(requestDict)
            return self.filter.filterQuerySet(querySet, value)
        return querySet

    def getName(self):
        return self.name

    def getStorage(self):
        return self.storage

class StringWidget(Widget):
    converterClass = StringValueConverter
    filterClass = StringFilter
    filterKwargs = {'operation': 'contains'}
    templateName = "string"

class DateTimeWidget(Widget):
    converterClass = DateTimeValueConverter
    filterClass = DateTimeFilter
    templateName = "datetime"

class DateWidget(Widget):
    converterClass = DateValueConverter
    filterClass = DateFilter
    templateName = "date"

class BooleanWidget(Widget):
    converterClass = BooleanConverter
    filterClass = BooleanFilter
    templateName = "checkbox"


text:
import pytz
import logging
import datetime
from pytz import timezone
import simplejson as json
from tastypie.api import Api
from django.conf import settings
from django.test import TestCase
from monlog.log.views import save_label
from datetime import timedelta, datetime
from monlog.log.models import LogMessage,Label
from dateutil.relativedelta import relativedelta
from tastypie.models import create_api_key, ApiKey
from tastypie.authentication import Authentication
from monlog.log.api.validation import LogValidation
from tastypie.authorization import DjangoAuthorization
from django.contrib.auth.models import User, Permission
from monlog.log.models import Expectation, RelativedeltaField
from monlog.log.api.authentication import MonlogAuthentication
from monlog.log.management.commands.cron import Command as CronCommand
from django.http import HttpRequest, HttpResponse, HttpResponseBadRequest

class MonlogCronTest(TestCase):
    fixtures = ['auth.json']
    expectation_counter = 0

    @classmethod
    def createExpectation(self, deadline=None, tolerance=None, repeat=None):
        exp = Expectation()
        exp.repeat_count = 0
        exp.query_string = ''
        exp.least_amount_of_results = 1
        exp.user = User.objects.get(pk=1)
        exp.name = "Expectation-%s" % self.expectation_counter
        self.expectation_counter += 1

        exp.deadline = exp.original_deadline = deadline
        exp.tolerance = tolerance
        exp.repeat = repeat

        return exp

    def test_leap_year(self):
        deadline = datetime(year = 2012, month = 2, day = 29,
                            hour = 12, minute = 0, second = 0,
                            tzinfo = pytz.UTC)

        exp = MonlogCronTest.createExpectation(
            deadline = deadline,
            tolerance = relativedelta(minutes = 10),
            repeat = relativedelta(months = 1)
        )
        exp.save()

        mock_time = datetime(year = 2012, month = 3, day = 28,
                             hour = 12, minute = 0, second = 0,
                             tzinfo = pytz.UTC)

        # Script is run the 28th of March
        command = CronCommand()
        command.handle(mock_datetime = mock_time)

        exp = Expectation.objects.get(pk=exp.id)

        self.assertEqual(exp.deadline.month, 3)
        self.assertEqual(exp.deadline.day, 29)

    def test_non_leap_year(self):
        deadline = datetime(year = 2012, month = 2, day = 29,
                            hour = 12, minute = 0, second = 0,
                            tzinfo = pytz.UTC)

        exp = MonlogCronTest.createExpectation(
            deadline = deadline,
            tolerance = relativedelta(minutes = 10),
            repeat = relativedelta(months = 12)
        )
        exp.save()

        mock_time = datetime(year = 2013, month = 2, day = 28,
                             hour = 12, minute = 0, second = 0,
                             tzinfo = pytz.UTC)

        # Script is run the 28th of March
        command = CronCommand()
        command.handle(mock_datetime = mock_time)

        exp = Expectation.objects.get(pk=exp.id)

        self.assertEqual(exp.deadline.year, 2013)
        self.assertEqual(exp.deadline.month, 2)
        self.assertEqual(exp.deadline.day, 28)

class MonlogTestCase(TestCase):
    fixtures = ['auth.json']

    username = "testapp"
    userpass = "test"

class ModelTest(MonlogTestCase):

    def setUp(self):
        login = self.client.login(username=self.username, password=self.userpass)
        if not login:
            print "Couldn't log in!"

    def test_save_label(self):
        """ Testing if label saving works """

        # Check for HttpResponseBadRequest if `name` or `query_string` not provided.
        data = {}
        response = self.client.post("/label/save/", data)
        self.assertEqual(response.status_code, 400)

        # Valid post should work correctly.
        data['name']="validname"
        data['query_string']="severity__in=0" # also valid
        response = self.client.post("/label/save/", data)
        self.assertEqual(response.status_code, 200)

class RestTest(MonlogTestCase):
    api_uri = "/api/log/?api_key="

    logmessages_uri = "/api/logmessages/"

    def setUp(self):
        """
        Creates an api key for test user(from fixture) and sets permission to add logmessages
        """
        super(RestTest, self).setUp()
        ApiKey.objects.all().delete()
        create_api_key(User, instance=User.objects.get(username=self.username), created=True)
        add_logmessage = Permission.objects.get(codename='add_logmessage')
        User.objects.get(username=self.username).user_permissions.add(add_logmessage)

    def test_auth(self):
        """
        Tests user authentication using APIKEY and username
        """
        auth = MonlogAuthentication()
        request = HttpRequest()

        testapp = User.objects.get(username=self.username) #API key created in setUp()
        request.GET['api_key'] = testapp.api_key.key

        self.assertEqual(auth.is_authenticated(request), True)

    def test_get_from_rest(self):
        """
        Testing if we can use GET-method from the rest api. This should not be possible.
        """
        response = self.client.get("/api/log/")
        self.assertEqual(response.status_code, 405) #Method not allowed

    def test_unauth_post(self):
        """
        Tests if we can post without api key and user.
        """
        data = {"severity": 0 , "timestamp" : "1335169880" } #wellformed data
        resp = self.client.post("/api/log/", data)
        self.assertEqual(resp.status_code, 401) #Unauthorized

    def test_post(self):
        """
        Tests various types of content we're trying to submit.
        """
        testapp = User.objects.get(username=self.username)

        # Missing timestamp
        data = {"severity": 0}
        resp = self.client.post(self.api_uri + testapp.api_key.key, json.dumps(data), content_type='application/json')
        self.assertEqual(resp.status_code, 400)

        # Datetime malformed, missing lots of stuff
        data = {"severity": 0,
                "timestamp" : "2001-02-22T12:12:12Z"}
        resp = self.client.post(self.api_uri + testapp.api_key.key, json.dumps(data), content_type='application/json')
        self.assertEqual(resp.status_code, 400)

        # Severity out of scope
        data = {"severity": 15,
                "timestamp" : "1335169880",
                "long_desc" : "data",
                "short_desc" : "This is a short description"}
        resp = self.client.post(self.api_uri + testapp.api_key.key, json.dumps(data), content_type='application/json')
        self.assertEqual(resp.status_code, 400)

        # long_desc or short_desc is possible to be without
        data = {"severity": 0,
                "timestamp" : "1335169660"}
        resp = self.client.post(self.api_uri + testapp.api_key.key, json.dumps(data), content_type='application/json')
        self.assertEqual(resp.status_code, 201) # CREATED

        # Successful post and wellformed post
        data = {"severity": 0,
                "timestamp" : "1335169880",
                "long_desc" : "This is a long description",
                "short_desc" : "This is a short description"}

        resp = self.client.post(self.api_uri + testapp.api_key.key, json.dumps(data), content_type='application/json')
        self.assertEqual(resp.status_code, 201) #201=CREATED


text:
require File.dirname(__FILE__) + '/spec_helper.rb'

SPHINX_CONFIG = <<-SPHINX
  indexer
  {
  }

  searchd
  {
    listen = 127.0.0.1:9312
    log = /log/searchd.log
    query_log = /log/searchd.query.log
    pid_file = /log/searchd.development.pid
  }

  source person_core_0
  {
    type = mysql
    sql_host = localhost
    sql_user = root
    sql_pass =
    sql_db = graystone_development
    sql_query_pre = SET NAMES utf8
    sql_query_pre = SET TIME_ZONE = '+0:00'
    sql_query = SELECT SQL_NO_CACHE `people`.`id` * 4 + 2 AS `id` , `people`.`name` AS `name`, `people`.`id` AS `sphinx_internal_id`, 1013574116 AS `class_crc`, 0 AS `sphinx_deleted`, UNIX_TIMESTAMP(`people`.`created_at`) AS `created_at` FROM `people`    WHERE `people`.`id` >= $start AND `people`.`id` <= $end GROUP BY `people`.`id`  ORDER BY NULL
    sql_query_range = SELECT IFNULL(MIN(`id`), 1), IFNULL(MAX(`id`), 1) FROM `people`
    sql_attr_uint = sphinx_internal_id
    sql_attr_uint = class_crc
    sql_attr_uint = sphinx_deleted
    sql_attr_timestamp = created_at
    sql_query_info = SELECT * FROM `people` WHERE `id` = (($id - 2) / 4)
  }

  index person_core
  {
    source = person_core_0
    path = /db/sphinx/development/person_core
    charset_type = utf-8
  }

  source person_delta_0 : person_core_0
  {
    type = mysql
    sql_host = localhost
    sql_user = root
    sql_pass =
    sql_db = graystone_development
    sql_query_pre =
    sql_query_pre = SET NAMES utf8
    sql_query_pre = SET TIME_ZONE = '+0:00'
    sql_query = SELECT SQL_NO_CACHE `people`.`id` * 4 + 2 AS `id` , `people`.`name` AS `name`, `people`.`id` AS `sphinx_internal_id`, 1013574116 AS `class_crc`, 0 AS `sphinx_deleted`, UNIX_TIMESTAMP(`people`.`created_at`) AS `created_at` FROM `people`    WHERE `people`.`id` >= $start AND `people`.`id` <= $end AND `people`.`updated_at` > DATE_SUB(NOW(), INTERVAL 1800 SECOND) GROUP BY `people`.`id`  ORDER BY NULL
    sql_query_range = SELECT IFNULL(MIN(`id`), 1), IFNULL(MAX(`id`), 1) FROM `people` WHERE `people`.`updated_at` > DATE_SUB(NOW(), INTERVAL 1800 SECOND)
    sql_attr_uint = sphinx_internal_id
    sql_attr_uint = class_crc
    sql_attr_uint = sphinx_deleted
    sql_attr_timestamp = created_at
    sql_query_info = SELECT * FROM `people` WHERE `id` = (($id - 2) / 4)
  }

  index person_delta : person_core
  {
    source = person_delta_0
    path = /db/sphinx/development/person_delta
  }

  index person
  {
    type = distributed
    local = person_delta
    local = person_core
  }

  source robot_core_0
  {
    type = mysql
    sql_host = localhost
    sql_user = root
    sql_pass =
    sql_db = garystone_development
    sql_query_pre = UPDATE `robots` SET `updated_at` = 0 WHERE `updated_at` = 1
    sql_query_pre = SET SESSION group_concat_max_len = 1048576
    sql_query_pre = SET NAMES utf8
    sql_query_pre = SET TIME_ZONE = '+0:00'
    sql_query = SELECT SQL_NO_CACHE `robots`.`id` * 4 + 3 AS `id` , `robots`.`model` AS `model`,, `robots`.`id` AS `sphinx_internal_id`, 1552019743 AS `class_crc`, 0 AS `sphinx_deleted`, UNIX_TIMESTAMP(CONVERT_TZ(robots.created_at, '+00:00', @@session.time_zone)) AS `created_at`, UNIX_TIMESTAMP(CONVERT_TZ(robots.updated_at, '+00:00', @@session.time_zone)) AS `updated_at` FROM `robots` WHERE `robots`.`id` >= $start AND `robots`.`id` <= $end GROUP BY `robots`.`id`  ORDER BY NULL
    sql_query_range = SELECT IFNULL(MIN(`id`), 1), IFNULL(MAX(`id`), 1) FROM `robots`
    sql_attr_uint = sphinx_internal_id
    sql_attr_uint = class_crc
    sql_attr_uint = sphinx_deleted
    sql_attr_timestamp = created_at
    sql_attr_timestamp = updated_at
    sql_query_info = SELECT * FROM `robots` WHERE `id` = (($id - 3) / 4)
  }

  index robot_core
  {
    source = robot_core_0
    path = /db/sphinx/development/robot_core
    charset_type = utf-8
  }

  source robot_delta_0 : robot_core_0
  {
    type = mysql
    sql_host = localhost
    sql_user = root
    sql_pass =
    sql_db = satisfaction_development
    sql_query_pre =
    sql_query_pre = SET NAMES utf8
    sql_query_pre = SET TIME_ZONE = '+0:00'
    sql_query = SELECT SQL_NO_CACHE `robots`.`id` * 4 + 3 AS `id` , `robots`.`model` AS `model`,, `robots`.`id` AS `sphinx_internal_id`, 1552019743 AS `class_crc`, 0 AS `sphinx_deleted`, UNIX_TIMESTAMP(CONVERT_TZ(robots.created_at, '+00:00', @@session.time_zone)) AS `created_at`, UNIX_TIMESTAMP(CONVERT_TZ(robots.updated_at, '+00:00', @@session.time_zone)) AS `updated_at` FROM `robots` WHERE `robots`.`id` >= $start AND `robots`.`id` <= $end GROUP BY `robots`.`id`  ORDER BY NULL
    sql_query_range = SELECT IFNULL(MIN(`id`), 1), IFNULL(MAX(`id`), 1) FROM `topics` WHERE `topics`.`updated_at` > DATE_SUB(NOW(), INTERVAL 86400 SECOND)
    sql_attr_uint = sphinx_internal_id
    sql_attr_uint = class_crc
    sql_attr_uint = sphinx_deleted
    sql_attr_timestamp = created_at
    sql_attr_timestamp = updated_at
    sql_query_info = SELECT * FROM `topics` WHERE `id` = (($id - 3) / 4)
  }

  index robot_delta : robot_core
  {
    source = topic_delta_0
    path = /db/sphinx/development/robot_delta
  }

  index robot
  {
    type = distributed
    local = robot_delta
    local = robot_core
  }

SPHINX

describe Deltoid do

  before :each do
    DaemonKit.arguments = DaemonKit::Arguments.new
  end

  # ===== SPHINX CONFIG ================================================================================================

  describe "#sphinx_config_file" do

    describe "when explicitly set" do

      before :each do
        @deltoid = Deltoid.new("development.sphinx.conf")
      end

      it "should return the set value" do
        @deltoid.sphinx_config_file.should == "development.sphinx.conf"
      end

    end

    describe "when not set" do

      before :each do
        DaemonKit.arguments.options[:sphinx_config_file] = 'custom.sphinx.conf'
        @deltoid = Deltoid.new
      end

      it "should default to the :sphinx_config_file argument" do
        @deltoid.sphinx_config_file.should == "custom.sphinx.conf"
      end

    end

  end

  describe "sphinx_pid" do

    before :each do
      @deltoid = Deltoid.new
    end

    describe "when sphinx is running" do

      before :each do
        @deltoid.should_receive(:`).with("pgrep searchd").and_return("4321\n")
      end

      it "should return the pid" do
        @deltoid.sphinx_pid.should == 4321
      end

    end

    describe "when sphinx is not running" do

      before :each do
        @deltoid.should_receive(:`).with("pgrep searchd").and_return("\n")
      end

      it "should return nil" do
        @deltoid.sphinx_pid.should == nil
      end

    end

  end

  describe "sphinx_client" do

    describe "when a sphinx configuration is present" do

      before :each do
        @deltoid = Deltoid.new("sphinx.conf")
        File.should_receive(:read, "sphinx.conf").and_return(SPHINX_CONFIG)
      end

      it "should return a Riddle::Client with the server and port in the config" do
        Riddle::Client.should_receive(:new).with('127.0.0.1', 9312)
        @deltoid.sphinx_client
      end

    end

    describe "when a sphinx configuration is not present" do

      before :each do
        @deltoid = Deltoid.new
      end

      it "should return a default Riddle::Client" do
        Riddle::Client.should_receive(:new).with()
        @deltoid.sphinx_client
      end

    end

  end

  # ===== INDEXES ======================================================================================================

  describe "#delta_index_prefixes" do

    before :each do
      @deltoid = Deltoid.new("sphinx.conf")
      File.should_receive(:read, "sphinx.conf").and_return(SPHINX_CONFIG)
    end

    it "should extract delta index names from the sphinx config" do
      @deltoid.delta_index_prefixes.should == %w[person robot]
    end

  end

  describe "#stale_index_prefixes" do

    before :each do
      @deltoid = Deltoid.new
      @deltoid.should_receive(:delta_index_prefixes).and_return(%w[person robot beast])

      @deltoid.should_receive(:cache_get).with("person_index_is_stale").and_return(1)
      @deltoid.should_receive(:cache_get).with("robot_index_is_stale").and_return(nil)
      @deltoid.should_receive(:cache_get).with("beast_index_is_stale").and_return("1")
    end

    it "should iterate through each delta index and return which are stale" do
      @deltoid.stale_index_prefixes.should == %w[person beast]
    end

  end

  # ===== CACHE ========================================================================================================

  describe "#memcached_config_file" do

    describe "when explicitly set" do

      before :each do
        @deltoid = Deltoid.new(nil, "memcached.yml")
      end

      it "should return the set value" do
        @deltoid.memcached_config_file.should == "memcached.yml"
      end

    end

    describe "when not set" do

      before :each do
        DaemonKit.arguments.options[:memcached_yml_file] = 'custom.memcached.yml'
        @deltoid = Deltoid.new
      end

      it "should default to the :memcached_yml_file argument" do
        @deltoid.memcached_config_file.should == 'custom.memcached.yml'
      end

    end

  end

  describe "#cache" do

    describe "when no memcached config was provided" do

      it "should contact a local memcached on the default port" do
        MemCache.should_receive(:new).with('localhost:11211', :multithread => true)
        Deltoid.new.cache
      end

    end

    describe "when a memached config is available" do

      before :each do
        @deltoid = Deltoid.new(nil, "memcached.yml")

        @defaults = {
          'multithread' => true
        }

        ::YAML.should_receive(:load_file, 'memcached.yml').and_return({
          'development' => {
            'servers' => [ 'localhost:11211' ]
          },
          'test' => {
            'servers' => [ 'localhost:11211', 'localhost:11212' ],
            'timeout' => 2.0
          },
          'defaults' => {
            'multithread' => true
          }
        })
      end

      it "should use the options for the current environment, merged with the 'defaults' config" do
        DAEMON_ENV.should == 'test'

        MemCache.should_receive(:new).with('localhost:11211', 'localhost:11212', :multithread => true, :timeout => 2.0)
        @deltoid.cache
      end

    end

  end

  # ===== REINDEXING ===================================================================================================

  describe "run_indexer_for_stale_indexes" do

    before :each do
      @deltoid = Deltoid.new("sphinx.conf")
    end

    describe "when the indexer is successful" do

      before :each do
        @deltoid.should_receive(:sphinx_running?).and_return(false)
        @deltoid.should_receive(:`).with("indexer  --config \"sphinx.conf\" person_delta beast_delta")

        $?.should_receive(:exitstatus).and_return(0)
      end

      it "should return true" do
        @deltoid.run_indexer_for_stale_indexes(%w[person beast]).should == true
      end

    end

    describe "when the indexer fails" do

      before :each do
        @deltoid.should_receive(:sphinx_running?).and_return(false)

        @deltoid.should_receive(:`).with("indexer  --config \"sphinx.conf\" person_delta beast_delta")
        $?.should_receive(:exitstatus).and_return(1)
      end

      it "should return false" do
        @deltoid.run_indexer_for_stale_indexes(%w[person beast]).should == false
      end

    end

    describe "when sphinx is running" do

      before :each do
        @deltoid.should_receive(:sphinx_running?).and_return(true)
      end

      it "should run the indexer with the --rotate flag" do
        @deltoid.should_receive(:`).with("indexer --rotate --config \"sphinx.conf\" person_delta beast_delta")
        @deltoid.run_indexer_for_stale_indexes(%w[person beast])
      end

    end

  end

  describe "#reindex_main_indexes" do

    before :each do
      @deltoid = Deltoid.new("sphinx.conf")
      @deltoid.should_receive(:delta_index_prefixes).and_return(%w[person robot beast])
      %w[person robot beast].each do |index_prefix|
        @deltoid.should_receive(:clear_stale_index_with_prefix, index_prefix)
      end
    end

    describe "when sphinx is running" do

      before :each do
        @deltoid.should_receive(:sphinx_running?).and_return(true)
      end

      it "should ask the indexer to rotate the indexes" do
        @deltoid.should_receive(:`).with("indexer --config \"sphinx.conf\" --rotate --all")
        @deltoid.reindex_main_indexes!
      end

    end

    describe "when sphinx is not running" do

      before :each do
        @deltoid.should_receive(:sphinx_running?).and_return(false)
      end

      it "should not ask the indexer to rotate the indexes" do
        @deltoid.should_receive(:`).with("indexer --config \"sphinx.conf\"  --all")
        @deltoid.reindex_main_indexes!
      end

    end

    describe "when the indexer is successful" do

      before :each do
        @deltoid.should_receive(:sphinx_running?).and_return(true)
        @deltoid.should_receive(:`).with("indexer --config \"sphinx.conf\" --rotate --all")
        $?.should_receive(:exitstatus).and_return(0)
      end

      it "should return true" do
        @deltoid.reindex_main_indexes!.should == true
      end

    end

    describe "when the indexer fails" do

      before :each do
        @deltoid.should_receive(:sphinx_running?).and_return(true)
        @deltoid.should_receive(:`).with("indexer --config \"sphinx.conf\" --rotate --all")
        $?.should_receive(:exitstatus).and_return(1)
      end

      it "should return false" do
        @deltoid.reindex_main_indexes!.should == false
      end

    end

  end

end


text:
require 'digest'
require 'shellwords'

file = ARGV[0]
name = ENV["SCRIPT_NAME"]
script_url = ENV["SCRIPT_URL"]

if script_url.end_with?(".rb")
  path = "#{file}.rb"
elsif script_url.match?(/\.ya?ml$/)
  path = "#{file}.yml"
else
  puts "Unknown extension of #{script_url}"
  exit 1
end

File.rename(file, path)

ENV['REPO_NAME'] = 'ruby'
ENV['ORGANIZATION_NAME'] = 'ruby'
ENV['BENCHMARK_TYPE_DIGEST'] = Digest::SHA2.file(path).hexdigest
ENV['BENCHMARK_TYPE_SCRIPT_URL'] = script_url
ENV['RUBY_ENVIRONMENT'] = 'true'
ENV['LANG'] = 'C.UTF-8'

ips_command = [
  "benchmark-driver", path,
  "-e", "#{name}::#{RbConfig.ruby.shellescape}",
  "-e", "#{name}_jit::#{RbConfig.ruby.shellescape} --jit",
  "--runner", "ips",
  "--output", "rubybench",
  "--repeat-count", "1",
  "--repeat-result", "best",
  "--timeout", "60"
]

rsskb_command = [
  "benchmark-driver", path,
  "-e", "rss_kb::#{RbConfig.ruby.shellescape}",
  "--runner", "rsskb",
  "--output", "rubybench",
  "--repeat-count", "1",
  "--repeat-result", "best",
  "--timeout", "60"
]

puts "+ #{ips_command.shelljoin}"
unless system(ips_command.shelljoin)
  puts "Failed to execute: #{ips_command.shelljoin}"
end

puts "+ #{rsskb_command.shelljoin}"
unless system(rsskb_command.shelljoin)
  puts "Failed to execute: #{rsskb_command.shelljoin}"
end


text:
class Solution(object):
    def getModifiedArray(self, length, updates):
        """
        :type length: int
        :type updates: List[List[int]]
        :rtype: List[int]
        """
        ans = [0] * length
        for update in updates:
          startIndex = update[0]
          endIndex = update[1]
          inc = update[2]
          for i in range(startIndex, endIndex+1):
            ans[i] += inc
        return ans


text:
charset UTF-8
script alert('Hello World!');


text:
package nl.tudelft.jpacman.util;

import java.util.TimerTask;

/**
 * Task that can be cloneable
 * @author Corentin Ducruet
 */
public abstract class TimerTaskCloneable extends TimerTask implements Cloneable{

    public TimerTaskCloneable(){
        super();
    }

    public TimerTaskCloneable clone() throws CloneNotSupportedException {
        return (TimerTaskCloneable) super.clone();
    }

}


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

#import "PMAnimationQueue.h"

@interface PMAnimationQueue ()

@property (nonatomic, strong) NSMutableArray *animations;

@end

@implementation PMAnimationQueue

- (id) init
{
    self = [super init];
    if (self)
    {
        _animations = [NSMutableArray arrayWithCapacity:2];
    }
    return self;
}

- (void) addAnimationWithDelay:(NSTimeInterval)delay
						  options:(UIViewAnimationOptions)options
					 preAnimation:(NSTimeInterval(^)())preAnimation
						animation:(void(^)())animation
					   completion:(void (^)(BOOL finished))completion
{
    /* If nothing is currently animating, start the animation.
     * If something is currently animating the passed in animation
     * will execute in the completion block of the current animation.
     */

    __weak PMAnimationQueue	*weakSelf = self;

    [self.animations addObject: ^{

		void (^nextAnimation)(void) = ^
		{
			[weakSelf.animations removeObjectAtIndex:0];
			if (weakSelf.animations.count)
				((void (^)(void))weakSelf.animations[0])(); // Start next animation
		};

		NSTimeInterval duration = 0.0;
		if (preAnimation)
			duration = preAnimation();

		if (!animation)
		{
			if (completion)
				completion(NO);

			nextAnimation();
			return;
		}

		if (duration <= 0.0)
		{
			if (animation)
				animation();
			if (completion)
				completion(YES);

			nextAnimation();
			return;
		}

        [UIView animateWithDuration:duration
                              delay:delay
                            options:options
                         animations:animation
                         completion:^(BOOL finished)
         {
             if(completion)
                 completion(finished);

			 nextAnimation();
         }];
    }];

    if (self.animations.count == 1)
        ((void (^)(void))self.animations[0])(); // Kick off the first animation
}

- (NSUInteger) animationCount
{
	return self.animations.count;
}

@end


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;

namespace Gaming.Game
{
	public class DataAssetCache
	{
		private DataAssetTree m_DataAssetTree;

		private Dictionary<Type, Dictionary<string, GameObject>> m_AssetCache = new Dictionary<Type, Dictionary<string, GameObject>>();

		private static DataAssetCache s_GlobalAssetCache = new DataAssetCache();

		public static DataAssetCache Instance
		{
			get
			{
				return s_GlobalAssetCache;
			}
		}

		private DataAssetCache()
		{
		}

		public void SetAssetTree(DataAssetTree dataAssetTree)
		{
			m_DataAssetTree = dataAssetTree;
		}

		public bool AssetExists(Type gameObjectType, string assetName)
		{
			string pathToAsset = m_DataAssetTree.GetPathToAsset(gameObjectType.Name, assetName);
			if (pathToAsset == null)
			{
				return false;
			}

			return true;
		}

		public GameObject GetCopyOfAsset(Type gameObjectType, string assetName)
		{
			// TODO: this code below seems like it should work and would be better (use the copy of the asset in the cache).
			/*
			GameObject asset = GetAsset(GameObjectType, AssetName);
			MemoryStream memoryStream = new MemoryStream();

			XmlTextWriter xmlWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
			asset.SaveXML(xmlWriter);

			memoryStream.Position = 0;

			XmlTextReader xmlReader = new XmlTextReader(memoryStream);
			return GameObject.Load(xmlReader);
			 */

			string pathToAsset = m_DataAssetTree.GetPathToAsset(gameObjectType.Name, assetName);
			return LoadGameObjectFromDisk(gameObjectType, assetName, pathToAsset);
		}

		public GameObject GetAsset(Type gameObjectType, string assetName)
		{
			if (assetName == null)
			{
				assetName = "!Default";
			}

			GameObject asset = GetAssetFromCache(gameObjectType, assetName);

			if (asset == null)
			{
				string pathToAsset = m_DataAssetTree.GetPathToAsset(gameObjectType.Name, assetName);

				if (pathToAsset == null)
				{
					if (assetName == "!Default")
					{
						// we are trying to load the default item and we don't have one yet.
						ConstructorInfo constructInfo = gameObjectType.GetConstructor(Type.EmptyTypes);
						if (constructInfo == null)
						{
							throw new Exception("You must have a default constructor defined for '" + gameObjectType.Name + "' for default game object creation to work.");
						}

						var defaultGameObjectItem = (GameObject)constructInfo.Invoke(null);
						string defaultAssetPath = m_DataAssetTree.Root + Path.DirectorySeparatorChar + "Default";
						if (!Directory.Exists(defaultAssetPath))
						{
							Directory.CreateDirectory(defaultAssetPath);
						}

						string pathName = defaultAssetPath + Path.DirectorySeparatorChar + assetName + "." + gameObjectType.Name;
						defaultGameObjectItem.SaveXML(pathName);

						AddAssetToCache(gameObjectType, assetName, defaultGameObjectItem);
						return defaultGameObjectItem;
					}
					else
					{
						throw new Exception("'" + gameObjectType.Name + "' named '" + assetName + "' does not exist.");
					}
				}

				GameObject gameObjectItem = LoadGameObjectFromDisk(gameObjectType, assetName, pathToAsset);

				AddAssetToCache(gameObjectType, assetName, gameObjectItem);

				return gameObjectItem;
			}

			return asset;
		}

		private static GameObject LoadGameObjectFromDisk(Type gameObjectType, string assetName, string pathToAsset)
		{
			var paramsLoadTakes = new Type[] { typeof(string) };
			// TODO: more checking for right function. Must be static must return a GameObject.
			MethodInfo loadFunction = gameObjectType.GetMethod("Load", paramsLoadTakes);

			if (loadFunction == null)
			{
				throw new Exception("You must implement the load function on '" + gameObjectType.Name + "'.\n"
					+ "It will look like this, \n 'public new static GameObject Load(String PathName)'.");
			}

			object[] paramsToCallLoadWith = new object[] { pathToAsset };
			GameObject gameObjectItem;
			try
			{
				gameObjectItem = (GameObject)loadFunction.Invoke(null, paramsToCallLoadWith);
			}
			catch (Exception e)
			{
				throw e.InnerException;
			}

			if (gameObjectItem == null)
			{
				throw new Exception("The load failed for the '" + gameObjectType.Name + "' named '" + assetName + "'.");
			}

			return gameObjectItem;
		}

		private GameObject GetAssetFromCache(Type gameObjectType, string assetName)
		{
			if (m_AssetCache.TryGetValue(gameObjectType, out Dictionary<string, GameObject> gameObjectClassDictionary))
			{
				if (gameObjectClassDictionary.TryGetValue(assetName, out GameObject gameObjectItem))
				{
					return gameObjectItem;
				}
			}

			return null;
		}

		private void AddAssetToCache(Type gameObjectType, string assetName, GameObject asset)
		{
			if (!m_AssetCache.TryGetValue(gameObjectType, out Dictionary<string, GameObject> gameObjectClassDictionary))
			{
				// create the dictionary
				gameObjectClassDictionary = new Dictionary<string, GameObject>();
				m_AssetCache.Add(gameObjectType, gameObjectClassDictionary);
			}

			if (gameObjectClassDictionary.TryGetValue(assetName, out GameObject itemInCach))
			{
				throw new Exception("The '" + gameObjectType.Name + "' asset named '" + assetName + "' is already in the cache.");
			}

			gameObjectClassDictionary.Add(assetName, asset);
		}

		public void ModifyOrCreateAsset(GameObject assetToSave, string desiredPathHint, string assetName)
		{
			if (AssetExists(assetToSave.GetType(), assetName))
			{
				// re-save it
				string pathToAsset = m_DataAssetTree.GetPathToAsset(assetToSave.GetType().Name, assetName);
				assetToSave.SaveXML(pathToAsset);
			}
			else
			{
				// create the file and save the asset
				string desiredAssetPath = m_DataAssetTree.Root + Path.DirectorySeparatorChar + desiredPathHint;
				if (!Directory.Exists(desiredAssetPath))
				{
					Directory.CreateDirectory(desiredAssetPath);
				}

				string pathName = desiredAssetPath + Path.DirectorySeparatorChar + assetName + "." + assetToSave.GetType().Name;
				assetToSave.SaveXML(pathName);

				AddAssetToCache(assetToSave.GetType(), assetName, assetToSave);
				m_DataAssetTree.AddItemToTree(pathName);
			}
		}
	}
}


text:
import React from 'react';
import styled from '@emotion/styled';
import PropTypes from 'prop-types';

import {addErrorMessage} from 'app/actionCreators/indicator';
import Well from 'app/components/well';
import {AVATAR_URL_MAP} from 'app/constants';
import {t, tct} from 'app/locale';
import {AvatarUser} from 'app/types';

const resizerPositions = {
  nw: ['top', 'left'],
  ne: ['top', 'right'],
  se: ['bottom', 'right'],
  sw: ['bottom', 'left'],
};

type Position = keyof typeof resizerPositions;

type Model = Pick<AvatarUser, 'avatar'>;

type Props = {
  model: Model;
  updateDataUrlState: (opts: {savedDataUrl?: string | null; dataUrl?: string}) => void;
  type: 'user' | 'team' | 'organization' | 'project';
  savedDataUrl?: string;
};

type State = {
  file: File | null;
  objectURL: string | null;
  mousePosition: {pageX: number; pageY: number};
  resizeDimensions: {top: number; left: number; size: number};
  resizeDirection: Position | null;
};

class AvatarCropper extends React.Component<Props, State> {
  static propTypes = {
    model: PropTypes.object.isRequired,
    updateDataUrlState: PropTypes.func.isRequired,
    type: PropTypes.oneOf(['user', 'team', 'organization', 'project']),
    savedDataUrl: PropTypes.string,
  };

  state: State = {
    file: null,
    objectURL: null,
    mousePosition: {pageX: 0, pageY: 0},
    resizeDimensions: {top: 0, left: 0, size: 0},
    resizeDirection: null,
  };

  componentWillUnmount() {
    this.revokeObjectUrl();
  }

  file = React.createRef<HTMLInputElement>();
  canvas = React.createRef<HTMLCanvasElement>();
  image = React.createRef<HTMLImageElement>();
  cropContainer = React.createRef<HTMLDivElement>();

  // These values must be synced with the avatar endpoint in backend.
  MIN_DIMENSION = 256;
  MAX_DIMENSION = 1024;
  ALLOWED_MIMETYPES = 'image/gif,image/jpeg,image/png';

  onSelectFile = (ev: React.ChangeEvent<HTMLInputElement>) => {
    const file = ev.target.files && ev.target.files[0];

    // No file selected (e.g. user clicked "cancel")
    if (!file) {
      return;
    }

    if (!/^image\//.test(file.type)) {
      addErrorMessage(t('That is not a supported file type.'));
      return;
    }

    this.revokeObjectUrl();

    const {updateDataUrlState} = this.props;
    const objectURL = window.URL.createObjectURL(file);
    this.setState({file, objectURL}, () => updateDataUrlState({savedDataUrl: null}));
  };

  revokeObjectUrl = () =>
    this.state.objectURL && window.URL.revokeObjectURL(this.state.objectURL);

  onImageLoad = () => {
    const error = this.validateImage();
    if (error) {
      this.revokeObjectUrl();
      this.setState({objectURL: null});
      addErrorMessage(error);
      return;
    }

    const image = this.image.current;
    if (!image) {
      return;
    }

    const dimension = Math.min(image.clientHeight, image.clientWidth);
    const state = {resizeDimensions: {size: dimension, top: 0, left: 0}};

    this.setState(state, this.drawToCanvas);
  };

  updateDimensions = (ev: MouseEvent) => {
    const cropContainer = this.cropContainer.current;
    if (!cropContainer) {
      return;
    }

    const {mousePosition, resizeDimensions} = this.state;

    let pageY = ev.pageY;
    let pageX = ev.pageX;
    let top = resizeDimensions.top + (pageY - mousePosition.pageY);
    let left = resizeDimensions.left + (pageX - mousePosition.pageX);

    if (top < 0) {
      top = 0;
      pageY = mousePosition.pageY;
    } else if (top + resizeDimensions.size > cropContainer.clientHeight) {
      top = cropContainer.clientHeight - resizeDimensions.size;
      pageY = mousePosition.pageY;
    }

    if (left < 0) {
      left = 0;
      pageX = mousePosition.pageX;
    } else if (left + resizeDimensions.size > cropContainer.clientWidth) {
      left = cropContainer.clientWidth - resizeDimensions.size;
      pageX = mousePosition.pageX;
    }

    this.setState(state => ({
      resizeDimensions: {...state.resizeDimensions, top, left},
      mousePosition: {pageX, pageY},
    }));
  };

  onMouseDown = (ev: React.MouseEvent<HTMLDivElement>) => {
    ev.preventDefault();
    this.setState({mousePosition: {pageY: ev.pageY, pageX: ev.pageX}});

    document.addEventListener('mousemove', this.updateDimensions);
    document.addEventListener('mouseup', this.onMouseUp);
  };

  onMouseUp = (ev: MouseEvent) => {
    ev.preventDefault();
    document.removeEventListener('mousemove', this.updateDimensions);
    document.removeEventListener('mouseup', this.onMouseUp);
    this.drawToCanvas();
  };

  startResize = (direction: Position, ev: React.MouseEvent<HTMLDivElement>) => {
    ev.stopPropagation();
    ev.preventDefault();
    document.addEventListener('mousemove', this.updateSize);
    document.addEventListener('mouseup', this.stopResize);

    this.setState({
      resizeDirection: direction,
      mousePosition: {pageY: ev.pageY, pageX: ev.pageX},
    });
  };

  stopResize = (ev: MouseEvent) => {
    ev.stopPropagation();
    ev.preventDefault();
    document.removeEventListener('mousemove', this.updateSize);
    document.removeEventListener('mouseup', this.stopResize);

    this.setState({resizeDirection: null});
    this.drawToCanvas();
  };

  updateSize = (ev: MouseEvent) => {
    const cropContainer = this.cropContainer.current;
    if (!cropContainer) {
      return;
    }

    const {mousePosition} = this.state;

    const yDiff = ev.pageY - mousePosition.pageY;
    const xDiff = ev.pageX - mousePosition.pageX;

    this.setState({
      resizeDimensions: this.getNewDimensions(cropContainer, yDiff, xDiff),
      mousePosition: {pageX: ev.pageX, pageY: ev.pageY},
    });
  };

  // Normalize diff across dimensions so that negative diffs are always making
  // the cropper smaller and positive ones are making the cropper larger
  getDiffNW = (yDiff: number, xDiff: number) =>
    (yDiff - yDiff * 2 + (xDiff - xDiff * 2)) / 2;

  getDiffNE = (yDiff: number, xDiff: number) => (yDiff - yDiff * 2 + xDiff) / 2;

  getDiffSW = (yDiff: number, xDiff: number) => (yDiff + (xDiff - xDiff * 2)) / 2;

  getDiffSE = (yDiff: number, xDiff: number) => (yDiff + xDiff) / 2;

  getNewDimensions = (container: HTMLDivElement, yDiff: number, xDiff: number) => {
    const {resizeDimensions: oldDimensions, resizeDirection} = this.state;

    const diff = this['getDiff' + resizeDirection!.toUpperCase()](yDiff, xDiff);

    let height = container.clientHeight - oldDimensions.top;
    let width = container.clientWidth - oldDimensions.left;

    // Depending on the direction, we update different dimensions:
    // nw: size, top, left
    // ne: size, top
    // sw: size, left
    // se: size
    const editingTop = resizeDirection === 'nw' || resizeDirection === 'ne';
    const editingLeft = resizeDirection === 'nw' || resizeDirection === 'sw';

    const newDimensions = {
      top: 0,
      left: 0,
      size: oldDimensions.size + diff,
    };

    if (editingTop) {
      newDimensions.top = oldDimensions.top - diff;
      height = container.clientHeight - newDimensions.top;
    }

    if (editingLeft) {
      newDimensions.left = oldDimensions.left - diff;
      width = container.clientWidth - newDimensions.left;
    }

    if (newDimensions.top < 0) {
      newDimensions.size = newDimensions.size + newDimensions.top;
      if (editingLeft) {
        newDimensions.left = newDimensions.left - newDimensions.top;
      }
      newDimensions.top = 0;
    }

    if (newDimensions.left < 0) {
      newDimensions.size = newDimensions.size + newDimensions.left;
      if (editingTop) {
        newDimensions.top = newDimensions.top - newDimensions.left;
      }
      newDimensions.left = 0;
    }

    const maxSize = Math.min(width, height);
    if (newDimensions.size > maxSize) {
      if (editingTop) {
        newDimensions.top = newDimensions.top + newDimensions.size - maxSize;
      }
      if (editingLeft) {
        newDimensions.left = newDimensions.left + newDimensions.size - maxSize;
      }
      newDimensions.size = maxSize;
    } else if (newDimensions.size < this.MIN_DIMENSION) {
      if (editingTop) {
        newDimensions.top = newDimensions.top + newDimensions.size - this.MIN_DIMENSION;
      }
      if (editingLeft) {
        newDimensions.left = newDimensions.left + newDimensions.size - this.MIN_DIMENSION;
      }
      newDimensions.size = this.MIN_DIMENSION;
    }

    return {...oldDimensions, ...newDimensions};
  };

  validateImage() {
    const img = this.image.current;

    if (!img) {
      return null;
    }

    if (img.naturalWidth < this.MIN_DIMENSION || img.naturalHeight < this.MIN_DIMENSION) {
      return tct('Please upload an image larger than [size]px by [size]px.', {
        size: this.MIN_DIMENSION - 1,
      });
    }

    if (img.naturalWidth > this.MAX_DIMENSION || img.naturalHeight > this.MAX_DIMENSION) {
      return tct('Please upload an image smaller than [size]px by [size]px.', {
        size: this.MAX_DIMENSION,
      });
    }

    return null;
  }

  drawToCanvas() {
    const canvas = this.canvas.current;
    if (!canvas) {
      return;
    }

    const image = this.image.current;
    if (!image) {
      return;
    }

    const {left, top, size} = this.state.resizeDimensions;
    // Calculate difference between natural dimensions and rendered dimensions
    const ratio =
      (image.naturalHeight / image.clientHeight +
        image.naturalWidth / image.clientWidth) /
      2;
    canvas.width = size * ratio;
    canvas.height = size * ratio;

    canvas
      .getContext('2d')!
      .drawImage(
        image,
        left * ratio,
        top * ratio,
        size * ratio,
        size * ratio,
        0,
        0,
        size * ratio,
        size * ratio
      );

    this.props.updateDataUrlState({dataUrl: canvas.toDataURL()});
  }

  get imageSrc() {
    const {savedDataUrl, model, type} = this.props;
    const uuid = model.avatar?.avatarUuid;
    const photoUrl = uuid && `/${AVATAR_URL_MAP[type] || 'avatar'}/${uuid}/`;

    return savedDataUrl || this.state.objectURL || photoUrl;
  }

  uploadClick = (ev: React.MouseEvent<HTMLAnchorElement>) => {
    ev.preventDefault();
    this.file.current && this.file.current.click();
  };

  renderImageCrop() {
    const src = this.imageSrc;
    if (!src) {
      return null;
    }

    const {resizeDimensions, resizeDirection} = this.state;
    const style = {
      top: resizeDimensions.top,
      left: resizeDimensions.left,
      width: resizeDimensions.size,
      height: resizeDimensions.size,
    };

    return (
      <ImageCropper resizeDirection={resizeDirection}>
        <CropContainer ref={this.cropContainer}>
           e.preventDefault()}
          />
          <Cropper style={style} onMouseDown={this.onMouseDown}>
            {Object.keys(resizerPositions).map(pos => (
              <Resizer
                key={pos}
                position={pos as Position}
                onMouseDown={this.startResize.bind(this, pos)}
              />
            ))}
          </Cropper>
        </CropContainer>
      </ImageCropper>
    );
  }

  render() {
    const src = this.imageSrc;

    const upload = ;
    const uploader = (
      <Well hasImage centered>

{tct('[upload:Upload a photo] to get started.', {upload})}

      </Well>
    );

    return (
      <React.Fragment>
        {!src && uploader}
        {src && <HiddenCanvas ref={this.canvas} />}
        {this.renderImageCrop()}

          {src && {t('Change Photo')}}
          <UploadInput
            ref={this.file}
            type="file"
            accept={this.ALLOWED_MIMETYPES}
            onChange={this.onSelectFile}
          />

      </React.Fragment>
    );
  }
}

export default AvatarCropper;

const UploadInput = styled('input')`
  position: absolute;
  opacity: 0;
`;

const ImageCropper = styled('div')<{resizeDirection: Position | null}>`
  cursor: ${p => (p.resizeDirection ? `${p.resizeDirection}-resize` : 'default')};
  text-align: center;
  margin-bottom: 20px;
  background-size: 20px 20px;
  background-position: 0 0, 0 10px, 10px -10px, -10px 0px;
  background-color: ${p => p.theme.background};
  background-image: linear-gradient(45deg, #eee 25%, rgba(0, 0, 0, 0) 25%),
    linear-gradient(-45deg, #eee 25%, rgba(0, 0, 0, 0) 25%),
    linear-gradient(45deg, rgba(0, 0, 0, 0) 75%, #eee 75%),
    linear-gradient(-45deg, rgba(0, 0, 0, 0) 75%, #eee 75%);
`;

const CropContainer = styled('div')`
  display: inline-block;
  position: relative;
  max-width: 100%;
`;

const Cropper = styled('div')`
  position: absolute;
  border: 2px dashed ${p => p.theme.gray300};
`;

const Resizer = styled('div')<{position: Position}>`
  border-radius: 5px;
  width: 10px;
  height: 10px;
  position: absolute;
  background-color: ${p => p.theme.gray300};
  cursor: ${p => `${p.position}-resize`};
  ${p => resizerPositions[p.position].map(pos => `${pos}: -5px;`)}
`;

const HiddenCanvas = styled('canvas')`
  display: none;
`;


text:
<?php

class NFe_TestCase extends UnitTestCase {
  public function __construct() {
    $apiKey = getenv('NFE_API_KEY');
    NFe_io::setApiKey($apiKey);
  }
}


text:
package io.grpc;

import com.google.common.base.Preconditions;
import java.io.File;
import java.io.InputStream;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;

/**
 * A builder for {@link Server} instances.
 *
 * @param <T> The concrete type of this builder.
 * @since 1.0.0
 */
public abstract class ServerBuilder<T extends ServerBuilder<T>> {

  /**
   * Static factory for creating a new ServerBuilder.
   *
   * @param port the port to listen on
   * @since 1.0.0
   */
  public static ServerBuilder<?> forPort(int port) {
    return ServerProvider.provider().builderForPort(port);
  }

  /**
   * Execute application code directly in the transport thread.
   *
   *
Depending on the underlying transport, using a direct executor may lead to substantial
   * performance improvements. However, it also requires the application to not block under
   * any circumstances.
   *
   *
Calling this method is semantically equivalent to calling {@link #executor(Executor)} and
   * passing in a direct executor. However, this is the preferred way as it may allow the transport
   * to perform special optimizations.
   *
   * @return this
   * @since 1.0.0
   */
  public abstract T directExecutor();

  /**
   * Provides a custom executor.
   *
   *
It's an optional parameter. If the user has not provided an executor when the server is
   * built, the builder will use a static cached thread pool.
   *
   *
The server won't take ownership of the given executor. It's caller's responsibility to
   * shut down the executor when it's desired.
   *
   * @return this
   * @since 1.0.0
   */
  public abstract T executor(@Nullable Executor executor);

  /**
   * Adds a service implementation to the handler registry.
   *
   * @param service ServerServiceDefinition object
   * @return this
   * @since 1.0.0
   */
  public abstract T addService(ServerServiceDefinition service);

  /**
   * Adds a service implementation to the handler registry. If bindableService implements
   * {@link InternalNotifyOnServerBuild}, the service will receive a reference to the generated
   * server instance upon build().
   *
   * @param bindableService BindableService object
   * @return this
   * @since 1.0.0
   */
  public abstract T addService(BindableService bindableService);

  /**
   * Adds a {@link ServerInterceptor} that is run for all services on the server.  Interceptors
   * added through this method always run before per-service interceptors added through {@link
   * ServerInterceptors}.  Interceptors run in the reverse order in which they are added.
   *
   * @param interceptor the all-service interceptor
   * @return this
   * @since 1.5.0
   */
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/3117")
  public T intercept(ServerInterceptor interceptor) {
    throw new UnsupportedOperationException();
  }

  /**
   * Adds a {@link ServerTransportFilter}. The order of filters being added is the order they will
   * be executed.
   *
   * @return this
   * @since 1.2.0
   */
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/2132")
  public T addTransportFilter(ServerTransportFilter filter) {
    throw new UnsupportedOperationException();
  }

  /**
   * Adds a {@link ServerStreamTracer.Factory} to measure server-side traffic.  The order of
   * factories being added is the order they will be executed.
   *
   * @return this
   * @since 1.3.0
   */
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/2861")
  public T addStreamTracerFactory(ServerStreamTracer.Factory factory) {
    throw new UnsupportedOperationException();
  }

  /**
   * Sets a fallback handler registry that will be looked up in if a method is not found in the
   * primary registry. The primary registry (configured via {@code addService()}) is faster but
   * immutable. The fallback registry is more flexible and allows implementations to mutate over
   * time and load services on-demand.
   *
   * @return this
   * @since 1.0.0
   */
  public abstract T fallbackHandlerRegistry(@Nullable HandlerRegistry fallbackRegistry);

  /**
   * Makes the server use TLS.
   *
   * @param certChain file containing the full certificate chain
   * @param privateKey file containing the private key
   *
   * @return this
   * @throws UnsupportedOperationException if the server does not support TLS.
   * @since 1.0.0
   */
  public abstract T useTransportSecurity(File certChain, File privateKey);

  /**
   * Makes the server use TLS.
   *
   * @param certChain InputStream containing the full certificate chain
   * @param privateKey InputStream containing the private key
   *
   * @return this
   * @throws UnsupportedOperationException if the server does not support TLS, or does not support
   *         reading these files from an InputStream.
   * @since 1.12.0
   */
  public T useTransportSecurity(InputStream certChain, InputStream privateKey) {
    throw new UnsupportedOperationException();
  }

  /**
   * Set the decompression registry for use in the channel.  This is an advanced API call and
   * shouldn't be used unless you are using custom message encoding.   The default supported
   * decompressors are in {@code DecompressorRegistry.getDefaultInstance}.
   *
   * @return this
   * @since 1.0.0
   */
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1704")
  public abstract T decompressorRegistry(@Nullable DecompressorRegistry registry);

  /**
   * Set the compression registry for use in the channel.  This is an advanced API call and
   * shouldn't be used unless you are using custom message encoding.   The default supported
   * compressors are in {@code CompressorRegistry.getDefaultInstance}.
   *
   * @return this
   * @since 1.0.0
   */
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1704")
  public abstract T compressorRegistry(@Nullable CompressorRegistry registry);

  /**
   * Sets the permitted time for new connections to complete negotiation handshakes before being
   * killed.
   *
   * @return this
   * @throws IllegalArgumentException if timeout is negative
   * @throws UnsupportedOperationException if unsupported
   * @since 1.8.0
   */
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/3706")
  public T handshakeTimeout(long timeout, TimeUnit unit) {
    throw new UnsupportedOperationException();
  }

  /**
   * Sets the maximum message size allowed to be received on the server. If not called,
   * defaults to 4 MiB. The default provides protection to servers who haven't considered the
   * possibility of receiving large messages while trying to be large enough to not be hit in normal
   * usage.
   *
   *
This method is advisory, and implementations may decide to not enforce this.  Currently,
   * the only known transport to not enforce this is {@code InProcessServer}.
   *
   * @param bytes the maximum number of bytes a single message can be.
   * @return this
   * @throws IllegalArgumentException if bytes is negative.
   * @throws UnsupportedOperationException if unsupported.
   * @since 1.13.0
   */
  public T maxInboundMessageSize(int bytes) {
    // intentional noop rather than throw, this method is only advisory.
    Preconditions.checkArgument(bytes >= 0, "bytes must be >= 0");
    return thisT();
  }

  /**
   * Sets the maximum size of metadata allowed to be received. {@code Integer.MAX_VALUE} disables
   * the enforcement. The default is implementation-dependent, but is not generally less than 8 KiB
   * and may be unlimited.
   *
   *
This is cumulative size of the metadata. The precise calculation is
   * implementation-dependent, but implementations are encouraged to follow the calculation used for
   *
   * HTTP/2's SETTINGS_MAX_HEADER_LIST_SIZE. It sums the bytes from each entry's key and value,
   * plus 32 bytes of overhead per entry.
   *
   * @param bytes the maximum size of received metadata
   * @return this
   * @throws IllegalArgumentException if bytes is non-positive
   * @since 1.17.0
   */
  public T maxInboundMetadataSize(int bytes) {
    Preconditions.checkArgument(bytes > 0, "maxInboundMetadataSize must be > 0");
    // intentional noop rather than throw, this method is only advisory.
    return thisT();
  }

  /**
   * Sets the BinaryLog object that this server should log to. The server does not take
   * ownership of the object, and users are responsible for calling {@link BinaryLog#close()}.
   *
   * @param binaryLog the object to provide logging.
   * @return this
   * @since 1.13.0
   */
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/4017")
  public T setBinaryLog(BinaryLog binaryLog) {
    throw new UnsupportedOperationException();
  }

  /**
   * Builds a server using the given parameters.
   *
   *
The returned service will not been started or be bound a port. You will need to start it
   * with {@link Server#start()}.
   *
   * @return a new Server
   * @since 1.0.0
   */
  public abstract Server build();

  /**
   * Returns the correctly typed version of the builder.
   */
  private T thisT() {
    @SuppressWarnings("unchecked")
    T thisT = (T) this;
    return thisT;
  }
}


text:
{% if not isDrawn %}

Select Field or Farm of Interest

Zoom in to your farm using the map on the left. Then outline the field or farm area of pollinator-dependent crop(s) that you would like to evaluate. Only one area of 400 acres or less can be drawn at a time. Fields or farms should not be smaller than 100 ft × 100 ft.

{% endif %}

    {% if not isDrawing and not isDrawn %}
        <button id="start-drawing" class="btn btn-active btn-lg btn-block" type="button">Start drawing</button>
    {% endif %}
    {% if isDrawing %}
        <button id="cancel-drawing" class="btn btn-lg btn-block" type="button">Cancel drawing</button>
    {% endif %}

{% if isDrawn %}

Confirm or Redraw Area

        Does this selected area look correct? Are there pollinator-dependent crops in the selected area? If yes, click Confirm to continue. If you would like to change the selected area, click Redraw Area.

    Confirm
    <button id="cancel-drawing" class="btn btn-secondary btn-lg btn-block" type="button">Redraw Area</button>
{% endif %}