text:
require 'openssl'
require 'uri'
require 'faraday'

module Percy
  class Client
    module Connection
      class NiceErrorMiddleware < Faraday::Response::Middleware
        CLIENT_ERROR_STATUS_RANGE = 400...600

        def on_complete(env)
          error_class = nil

          case env[:status]
          when 400
            error_class = Percy::Client::BadRequestError
          when 401
            error_class = Percy::Client::UnauthorizedError
          when 402
            error_class = Percy::Client::PaymentRequiredError
          when 403
            error_class = Percy::Client::ForbiddenError
          when 404
            error_class = Percy::Client::NotFoundError
          when 409
            error_class = Percy::Client::ConflictError
          when 500
            error_class = Percy::Client::InternalServerError
          when 502
            error_class = Percy::Client::BadGatewayError
          when 503
            error_class = Percy::Client::ServiceUnavailableError
          when 504
            error_class = Percy::Client::GatewayTimeoutError
          when 520..530
            error_class = Percy::Client::CloudflareError
          when CLIENT_ERROR_STATUS_RANGE # Catchall.
            error_class = Percy::Client::HttpError
          end

          return unless error_class

          raise error_class.new(
            env.status, env.method.upcase, env.url, env.body,
            "Got #{env.status} (#{env.method.upcase} #{env.url}):\n#{env.body}",
          )
        end
      end

      def connection
        return @connection if defined?(@connection)

        parsed_uri = URI.parse(config.api_url)
        base_url = "#{parsed_uri.scheme}://#{parsed_uri.host}:#{parsed_uri.port}"

        @connection = Faraday.new(url: base_url) do |faraday|
          faraday.request :token_auth, config.access_token if config.access_token
          faraday.use Percy::Client::Connection::NiceErrorMiddleware
          faraday.adapter :excon
        end

        @connection
      end

      def get(path, options = {})
        retries = options[:retries] || 3

        begin
          response = connection.get do |request|
            request.url(path)
            request.headers.merge! _headers
          end
        rescue Faraday::TimeoutError
          raise Percy::Client::TimeoutError
        rescue Faraday::ConnectionFailed
          raise Percy::Client::ConnectionFailed
        rescue Percy::Client::ServerError => e
          # Retry on 5XX errors.
          if (retries -= 1) >= 0
            sleep(rand(1..3))
            retry
          end
          raise e
        end
        JSON.parse(response.body)
      end

      def post(path, data, options = {})
        retries = options[:retries] || 3

        begin
          response = connection.post do |request|
            request.url(path)
            request.headers.merge! _headers
            request.body = data.to_json
          end
        rescue Faraday::TimeoutError
          if (retries -= 1) >= 0
            retry
          end
          raise Percy::Client::TimeoutError
        rescue Faraday::ConnectionFailed
          raise Percy::Client::ConnectionFailed
        rescue Percy::Client::ServerError => e
          # Retry on 5XX errors.
          if (retries -= 1) >= 0
            sleep(rand(1..3))
            retry
          end

          raise e
        end

        JSON.parse(response.body)
      end

      def _headers
        {
          'Content-Type' => 'application/vnd.api+json',
          'User-Agent' => _user_agent,
        }
      end

      def _user_agent
        @_user_agent ||= begin
          client = [
            "Percy/#{_api_version}",
            client_info,
            "percy-client/#{VERSION}",
          ].compact.join(' ')

          environment = [
            environment_info,
            "ruby/#{_ruby_version}",
            Percy::Client::Environment.ci_info,
          ].compact.join('; ')

          "#{client} (#{environment})"
        end
      end

      def _reset_user_agent
        @_user_agent = nil
      end

      def _api_version
        config.api_url.match(/\w+$/).to_s
      end

      def _ruby_version
        "#{RUBY_VERSION}p#{RUBY_PATCHLEVEL}"
      end
    end
  end
end


text:
package com.google.common.base;

import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.VisibleForTesting;

/**
 * Utility class for converting between various ASCII case formats.
 *
 * @author Mike Bostock
 * @since 1
 */
@GwtCompatible
public enum CaseFormat {
  /**
   * Hyphenated variable naming convention, e.g., "lower-hyphen".
   */
  LOWER_HYPHEN(CharMatcher.is('-'), "-"),

  /**
   * C++ variable naming convention, e.g., "lower_underscore".
   */
  LOWER_UNDERSCORE(CharMatcher.is('_'), "_"),

  /**
   * Java variable naming convention, e.g., "lowerCamel".
   */
  LOWER_CAMEL(CharMatcher.inRange('A', 'Z'), ""),

  /**
   * Java and C++ class naming convention, e.g., "UpperCamel".
   */
  UPPER_CAMEL(CharMatcher.inRange('A', 'Z'), ""),

  /**
   * Java and C++ constant naming convention, e.g., "UPPER_UNDERSCORE".
   */
  UPPER_UNDERSCORE(CharMatcher.is('_'), "_");

  private final CharMatcher wordBoundary;
  private final String wordSeparator;

  CaseFormat(CharMatcher wordBoundary, String wordSeparator) {
    this.wordBoundary = wordBoundary;
    this.wordSeparator = wordSeparator;
  }

  /**
   * Converts the specified {@code String s} from this format to the specified {@code format}. A
   * "best effort" approach is taken; if {@code s} does not conform to the assumed format, then the
   * behavior of this method is undefined but we make a reasonable effort at converting anyway.
   */
  public String to(CaseFormat format, String s) {
    if (format == null) {
      throw new NullPointerException();
    }
    if (s == null) {
      throw new NullPointerException();
    }

    if (format == this) {
      return s;
    }

    /* optimize cases where no camel conversion is required */
    switch (this) {
      case LOWER_HYPHEN:
        switch (format) {
          case LOWER_UNDERSCORE:
            return s.replace('-', '_');
          case UPPER_UNDERSCORE:
            return toUpperCaseAscii(s.replace('-', '_'));
        }
        break;
      case LOWER_UNDERSCORE:
        switch (format) {
          case LOWER_HYPHEN:
            return s.replace('_', '-');
          case UPPER_UNDERSCORE:
            return toUpperCaseAscii(s);
        }
        break;
      case UPPER_UNDERSCORE:
        switch (format) {
          case LOWER_HYPHEN:
            return toLowerCaseAscii(s.replace('_', '-'));
          case LOWER_UNDERSCORE:
            return toLowerCaseAscii(s);
        }
        break;
    }

    // otherwise, deal with camel conversion
    StringBuilder out = null;
    int i = 0;
    int j = -1;
    while ((j = wordBoundary.indexIn(s, ++j)) != -1) {
      if (i == 0) {
        // include some extra space for separators
        out = new StringBuilder(s.length() + 4 * wordSeparator.length());
        out.append(format.normalizeFirstWord(s.substring(i, j)));
      } else {
        out.append(format.normalizeWord(s.substring(i, j)));
      }
      out.append(format.wordSeparator);
      i = j + wordSeparator.length();
    }
    if (i == 0) {
      return format.normalizeFirstWord(s);
    }
    out.append(format.normalizeWord(s.substring(i)));
    return out.toString();
  }

  private String normalizeFirstWord(String word) {
    switch (this) {
      case LOWER_CAMEL:
        return toLowerCaseAscii(word);
      default:
        return normalizeWord(word);
    }
  }

  private String normalizeWord(String word) {
    switch (this) {
      case LOWER_HYPHEN:
        return toLowerCaseAscii(word);
      case LOWER_UNDERSCORE:
        return toLowerCaseAscii(word);
      case LOWER_CAMEL:
        return firstCharOnlyToUpper(word);
      case UPPER_CAMEL:
        return firstCharOnlyToUpper(word);
      case UPPER_UNDERSCORE:
        return toUpperCaseAscii(word);
    }
    throw new RuntimeException("unknown case: " + this);
  }

  private static String firstCharOnlyToUpper(String word) {
    int length = word.length();
    if (length == 0) {
      return word;
    }
    return new StringBuilder(length)
        .append(charToUpperCaseAscii(word.charAt(0)))
        .append(toLowerCaseAscii(word.substring(1)))
        .toString();
  }

  @VisibleForTesting static String toUpperCaseAscii(String string) {
    int length = string.length();
    StringBuilder builder = new StringBuilder(length);
    for (int i = 0; i < length; i++) {
      builder.append(charToUpperCaseAscii(string.charAt(i)));
    }
    return builder.toString();
  }

  @VisibleForTesting static String toLowerCaseAscii(String string) {
    int length = string.length();
    StringBuilder builder = new StringBuilder(length);
    for (int i = 0; i < length; i++) {
      builder.append(charToLowerCaseAscii(string.charAt(i)));
    }
    return builder.toString();
  }

  private static char charToUpperCaseAscii(char c) {
    return isLowerCase(c) ? (char) (c & 0x5f) : c;
  }

  private static char charToLowerCaseAscii(char c) {
    return isUpperCase(c) ? (char) (c ^ 0x20) : c;
  }

  private static boolean isLowerCase(char c) {
    return (c >= 'a') && (c <= 'z');
  }

  private static boolean isUpperCase(char c) {
    return (c >= 'A') && (c <= 'Z');
  }
}

redpajama_set_name: RedPajamaGithub


text:
@implementation ProgressIndicator
{
    NSMutableArray* _buttons;
    NSMutableArray* _labels;
    UIView* _line;

    NSMutableDictionary* _indicatorFonts;
    NSMutableDictionary* _indicatorBorderColors;
    NSMutableDictionary* _indicatorBackgroundColors;
    NSMutableDictionary* _indicatorTitleColors;
    NSMutableDictionary* _captionFonts;
    NSMutableDictionary* _captionColor;
}
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        _buttons = [NSMutableArray new];
        _labels = [NSMutableArray new];
        _line = [UIView new];
        _line.tag = NSNotFound;
        [self addSubview:_line];

        _itemSize = CGSizeMake(30, 30);
        _contentInsets = UIEdgeInsetsMake(5, 5, 5, 5);

        [self setLineColor:[UIColor grayColor]];
    }
    return self;
}

+ (ProgressIndicator *)progressIndicatorWithFrame:(CGRect)frame andItemsCaption:(NSArray *)itemsCaption
{
    ProgressIndicator* indicator = [[ProgressIndicator alloc] initWithFrame:frame];
    indicator.itemsCaption = itemsCaption;
    return indicator;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    [self customLayoutSubviews];
}

- (void)customLayoutSubviews
{
    CGRect frame = self.bounds;

    int areaLength = frame.size.width - _contentInsets.left - _contentInsets.right - _itemSize.width;
    int beginX = _contentInsets.left + _itemSize.width/2;
    int between = areaLength/MAX(_numberOfItems-1, 1);

    for (int i = 0; i < _numberOfItems; i++) {
        UIButton* button = _buttons[i];
        button.frame = CGRectMake(0, 0, _itemSize.width, _itemSize.height);
        button.layer.cornerRadius = _itemSize.width/2;
        button.center = CGPointMake(beginX + between * i, _contentInsets.top + _itemSize.height/2);

        if (_labels.count > i) {
            UILabel* label = _labels[i];
            label.center = CGPointMake(button.center.x, button.frame.origin.y + button.frame.size.height + label.frame.size.height/2 + 1);
        }
    }

    _line.frame = CGRectMake(beginX, _contentInsets.top + _itemSize.height/2, areaLength, 1);
    [self sendSubviewToBack:_line];
}

#pragma mark - Setter:

- (void)setNumberOfItems:(NSUInteger)numberOfItems
{
    _numberOfItems = numberOfItems;
    [self add:numberOfItems buttonsWitCaptions:nil];
}

- (void)setItemsCaption:(NSArray *)itemsCaption
{
    _numberOfItems = itemsCaption.count;
    _itemsCaption = itemsCaption;

    [self add:itemsCaption.count buttonsWitCaptions:itemsCaption];
}

- (void)setSelectedItemAtIndex:(NSUInteger)selectedItemAtIndex
{
    _selectedItemAtIndex = selectedItemAtIndex;

    UIColor* indicatorBorderColor = [_indicatorBorderColors valueForKey:@(UIControlStateNormal).stringValue];
    UIFont* indicatorFont = [_indicatorFonts valueForKey:@(UIControlStateNormal).stringValue];
    UIColor* indicatorBackgroundColor = [_indicatorBackgroundColors valueForKey:@(UIControlStateNormal).stringValue];
    UIColor* titleColor = [_indicatorTitleColors valueForKey:@(UIControlStateNormal).stringValue];
    UIColor* captionColor = [_captionColor valueForKey:@(UIControlStateNormal).stringValue];
    UIFont* captionFont = [_captionFonts valueForKey:@(UIControlStateNormal).stringValue];

    UIColor* indicatorBorderColorSelected = [_indicatorBorderColors valueForKey:@(UIControlStateSelected).stringValue];
    UIFont* indicatorFontSelected = [_indicatorFonts valueForKey:@(UIControlStateSelected).stringValue];
    UIColor* indicatorBackgroundColorSelected = [_indicatorBackgroundColors valueForKey:@(UIControlStateSelected).stringValue];
    UIColor* titleColorSelected = [_indicatorTitleColors valueForKey:@(UIControlStateSelected).stringValue];
    UIColor* captionColorSelected = [_captionColor valueForKey:@(UIControlStateSelected).stringValue];
    UIFont* captionFontSelected = [_captionFonts valueForKey:@(UIControlStateSelected).stringValue];

    for (UIButton* indicator in _buttons) {
        if (indicator.tag == selectedItemAtIndex) {
            indicator.layer.borderColor = indicatorBorderColorSelected ? indicatorBorderColorSelected.CGColor : [UIColor darkGrayColor].CGColor;
            indicator.titleLabel.font = indicatorFontSelected ? indicatorFontSelected : [UIFont boldSystemFontOfSize:12];
            indicator.backgroundColor = indicatorBackgroundColorSelected ? indicatorBackgroundColorSelected : [UIColor darkGrayColor];
            [indicator setTitleColor:titleColorSelected?titleColorSelected:[UIColor whiteColor]
                            forState:UIControlStateNormal];
        }
        else
        {
            indicator.layer.borderColor = indicatorBorderColor ? indicatorBorderColor.CGColor : [UIColor grayColor].CGColor;
            indicator.titleLabel.font = indicatorFont ? indicatorFont : [UIFont systemFontOfSize:12];
            indicator.backgroundColor = indicatorBackgroundColor ? indicatorBackgroundColor : [UIColor whiteColor];
            [indicator setTitleColor:titleColor?titleColor:[UIColor darkGrayColor]
                            forState:UIControlStateNormal];
        }
    }

    for (UILabel* caption in _labels) {
        if (caption.tag == selectedItemAtIndex) {
            caption.font = captionFontSelected ? captionFontSelected : [UIFont boldSystemFontOfSize:10];
            caption.textColor = captionColorSelected ? captionColorSelected : [UIColor darkGrayColor];
        }
        else
        {
            caption.font = captionFont ? captionFont : [UIFont systemFontOfSize:10];
            caption.textColor = captionColor ? captionColor : [UIColor grayColor];
        }

        caption.text = _itemsCaption[caption.tag];
        [caption sizeToFit];
    }
}

- (void)setLineColor:(UIColor *)lineColor
{
    _line.backgroundColor = lineColor;
}

- (void)setItemSize:(CGSize)itemSize
{
    _itemSize = itemSize;
    [self customLayoutSubviews];
}

- (void)setContentInsets:(UIEdgeInsets)contentInsets
{
    _contentInsets = contentInsets;
    [self customLayoutSubviews];
}

#pragma mark - Customize UI

- (void)setIndicatorBorderColor:(UIColor *)color forState:(UIControlState)state
{
    if (_indicatorBorderColors == nil) {
        _indicatorBorderColors = [NSMutableDictionary dictionaryWithCapacity:MAX_EVENTS_COUNT];
    }

    [_indicatorBorderColors setValue:color
                              forKey:@(state).stringValue];
    [self setSelectedItemAtIndex:_selectedItemAtIndex];
}

- (void)setIndicatorBackgroundColor:(UIColor *)color forState:(UIControlState)state
{
    if (_indicatorBackgroundColors == nil) {
        _indicatorBackgroundColors = [NSMutableDictionary dictionaryWithCapacity:MAX_EVENTS_COUNT];
    }
    [_indicatorBackgroundColors setValue:color
                                  forKey:@(state).stringValue];
    [self setSelectedItemAtIndex:_selectedItemAtIndex];
}

- (void)setIndicatorTitleColor:(UIColor *)color forState:(UIControlState)state
{
    if (_indicatorTitleColors == nil) {
        _indicatorTitleColors = [NSMutableDictionary dictionaryWithCapacity:MAX_EVENTS_COUNT];
    }
    [_indicatorTitleColors setValue:color forKey:@(state).stringValue];
    [self setSelectedItemAtIndex:_selectedItemAtIndex];
}

- (void)setIndicatorTitleFont:(UIFont *)font forState:(UIControlState)state
{
    if (_indicatorFonts == nil) {
        _indicatorFonts = [NSMutableDictionary dictionaryWithCapacity:MAX_EVENTS_COUNT];
    }
    [_indicatorFonts setValue:font
                       forKey:@(state).stringValue];
    [self setSelectedItemAtIndex:_selectedItemAtIndex];
}

- (void)setCaptionColor:(UIColor *)color forState:(UIControlState)state
{
    if (_captionColor == nil) {
        _captionColor = [NSMutableDictionary dictionaryWithCapacity:MAX_EVENTS_COUNT];
    }
    [_captionColor setValue:color
                     forKey:@(state).stringValue];
    [self setSelectedItemAtIndex:_selectedItemAtIndex];
}

- (void)setCaptionFont:(UIFont *)font forState:(UIControlState)state
{
    if (_captionFonts == nil) {
        _captionFonts = [NSMutableDictionary dictionaryWithCapacity:MAX_EVENTS_COUNT];
    }
    [_captionFonts setValue:font
                     forKey:@(state).stringValue];
    [self setSelectedItemAtIndex:_selectedItemAtIndex];
}

#pragma mark - Control actions

- (void)didSelectItem:(UIButton *)itemButton
{
    [self setSelectedItemAtIndex:itemButton.tag];
    [self sendActionsForControlEvents:UIControlEventValueChanged];
}

#pragma mark - Helpers;

- (void)add:(NSUInteger)numberOfButtons buttonsWitCaptions:(NSArray *)captions
{
    for (UIView* subview in self.subviews) {
        if (subview != _line) {
            [subview removeFromSuperview];
        }
    }

    [_buttons removeLastObject];
    [_labels removeLastObject];

    _buttons = [NSMutableArray arrayWithCapacity:numberOfButtons];
    if (captions) {
        _labels = [NSMutableArray arrayWithCapacity:numberOfButtons];
    }

    for (int i = 0; i < numberOfButtons; i++)
    {
        UIButton* newButtonItem = [UIButton buttonWithType:UIButtonTypeCustom];
        newButtonItem.tag = i;
        newButtonItem.layer.borderWidth = 1.0f;
        [newButtonItem setTitle:@(i+1).stringValue forState:UIControlStateNormal];
        [_buttons addObject:newButtonItem];
        [self addSubview:newButtonItem];

        [newButtonItem addTarget:self
                          action:@selector(didSelectItem:)
                forControlEvents:UIControlEventTouchUpInside];

        if (captions.count > i) {
            UILabel* newCaptionLabel = [UILabel new];
            newCaptionLabel.tag = i;
            newCaptionLabel.backgroundColor = [UIColor clearColor];
            newCaptionLabel.textAlignment = NSTextAlignmentCenter;
            [self insertSubview:newCaptionLabel belowSubview:newButtonItem];
            [_labels addObject:newCaptionLabel];
        }
    }

    [self setSelectedItemAtIndex:_selectedItemAtIndex];

    [self customLayoutSubviews];
}

@end


text:
static _Bool initialized = false;

static void _strict_init() {
  if (initialized) {
    // Calling init multiple times is a programmer error.
    __builtin_trap();
  }
  initialized = true;
}

static void _strict_add(struct scheduler_work *unit) {
  if (!initialized) {
    // Calling API before initialization is programmer error.
    __builtin_trap();
  }

  if (!unit->callback) {
    // The work unit is invalid (NULL callback).
    __builtin_trap();
  }

  struct scheduler_work *search = &the_scheduler_head;
  do {
    if (search == unit) {
      // The work unit is already in the schedule.
      __builtin_trap();
    }
    search = search->later;
  } while(search);
}

static void _strict_remove(struct scheduler_work *unit) {
  if (!initialized) {
    // Calling API before initialization is programmer error.
    __builtin_trap();
  }

  struct scheduler_work *earlier_unit = &the_scheduler_head;
  // This loop is never entered in the common case.
  while(earlier_unit != NULL && earlier_unit->later != unit) {
    earlier_unit = earlier_unit->later;
  }
  if (!earlier_unit) {
    // The work unit was not in the schedule. This is a programmer error.
    __builtin_trap();
  }
}

#else

#define _strict_init()
#define _strict_add(unit)
#define _strict_remove(unit)

#endif


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RestSharp.Tests.SampleClasses
{
	public class TwilioCallList : List<Call>
	{
		public int Page { get; set; }
		public int NumPages { get; set; }
	}

	public class Call
	{
		public string Sid { get; set; }
	}
}


text:
import skbio.stats.ordination

def pcoa(distance_matrix: skbio.DistanceMatrix) -> skbio.OrdinationResults:
    return skbio.stats.ordination.pcoa(distance_matrix)


text:
package main

type UserResponse struct {
	BenisHistory [][]int32 `json:"benisHistory,omitempty"`
}

type UserSuggestResponse struct {
	Names []string `json:"names"`
}


text:
"""
9. Write a Python script in a different directory (not the one containing mytest).

    a. Verify that you can import mytest and call the three functions func1(), func2(), and func3().
    b. Create an object that uses MyClass. Verify that you call the hello() and not_hello() methods.
"""

from mytest import func1, func2, func3, MyClass

__author__ = 'Chip Hudgins'
__email__ = 'mudzi42@gmail.com'

def main():
    func1()
    func2()
    func3()

    song = MyClass('John', 'Paul', 'George', 'Ringo')
    song.not_hello()
    song.hello()

if __name__ == "__main__":
    main()


text:
function [vals, pos] = minandmax(f)
%MINANDMAX   Global minimum and maximum of a CLASSICFUN on [a,b].
%   VALS = MINANDMAX(F) returns a 2-vector, VALS = [MIN(F); MAX(F)], with the
%   global minimum and maximum of the CLASSICFUN F on [a,b].  If F is an array-valued
%   CLASSICFUN then VALS is a 2-by-M matrix, where M is the number of columns of F.
%   VALS(1, K) is the global minimum of the Kth column of F on [a,b], and
%   VALS(2, K) is the global maximum of the same.
%
%   [VALS, POS] = MINANDMAX(F) returns also the 2-vector POS where the minimum
%   and the maximum of F occur.
%
%   If F is complex-valued the absolute values are taken to determine extrema
%   but the output values correspond to those of the original function. That is,
%   VALS = FEVAL(F, POS) where [~, POS] = MINANDMAX(ABS(F)).
%
% See also MIN, MAX.

% Copyright 2016 by The University of Oxford and The Chebfun Developers.
% See http://www.chebfun.org/ for Chebfun information.

% Call minandmax for the ONEFUN of f:
[vals, onefunPos] = minandmax(f.onefun);

% Map the position results obtained on [-1,1] to [a,b]:
pos = f.mapping.For(onefunPos);

end


text:
'use strict';

// Transactions controller
angular.module('transactions').controller('TransactionsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Transactions',
  function ($scope, $stateParams, $location, Authentication, Transactions) {
    $scope.authentication = Authentication;

    // Create new Transaction
    $scope.create = function () {
      // Create new Transaction object
      var transaction = new Transactions({
        name: this.name,
        to: this.to,
        kind: this.kind,
        status: this.status,
        value: this.value,
        date: this.date,
        dueDate: this.dueDate
      });

      // Redirect after save
      transaction.$save(function (response) {
        $location.path('transactions/' + response._id);

        // Clear form fields
        $scope.name = '';
        $scope.to = '';
        $scope.kind = '';
        $scope.status = '';
        $scope.value = '';
        $scope.date = '';
        $scope.dueDate = '';
      }, function (errorResponse) {
        $scope.error = errorResponse.data.message;
      });
    };

    // Remove existing Transaction
    $scope.remove = function (transaction) {
      if (transaction) {
        transaction.$remove();

        for (var i in $scope.transactions) {
          if ($scope.transactions [i] === transaction) {
            $scope.transactions.splice(i, 1);
          }
        }
      } else {
        $scope.transaction.$remove(function () {
          $location.path('transactions');
        });
      }
    };

    // Update existing Transaction
    $scope.update = function () {
      var transaction = $scope.transaction;

      transaction.$update(function () {
        $location.path('transactions');
      }, function (errorResponse) {
        $scope.error = errorResponse.data.message;
      });
    };

    // Find a list of Transactions
    $scope.find = function () {
      $scope.transactions = Transactions.query();
    };

    // Find existing Transaction
    $scope.findOne = function () {
      $scope.transaction = Transactions.get({
        transactionId: $stateParams.transactionId
      });
    };

    $scope.title = function (transaction, user) {
      var to, kind, fromTo;

      if (transaction.user._id === user._id) {
        if (transaction.kind === 'pay') {
          kind = 'Pagar';
          fromTo = 'a';
        } else {
          kind = 'Receber';
          fromTo = 'de';
        }

        if (transaction.friend) {
          to = transaction.friend.displayName || transaction.to;
        } else {
          to = transaction.to;
        }
      } else {
        if (transaction.kind === 'pay') {
          kind = 'Receber';
          fromTo = 'de';
        } else {
          kind = 'Pagar';
          fromTo = 'a';
        }
        to = transaction.user.displayName;
      }

      return kind + ' R$' + transaction.value + ' ' + fromTo + ' ' + to;
    };

    $scope.canRevoke = function (transaction, user) {
      return transaction.user._id !== user._id &&
        transaction.to === user.email &&
        transaction.status === 'created';
    };

    $scope.canAccept = function (transaction, user) {
      return transaction.user._id !== user._id &&
        transaction.to === user.email &&
        (transaction.status === 'created' || transaction.status === 'revoked');
    };

    $scope.canPay = function (transaction, user) {
      return (transaction.user._id === user._id || transaction.to === user.email) &&
        (transaction.status === 'created' || transaction.status === 'accepted');
    };

    $scope.revoke = function (transaction) {
      if (transaction) {
        $scope.transaction = transaction;
      }
      $scope.transaction.status = 'revoked';
      $scope.update();
    };

    $scope.accept = function (transaction) {
      if (transaction) {
        $scope.transaction = transaction;
      }
      $scope.transaction.status = 'accepted';
      $scope.update();
    };

    $scope.pay = function (transaction) {
      if (transaction) {
        $scope.transaction = transaction;
      }
      $scope.transaction.status = 'paid';
      $scope.update();
    };

    $scope.rowClass = function (transaction, user) {
      var classe;

      switch (transaction.status) {
        case 'revoked':
          classe = 'list-group-item-danger';
          break;
        case 'paid':
          classe = 'list-group-item-success';
          break;
        case 'created':
          classe = (transaction.to === user.email) ? 'list-group-item-info' : '';
          break;
      }

      return classe;
    };
  }
]);


text:
"""Removes [users|preusers].username and adds [users|preusers].email instead

Revision ID: a2c99320aae4
Revises: 06299bfd31e3
Create Date: 2016-12-19 14:50:15.468293

"""

# revision identifiers, used by Alembic.
revision = 'a2c99320aae4'
down_revision = '06299bfd31e3'

from alembic import op
import sqlalchemy as sa

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('preusers', sa.Column('email', sa.String(length=100), nullable=True))

    # update all emails for the current preusers
    op.execute("UPDATE preusers SET email=username || '@wpi.edu';")

    op.drop_column('preusers', 'username')

    op.add_column('users', sa.Column('email', sa.String(length=100)))

    # update all emails for the current users
    op.execute("UPDATE users set email=username || '@wpi.edu';");

    op.alter_column('users', 'email',
                    existing_type=sa.String(length=100),
                    nullable=False)

    op.drop_constraint(u'users_username_key', 'users', type_='unique')
    op.create_unique_constraint(None, 'users', ['email'])
    op.drop_column('users', 'username')
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('users', sa.Column('username', sa.VARCHAR(length=80), autoincrement=False, nullable=False))
    op.drop_constraint(None, 'users', type_='unique')
    op.create_unique_constraint(u'users_username_key', 'users', ['username'])

    # get the username back from the emails in the users table
    op.execute("update users set username=split_part(email, '@', 1);")

    op.drop_column('users', 'email')
    op.add_column('preusers', sa.Column('username', sa.VARCHAR(length=80), autoincrement=False, nullable=True))

    # get the username back from the emails in the preusers table
    op.execute("update preusers set username=split_part(email, '@', 1);")

    op.drop_column('preusers', 'email')
    # ### end Alembic commands ###


text:
<?php

namespace Codeception\Lib\Driver;

use Codeception\Exception\ModuleException;

class PostgreSql extends Db
{
    protected $putline = false;

    protected $connection = null;

    protected $searchPath = null;

    /**
     * Loads a SQL file.
     *
     * @param string $sql sql file
     */
    public function load($sql)
    {
        $query = '';
        $delimiter = ';';
        $delimiterLength = 1;

        $dollarsOpen = false;
        foreach ($sql as $sqlLine) {
            if (preg_match('/DELIMITER ([\;\$\|\\\\]+)/i', $sqlLine, $match)) {
                $delimiter = $match[1];
                $delimiterLength = strlen($delimiter);
                continue;
            }

            $parsed = trim($query) == '' && $this->sqlLine($sqlLine);
            if ($parsed) {
                continue;
            }

            // Ignore $$ inside SQL standard string syntax such as in INSERT statements.
            if (!preg_match('/\'.*\$\$.*\'/', $sqlLine)) {
                $pos = strpos($sqlLine, '$$');
                if (($pos !== false) && ($pos >= 0)) {
                    $dollarsOpen = !$dollarsOpen;
                }
            }

            if (preg_match('/SET search_path = .*/i', $sqlLine, $match)) {
                $this->searchPath = $match[0];
            }

            $query .= "\n" . rtrim($sqlLine);

            if (!$dollarsOpen && substr($query, -1 * $delimiterLength, $delimiterLength) == $delimiter) {
                $this->sqlToRun = substr($query, 0, -1 * $delimiterLength);
                $this->sqlQuery($this->sqlToRun);
                $query = '';
            }
        }
    }

    public function cleanup()
    {
        $tables = $this->dbh
            ->query(
                "SELECT 'DROP TABLE IF EXISTS \"' || tablename || '\" cascade;' "
                . "FROM pg_tables WHERE schemaname = 'public';"
            )
            ->fetchAll();

        $sequences = $this->dbh
            ->query(
                "SELECT 'DROP SEQUENCE IF EXISTS \"' || relname || '\" cascade;' FROM pg_class WHERE relkind = 'S';"
            )
            ->fetchAll();

        // @codingStandardsIgnoreStart
        $types = $this->dbh
            ->query("SELECT 'DROP TYPE IF EXISTS \"' || t.typname || '\" cascade;' FROM pg_catalog.pg_type t LEFT JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace WHERE (t.typrelid = 0 OR (SELECT c.relkind = 'c' FROM pg_catalog.pg_class c WHERE c.oid = t.typrelid)) AND NOT EXISTS(SELECT 1 FROM pg_catalog.pg_type el WHERE el.oid = t.typelem AND el.typarray = t.oid) AND n.nspname <> 'pg_catalog' AND n.nspname <> 'information_schema' AND pg_catalog.pg_type_is_visible(t.oid);")
            ->fetchAll();
        // @codingStandardsIgnoreEnd

        $drops = array_merge($tables, $sequences, $types);
        if ($drops) {
            foreach ($drops as $drop) {
                $this->dbh->exec($drop[0]);
            }
        }
    }

    public function sqlLine($sql)
    {
        if (!$this->putline) {
            return parent::sqlLine($sql);
        }

        if ($sql == '\.') {
            $this->putline = false;
            pg_put_line($this->connection, $sql . "\n");
            pg_end_copy($this->connection);
            pg_close($this->connection);
        } else {
            pg_put_line($this->connection, $sql . "\n");
        }

        return true;
    }

    public function sqlQuery($query)
    {
        if (strpos(trim($query), 'COPY ') === 0) {
            if (!extension_loaded('pgsql')) {
                throw new ModuleException(
                    '\Codeception\Module\Db',
                    "To run 'COPY' commands 'pgsql' extension should be installed"
                );
            }
            if (defined('HHVM_VERSION')) {
                throw new ModuleException(
                    '\Codeception\Module\Db',
                    "'COPY' command is not supported on HHVM, please use INSERT instead"
                );
            }
            $constring = str_replace(';', ' ', substr($this->dsn, 6));
            $constring .= ' user=' . $this->user;
            $constring .= ' password=' . $this->password;
            $this->connection = pg_connect($constring);

            if ($this->searchPath !== null) {
                pg_query($this->connection, $this->searchPath);
            }

            pg_query($this->connection, $query);
            $this->putline = true;
        } else {
            $this->dbh->exec($query);
        }
    }

    /**
     * Get the last inserted ID of table.
     */
    public function lastInsertId($table)
    {
        /*
         * We make an assumption that the sequence name for this table
         * is based on how postgres names sequences for SERIAL columns
         */

        $sequenceName = $this->getQuotedName($table . '_id_seq');
        $lastSequence = null;

        try {
            $lastSequence = $this->getDbh()->lastInsertId($sequenceName);
        } catch (\PDOException $e) {
            // in this case, the sequence name might be combined with the primary key name
        }

        // here we check if for instance, it's something like table_primary_key_seq instead of table_id_seq
        // this could occur when you use some kind of import tool like pgloader
        if (!$lastSequence) {
            $primaryKeys = $this->getPrimaryKey($table);
            $pkName = array_shift($primaryKeys);
            $lastSequence = $this->getDbh()->lastInsertId($this->getQuotedName($table . '_' . $pkName . '_seq'));
        }

        return $lastSequence;
    }

    /**
     * Gets a quoted name of a variable.
     */
    public function getQuotedName($name)
    {
        $name = explode('.', $name);
        $name = array_map(
            function ($data) {
                return '"' . $data . '"';
            },
            $name
        );

        return implode('.', $name);
    }

    /**
     * Returns the primary key(s) of the table, based on:
     * https://wiki.postgresql.org/wiki/Retrieve_primary_key_columns.
     *
     * @param string $tableName
     *
     * @return array[string]
     */
    public function getPrimaryKey($tableName)
    {
        if (!isset($this->primaryKeys[$tableName])) {
            $primaryKey = [];
            $query = "SELECT a.attname
                FROM   pg_index i
                JOIN   pg_attribute a ON a.attrelid = i.indrelid
                                     AND a.attnum = ANY(i.indkey)
                WHERE  i.indrelid = '$tableName'::regclass
                AND    i.indisprimary";
            $stmt = $this->executeQuery($query, []);
            $columns = $stmt->fetchAll(\PDO::FETCH_ASSOC);
            foreach ($columns as $column) {
                $primaryKey []= $column['attname'];
            }
            $this->primaryKeys[$tableName] = $primaryKey;
        }

        return $this->primaryKeys[$tableName];
    }
}


text:
"""Undocumented Module"""

__all__ = ['findClass', 'rebindClass', 'copyFuncs', 'replaceMessengerFunc', 'replaceTaskMgrFunc', 'replaceStateFunc', 'replaceCRFunc', 'replaceAIRFunc', 'replaceIvalFunc']

import types
import os
import sys

def findClass(className):
    """
    Look in sys.modules dictionary for a module that defines a class
    with this className.
    """
    for moduleName, module in sys.modules.items():
        # Some modules are None for some reason
        if module:
            # print "Searching in ", moduleName
            classObj = module.__dict__.get(className)
            # If this modules defines some object called classname and the
            # object is a class or type definition and that class's module
            # is the same as the module we are looking in, then we found
            # the matching class and a good module namespace to redefine
            # our class in.
            if (classObj and
                ((type(classObj) == types.ClassType) or
                 (type(classObj) == types.TypeType)) and
                (classObj.__module__ == moduleName)):
                return [classObj, module.__dict__]
    return None

def rebindClass(filename):
    file = open(filename, 'r')
    lines = file.readlines()
    for i in xrange(len(lines)):
        line = lines[i]
        if (line[0:6] == 'class '):
            # Chop off the "class " syntax and strip extra whitespace
            classHeader = line[6:].strip()
            # Look for a open paren if it does inherit
            parenLoc = classHeader.find('(')
            if parenLoc > 0:
                className = classHeader[:parenLoc]
            else:
                # Look for a colon if it does not inherit
                colonLoc = classHeader.find(':')
                if colonLoc > 0:
                    className = classHeader[:colonLoc]
                else:
                    print 'error: className not found'
                    # Remove that temp file
                    file.close()
                    os.remove(filename)
                    return
            print 'Rebinding class name: ' + className
            break

    # Try to find the original class with this class name
    res = findClass(className)

    if not res:
        print ('Warning: Finder could not find class')
        # Remove the temp file we made
        file.close()
        os.remove(filename)
        return

    # Store the original real class
    realClass, realNameSpace = res

    # Now execute that class def in this namespace
    execfile(filename, realNameSpace)

    # That execfile should have created a new class obj in that namespace
    tmpClass = realNameSpace[className]

    # Copy the functions that we just redefined into the real class
    copyFuncs(tmpClass, realClass)

    # Now make sure the original class is in that namespace,
    # not our temp one from the execfile. This will help us preserve
    # class variables and other state on the original class.
    realNameSpace[className] = realClass

    # Remove the temp file we made
    file.close()
    os.remove(filename)

    print ('    Finished rebind')

def copyFuncs(fromClass, toClass):
    replaceFuncList = []
    newFuncList = []

    # Copy the functions from fromClass into toClass dictionary
    for funcName, newFunc in fromClass.__dict__.items():
        # Filter out for functions
        if (type(newFunc) == types.FunctionType):
            # See if we already have a function with this name
            oldFunc = toClass.__dict__.get(funcName)
            if oldFunc:

                """
                # This code is nifty, but with nested functions, give an error:
                #   SystemError: cellobject.c:22: bad argument to internal function
                # Give the new function code the same filename as the old function
                # Perhaps there is a cleaner way to do this? This was my best idea.
                newCode = types.CodeType(newFunc.func_code.co_argcount,
                                         newFunc.func_code.co_nlocals,
                                         newFunc.func_code.co_stacksize,
                                         newFunc.func_code.co_flags,
                                         newFunc.func_code.co_code,
                                         newFunc.func_code.co_consts,
                                         newFunc.func_code.co_names,
                                         newFunc.func_code.co_varnames,
                                         # Use the oldFunc's filename here. Tricky!
                                         oldFunc.func_code.co_filename,
                                         newFunc.func_code.co_name,
                                         newFunc.func_code.co_firstlineno,
                                         newFunc.func_code.co_lnotab)
                newFunc = types.FunctionType(newCode,
                                             newFunc.func_globals,
                                             newFunc.func_name,
                                             newFunc.func_defaults,
                                             newFunc.func_closure)
                """
                replaceFuncList.append((oldFunc, funcName, newFunc))
            else:
                # TODO: give these new functions a proper code filename
                newFuncList.append((funcName, newFunc))

    # Look in the messenger, taskMgr, and other globals that store func
    # pointers to see if this old function pointer is stored there, and
    # update it to the new function pointer.
    replaceMessengerFunc(replaceFuncList)
    replaceTaskMgrFunc(replaceFuncList)
    replaceStateFunc(replaceFuncList)
    replaceCRFunc(replaceFuncList)
    replaceAIRFunc(replaceFuncList)
    replaceIvalFunc(replaceFuncList)

    # Now that we've the globals funcs, actually swap the pointers in
    # the new class to the new functions
    for oldFunc, funcName, newFunc in replaceFuncList:
        # print "replacing old func: ", oldFunc, funcName, newFunc
        setattr(toClass, funcName, newFunc)
    # Add the brand new functions too
    for funcName, newFunc in newFuncList:
        # print "adding new func: ", oldFunc, funcName, newFunc
        setattr(toClass, funcName, newFunc)

def replaceMessengerFunc(replaceFuncList):
    try:
        messenger
    except:
        return
    for oldFunc, funcName, newFunc in replaceFuncList:
        res = messenger.replaceMethod(oldFunc, newFunc)
        if res:
            print ('replaced %s messenger function(s): %s' % (res, funcName))

def replaceTaskMgrFunc(replaceFuncList):
    try:
        taskMgr
    except:
        return
    for oldFunc, funcName, newFunc in replaceFuncList:
        if taskMgr.replaceMethod(oldFunc, newFunc):
            print ('replaced taskMgr function: %s' % funcName)

def replaceStateFunc(replaceFuncList):
    if not sys.modules.get('base.direct.fsm.State'):
        return
    from direct.fsm.State import State
    for oldFunc, funcName, newFunc in replaceFuncList:
        res = State.replaceMethod(oldFunc, newFunc)
        if res:
            print ('replaced %s FSM transition function(s): %s' % (res, funcName))

def replaceCRFunc(replaceFuncList):
    try:
        base.cr
    except:
        return
    # masad: Gyedo's fake cr causes a crash in followingreplaceMethod on rebinding, so
    # I throw in the isFake check. I still think the fake cr should be eliminated.
    if hasattr(base.cr,'isFake'):
        return
    for oldFunc, funcName, newFunc in replaceFuncList:
        if base.cr.replaceMethod(oldFunc, newFunc):
            print ('replaced DistributedObject function: %s' % funcName)

def replaceAIRFunc(replaceFuncList):
    try:
        simbase.air
    except:
        return
    for oldFunc, funcName, newFunc in replaceFuncList:
        if simbase.air.replaceMethod(oldFunc, newFunc):
            print ('replaced DistributedObject function: %s' % funcName)

def replaceIvalFunc(replaceFuncList):
    # Make sure we have imported IntervalManager and thus created
    # a global ivalMgr.
    if not sys.modules.get('base.direct.interval.IntervalManager'):
        return
    from direct.interval.FunctionInterval import FunctionInterval
    for oldFunc, funcName, newFunc in replaceFuncList:
        res = FunctionInterval.replaceMethod(oldFunc, newFunc)
        if res:
            print ('replaced %s interval function(s): %s' % (res, funcName))


text:
.responsive-image-menu span {
  display: inline-block;
}
.responsive-image-menu span img {
  width: 100%;
}


text:
export class AppError{
    constructor(public error?: any){

    }
}


text:
package io.cattle.platform.iaas.api.auth.integration.ldap.OpenLDAP;

import io.cattle.platform.core.util.SettingsUtils;
import io.cattle.platform.iaas.api.auth.SecurityConstants;
import io.cattle.platform.iaas.api.auth.integration.ldap.LDAPUtils;
import io.cattle.platform.iaas.api.auth.integration.ldap.interfaces.LDAPConstants;
import io.cattle.platform.json.JsonMapper;
import io.github.ibuildthecloud.gdapi.factory.SchemaFactory;
import io.github.ibuildthecloud.gdapi.model.ListOptions;
import io.github.ibuildthecloud.gdapi.request.ApiRequest;
import io.github.ibuildthecloud.gdapi.request.resource.impl.AbstractNoOpResourceManager;

import java.util.Map;
import javax.inject.Inject;

import org.apache.commons.lang3.StringUtils;

public class OpenLDAPConfigManager extends AbstractNoOpResourceManager {

    @Inject
    SettingsUtils settingsUtils;

    @Inject
    JsonMapper jsonMapper;

    @Override
    public Class<?>[] getTypeClasses() {
        return new Class<?>[]{OpenLDAPConfig.class};
    }

    @Override
    protected Object createInternal(String type, ApiRequest request) {
        if (!StringUtils.equals(OpenLDAPConstants.CONFIG, request.getType())) {
            return null;
        }
        LDAPConstants config = request.proxyRequestObject(LDAPConstants.class);
        LDAPUtils.validateConfig(config);
        return updateCurrentConfig(config);
    }

    private OpenLDAPConfig currentLdapConfig(LDAPConstants config) {
        OpenLDAPConfig currentConfig = (OpenLDAPConfig) listInternal(null, null, null, null);
        String domain = currentConfig.getDomain();
        if (config.getDomain() != null) {
            domain = config.getDomain();
        }
        String server = currentConfig.getServer();
        if (config.getServer() != null) {
            server = config.getServer();
        }
        String loginDomain = currentConfig.getLoginDomain();
        if (config.getLoginDomain() != null) {
            loginDomain = config.getLoginDomain();
        }
        String accessMode = currentConfig.getAccessMode();
        if (config.getAccessMode() != null) {
            accessMode = config.getAccessMode();
        }
        String serviceAccountUsername = currentConfig.getServiceAccountUsername();
        if (config.getServiceAccountUsername() != null) {
            serviceAccountUsername = config.getServiceAccountUsername();
        }
        String serviceAccountPassword = currentConfig.getServiceAccountPassword();
        if (config.getServiceAccountPassword() != null) {
            serviceAccountPassword = config.getServiceAccountPassword();
        }
        boolean tls = currentConfig.getTls();
        if (config.getTls() != null) {
            tls = config.getTls();
        }
        int port = currentConfig.getPort();
        if (config.getPort() != null) {
            port = config.getPort();
        }
        boolean enabled = currentConfig.getEnabled();
        if (config.getEnabled() != null) {
            enabled = config.getEnabled();
        }
        String userSearchField = currentConfig.getUserSearchField();
        if (config.getUserSearchField() != null){
            userSearchField = config.getUserSearchField();
        }
        String groupSearchField = currentConfig.getGroupSearchField();
        if (config.getGroupSearchField() != null){
            groupSearchField = config.getGroupSearchField();
        }
        String userLoginField = currentConfig.getUserLoginField();
        if (config.getUserLoginField() != null){
            userLoginField = config.getUserLoginField();
        }
        int userEnabledMaskBit = currentConfig.getUserDisabledBitMask();
        if (config.getUserDisabledBitMask() !=null){
            userEnabledMaskBit = config.getUserDisabledBitMask();
        }

        String userObjectClass = currentConfig.getUserObjectClass();
        if (config.getUserObjectClass() != null) {
            userObjectClass = config.getUserObjectClass();
        }
        String userNameField = currentConfig.getUserNameField();
        if (config.getUserNameField() != null){
            userNameField = config.getUserNameField();
        }
        String userEnabledAttribute = currentConfig.getUserEnabledAttribute();
        if (config.getUserEnabledAttribute() != null){
            userEnabledAttribute = config.getUserEnabledAttribute();
        }
        String groupObjectClass  = currentConfig.getGroupObjectClass();
        if (config.getGroupObjectClass()!= null){
            groupObjectClass = config.getGroupObjectClass();
        }
        String groupNameField = currentConfig.getGroupNameField();
        if (config.getGroupNameField() != null){
            groupNameField = config.getGroupNameField();
        }
        String userMemberAttribute = currentConfig.getUserMemberAttribute();
        if (config.getUserMemberAttribute() != null){
            userMemberAttribute = config.getUserMemberAttribute();
        }
        String groupMemberMappingAttribute = currentConfig.getGroupMemberMappingAttribute();
        if (config.getGroupMemberMappingAttribute() != null){
            groupMemberMappingAttribute = config.getGroupMemberMappingAttribute();
        }
        return new OpenLDAPConfig(server, port, userEnabledMaskBit, loginDomain, domain, enabled, accessMode,
                serviceAccountUsername, serviceAccountPassword, tls, userSearchField, userLoginField, userObjectClass,
                userNameField, userEnabledAttribute, groupSearchField, groupObjectClass, groupNameField, userMemberAttribute,
                groupMemberMappingAttribute, config.getConnectionTimeout());
    }

    @Override
    protected Object listInternal(SchemaFactory schemaFactory, String type, Map<Object, Object> criteria, ListOptions options) {
        boolean enabled = SecurityConstants.SECURITY.get();
        boolean tls = OpenLDAPConstants.TLS_ENABLED.get();
        int port = OpenLDAPConstants.LDAP_PORT.get();
        int userEnabledMaskBit = OpenLDAPConstants.USER_DISABLED_BIT_MASK.get();
        String accessMode = OpenLDAPConstants.ACCESS_MODE.get();
        String domain = OpenLDAPConstants.LDAP_DOMAIN.get();
        String groupMemberMappingAttribute = OpenLDAPConstants.GROUP_MEMBER_MAPPING_ATTRIBUTE.get();
        String groupNameField = OpenLDAPConstants.GROUP_NAME_FIELD.get();
        String groupObjectClass = OpenLDAPConstants.GROUP_OBJECT_CLASS.get();
        String groupSearchField = OpenLDAPConstants.GROUP_SEARCH_FIELD.get();
        String loginDomain = OpenLDAPConstants.LDAP_LOGIN_DOMAIN.get();
        String server = OpenLDAPConstants.LDAP_SERVER.get();
        String serviceAccountPassword = OpenLDAPConstants.SERVICE_ACCOUNT_PASSWORD.get();
        String serviceAccountUsername = OpenLDAPConstants.SERVICE_ACCOUNT_USER.get();
        String userEnabledAttribute = OpenLDAPConstants.USER_ENABLED_ATTRIBUTE.get();
        String userLoginField = OpenLDAPConstants.USER_LOGIN_FIELD.get();
        String userMemberAttribute = OpenLDAPConstants.USER_MEMBER_ATTRIBUTE.get();
        String userNameField = OpenLDAPConstants.USER_NAME_FIELD.get();
        String userObjectClass = OpenLDAPConstants.USER_OBJECT_CLASS.get();
        String userSearchField = OpenLDAPConstants.USER_SEARCH_FIELD.get();
        long connectionTimeout = OpenLDAPConstants.CONNECTION_TIMEOUT.get();
        return new OpenLDAPConfig(server, port, userEnabledMaskBit, loginDomain, domain, enabled, accessMode,
                serviceAccountUsername, serviceAccountPassword, tls, userSearchField, userLoginField, userObjectClass,
                userNameField, userEnabledAttribute, groupSearchField, groupObjectClass, groupNameField, userMemberAttribute,
                groupMemberMappingAttribute, connectionTimeout);
    }

    public OpenLDAPConfig updateCurrentConfig(LDAPConstants config) {
        settingsUtils.changeSetting(OpenLDAPConstants.ACCESS_MODE_SETTING, config.getAccessMode());
        settingsUtils.changeSetting(OpenLDAPConstants.DOMAIN_SETTING, config.getDomain());
        settingsUtils.changeSetting(OpenLDAPConstants.GROUP_NAME_FIELD_SETTING, config.getGroupNameField());
        settingsUtils.changeSetting(OpenLDAPConstants.GROUP_OBJECT_CLASS_SETTING, config.getGroupObjectClass());
        settingsUtils.changeSetting(OpenLDAPConstants.GROUP_SEARCH_FIELD_SETTING, config.getGroupSearchField());
        settingsUtils.changeSetting(OpenLDAPConstants.GROUP_USER_MAPPING_ATTRIBUTE_SETTING, config.getGroupMemberMappingAttribute());
        settingsUtils.changeSetting(OpenLDAPConstants.LOGIN_DOMAIN_SETTING, config.getLoginDomain());
        settingsUtils.changeSetting(OpenLDAPConstants.PORT_SETTING, config.getPort());
        settingsUtils.changeSetting(OpenLDAPConstants.SERVER_SETTING, config.getServer());
        settingsUtils.changeSetting(OpenLDAPConstants.SERVICE_ACCOUNT_PASSWORD_SETTING, config.getServiceAccountPassword());
        settingsUtils.changeSetting(OpenLDAPConstants.SERVICE_ACCOUNT_USERNAME_SETTING, config.getServiceAccountUsername());
        settingsUtils.changeSetting(OpenLDAPConstants.TLS_SETTING, config.getTls());
        settingsUtils.changeSetting(OpenLDAPConstants.USER_DISABLED_BIT_MASK_SETTING, config.getUserDisabledBitMask());
        settingsUtils.changeSetting(OpenLDAPConstants.USER_ENABLED_ATTRIBUTE_SETTING, config.getUserEnabledAttribute());
        settingsUtils.changeSetting(OpenLDAPConstants.USER_LOGIN_FIELD_SETTING, config.getUserLoginField());
        settingsUtils.changeSetting(OpenLDAPConstants.USER_MEMBER_ATTRIBUTE_SETTING, config.getUserMemberAttribute());
        settingsUtils.changeSetting(OpenLDAPConstants.USER_NAME_FIELD_SETTING, config.getUserNameField());
        settingsUtils.changeSetting(OpenLDAPConstants.USER_OBJECT_CLASS_SETTING, config.getUserObjectClass());
        settingsUtils.changeSetting(OpenLDAPConstants.USER_SEARCH_FIELD_SETTING, config.getUserSearchField());
        settingsUtils.changeSetting(OpenLDAPConstants.TIMEOUT_SETTING, config.getConnectionTimeout());
        settingsUtils.changeSetting(SecurityConstants.SECURITY_SETTING, config.getEnabled());
        if (config.getEnabled() != null){
            settingsUtils.changeSetting(SecurityConstants.AUTH_PROVIDER_SETTING, OpenLDAPConstants.CONFIG);
        } else {
            settingsUtils.changeSetting(SecurityConstants.AUTH_PROVIDER_SETTING, SecurityConstants.NO_PROVIDER);
        }
        return currentLdapConfig(config);
    }

    public String getName() {
        return OpenLDAPConstants.MANAGER;
    }

}


text:
package styles

import (
	"github.com/plandem/xlsx/internal/color"
	"github.com/plandem/xlsx/internal/ml"
	"github.com/plandem/xlsx/internal/ml/primitives"
	"github.com/stretchr/testify/require"
	"testing"
)

func TestFont(t *testing.T) {
	style := New(
		Font.Name("Calibri"),
		Font.Size(10),
		Font.Bold,
		Font.Italic,
		Font.Strikeout,
		Font.Shadow,
		Font.Condense,
		Font.Extend,
		Font.Family(FontFamilyDecorative),
		Font.Color("#FF00FF"),
		Font.Underline(UnderlineTypeSingle),
		Font.Superscript,
		Font.Scheme(FontSchemeMinor),
	)

	require.IsType(t, &Info{}, style)
	require.Equal(t, createStylesAndFill(func(f *Info) {
		f.styleInfo.Font = &ml.Font{
			Name:      "Calibri",
			Bold:      true,
			Italic:    true,
			Strike:    true,
			Shadow:    true,
			Condense:  true,
			Extend:    true,
			Size:      10.0,
			Color:     color.New("FFFF00FF"),
			Family:    FontFamilyDecorative,
			Underline: UnderlineTypeSingle,
			Effect:    primitives.FontEffectSuperscript,
			Scheme:    FontSchemeMinor,
		}
	}), style)
}


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

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	 version="3.1">
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

</web-app>


text:
import unittest

class HelpersTestCase(unittest.TestCase):
    pass

if __name__ == '__main__':
    unittest.main()


text:
from __future__ import unicode_literals

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('tasks', '0032_auto_20170410_1909'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='exporttask',
            name='filename',
        ),
    ]


text:
{% macro rule_head() -%}
    {# #}

{%- endmacro %}

{% macro rule_tabset(feed_uid, tabs) -%}

    {% for initial, rules in tabs|dictsort %}
      {% if initial != 'Python' %}

{{ initial }}

      {% endif %}
    {% endfor %}
    {% if 'Python' in tabs %}

Python

    {% endif %}

  {% for initial, rules in tabs|dictsort %}
    {% if initial != 'Python' %}

        Rule	Type	Text	Filtered articles
        Delete

      {% for uid, rtype, expires, text in rules %}

        {{ uid }}
        {{ rtype }}
        {{ text }}
        {% if feed_uid %}
        show
        {% else %}
        show
        {% endif %}
        delete

      {% endfor %}

    {% endif %}
  {% endfor %}
  {% if tabs.get('Python') %}

        Rule	Expires	Text	Delete
        Update

      {% for uid, rtype, expires, text in tabs['Python'] %}

        <form name="form_python_{{ uid }}" action="rules" method="GET">
          {{ uid }}<input type="hidden" name="uid" value="{{ uid }}">
          <input type="text" name="expires" value="{{ expires }}"
                     size="10">
          <textarea cols="80" rows="{{ text|rule_lines }}" name="text">{{ text }}</textarea>

          <input type="checkbox" name="delete">
          <input type="submit" value="Update">
        </form>

      {% endfor %}

        <form action="rules" method="GET">
        <input type="hidden" name="uid" value="new">
        <input type="text" name="expires" size="10" value="never">
        <textarea cols="80" name="text">'XXX' in feed_title and 'YYY' in title</textarea>

        <input type="submit" value="Add">

        </form>

Filter syntax:

The filtering rules are Python expressions that are evaluated as
    booleans. The following variables are always available:

        Variable	Description

feed_title	Title of the feed

title	Title of the article

title_lc	Title of the article (all in
      lower case)

title_words	Set of lower-cased and
      diacritic-stripped words in the title

content	Contents of the article

content_lc	Contents of the article (all
      in lower case)

content_words	Set of lower-cased and
      diacritic-stripped words in the content

union_lc	Union of the article (all in
      lower case)

union_words	Set of lower-cased and
      diacritic-stripped words in both title and contents

link	article URL (before dereferencing)

category	If present, set of categories for
      the article

author	Author of the article

In addition, the convenience functions <tt>title_any</tt>,
    <tt>content_any</tt>, <tt>union_any</tt>, <tt>title_any_lc</tt>,
    <tt>content_any_lc</tt>, <tt>union_any_lc</tt>,
    <tt>title_any_words</tt>, <tt>content_any_words</tt>,
    <tt>union_any_words</tt>are here to simplify rules. They take a list of
    strings and search in the corresponding
    <tt>title|content(|_lc|_words)</tt> (the <tt>union_</tt>* variants will
    match either title or contents). If any of the strings in the list
    matches, the function returns True.

The function <tt>link_already(</tt>url<tt>)</tt> checks if
    the URL passed as its argument is that of an article that was already
    loaded. This is useful to filter out duplicates or echos from
    aggregated feeds like Digg or Slashdot, but it also slows down feed
    processing. You can use the function
    <tt>link_extract(link_text, content)</tt> to extract a link from the
    content (the text of the link must match exactly).

Other variables may be available on a feed-by-feed basis, also
    depending on which feed standard is used (e.g. Atom vs. RSS). Check
    the feed details page for the feed you are interested in for more
    details.

If a variable does not exist, the expression evaluation will throw
    an exception, and the article will not be filtered out, but in a
    Python logical OR expression, if the first term evaluates true, the
    second term is not evaluated and the article will be filtered out even
    if the second term refers to a variable that does not exist.

You can add comments by starting a line with the character
    <tt>#</tt>, and use carriage returns like whitespace for
    legibility

Examples

Should be self-explanatory:

    'Salon' in feed_title and ('King Kaufman' in title or 'Letters' in
    title)

 'SAP' in title.split()

or almost equivalently:

    'sap' in title_words

    'Guardian Unlimited' in feed_title and (content.startswith('Sport:')
     or 'football' in content_lc or 'cricket' in content_lc)

which is equivalent to:

    'Guardian Unlimited' in feed_title and (content.startswith('Sport:')
    or content_any_lc('football', 'cricket'))

Filter articles referring to SAP, but as a word (i.e. do not filter
    out 'ASAP'):

    union_any_words('sap')

{% endif %}

{%- endmacro %}


text:
package br.com.RUAtevoce.jdbc;

import java.sql.*;

public class ConnectionFactory {

	public Connection getConnection(){

		try {
			/**
			 * O campo "database" deve ser substituido pelo nome do banco de dados corrente
			 * tambem pode ser utilizado as seguintes estruturas:
			 * jdbc:postgresql://host/database
			 * jdbc:postgresql://host:port/database
			 * A porta geralmente do PostegreSQL é 5432
			 */
			return DriverManager.getConnection("jdbc:postgresql:database","root",""); //O campo em branco "" representa a senha do banco de dados, nesse caso não há nenhum
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
}


text:
function addTaskFromOverlay() {
	tasks.setSelected(tasks.add());
	taskOverlay.hide();

	rerenderTabstrip();
	addTab();
}

var overlay = document.getElementById("task-overlay");
var taskContainer = document.getElementById("task-area");
var taskSwitcherButton = document.getElementById("switch-task-button");
var addTaskButton = document.getElementById("add-task");
var navbar = document.getElementById("task-overlay-navbar");

taskSwitcherButton.addEventListener("click", function () {
	taskOverlay.toggle();
});

addTaskButton.addEventListener("click", function (e) {
	switchToTask(tasks.add());
	taskOverlay.hide();
});

navbar.addEventListener("click", function () {
	taskOverlay.hide();
});

function getTaskOverlayTabElement(tab, task) {

	var item = createSearchbarItem({
		title: tab.title || "New Tab",
		secondaryText: urlParser.removeProtocol(tab.url),
		classList: ["task-tab-item"],
		delete: function () {
			task.tabs.destroy(tab.id);
			destroyWebview(tab.id);

			//if there are no tabs left, remove the task

			if (task.tabs.count() == 0) {
				destroyTask(task.id);
				if (tasks.get().length == 0) {
					addTaskFromOverlay();
				} else {
					//re-render the overlay to remove the task element
					getTaskContainer(task.id).remove();
				}
			}
		},
	});

	item.setAttribute("data-tab", tab.id);
	item.setAttribute("data-task", task.id);

	return item;
}

function getTaskElement(task, taskIndex) {
	var container = document.createElement("div");
	container.className = "task-container";

	container.setAttribute("data-task", task.id);

	var taskActionContainer = document.createElement("div");
	taskActionContainer.className = "task-action-container";

	//add the input for the task name

	var input = document.createElement("input");
	input.classList.add("task-name");

	input.placeholder = "Task " + (taskIndex + 1);

	input.value = task.name || "Task " + (taskIndex + 1);

	input.addEventListener("keyup", function (e) {
		if (e.keyCode == 13) {
			this.blur();
		}

		tasks.get(task.id).name = this.value;
	});

	input.addEventListener("focus", function () {
		this.select();
	});

	taskActionContainer.appendChild(input);

	//delete button

	var deleteButton = document.createElement("i");
	deleteButton.className = "fa fa-trash-o";

	deleteButton.addEventListener("click", function (e) {
		destroyTask(task.id);
		container.remove();

		if (tasks.get().length == 0) { //create a new task
			addTaskFromOverlay();
		}
	});

	taskActionContainer.appendChild(deleteButton);

	container.appendChild(taskActionContainer);

	var tabContainer = document.createElement("div");
	tabContainer.className = "task-tabs-container";

	if (task.tabs) {
		for (var i = 0; i < task.tabs.length; i++) {

			var el = getTaskOverlayTabElement(task.tabs[i], task);

			el.addEventListener("click", function (e) {
				switchToTask(this.getAttribute("data-task"));
				switchToTab(this.getAttribute("data-tab"));

				taskOverlay.hide();
			});

			tabContainer.appendChild(el);
		}
	}

	container.appendChild(tabContainer);

	return container;
}

var dragula = require("dragula");

var taskOverlay = {
	isShown: false,
	dragula: dragula({
		direction: "vertical",
	}),
	show: function () {

		/* disabled in focus mode */
		if (isFocusMode) {
			showFocusModeError();
			return;
		}

		leaveTabEditMode();

		taskOverlay.isShown = true;
		taskSwitcherButton.classList.add("active");

		taskOverlay.dragula.containers = [];
		empty(taskContainer);

		//show the task elements
		tasks.get().forEach(function (task, index) {
			var el = getTaskElement(task, index);

			taskContainer.appendChild(el);
			taskOverlay.dragula.containers.push(el.getElementsByClassName("task-tabs-container")[0]);
		});

		//scroll to the selected element and focus it

		var currentTabElement = document.querySelector('.task-tab-item[data-tab="{id}"]'.replace("{id}", currentTask.tabs.getSelected()));

		if (currentTabElement) {
			currentTabElement.scrollIntoViewIfNeeded();
			currentTabElement.classList.add("fakefocus");
		}

		//un-hide the overlay

		overlay.hidden = false;
	},
	hide: function () {
		if (taskOverlay.isShown) {
			taskOverlay.isShown = false;
			overlay.hidden = true;

			//if the current task has been deleted, switch to the first task
			if (!tasks.get(currentTask.id)) {
				switchToTask(tasks.get()[0].id);
			}

			taskSwitcherButton.classList.remove("active");
		}
	},
	toggle: function () {
		if (taskOverlay.isShown) {
			taskOverlay.hide();
		} else {
			taskOverlay.show();
		}
	}
}

//swipe down on the tabstrip to show the task overlay
//this was the old expanded mode gesture, so it's remapped to the overlay
tabContainer.addEventListener("mousewheel", function (e) {
	if (e.deltaY < -30 && e.deltaX < 10) {
		taskOverlay.show();
		e.stopImmediatePropagation();
	}
});

function getTaskContainer(id) {
	return document.querySelector('.task-container[data-task="{id}"]'.replace("{id}", id));
}

function syncStateAndOverlay() {
	var selectedTask = currentTask.id;

	var tabSet = {};
	//get a list of all of the currently open tabs

	tasks.get().forEach(function (task) {
		task.tabs.get().forEach(function (tab) {
			tabSet[tab.id] = tab;
		})
	});

	//loop through each task

	tasks.get().forEach(function (task) {

		var container = getTaskContainer(task.id);

		//if the task still exists, update the tabs
		if (container) {
			//remove all of the old tabs
			task.tabs.get().forEach(function (tab) {
				task.tabs.destroy(tab.id);
			});

			//add the new tabs
			var newTabs = container.getElementsByClassName("task-tab-item");

			if (newTabs.length != 0) {
				for (var i = 0; i < newTabs.length; i++) {
					task.tabs.add(tabSet[newTabs[i].getAttribute("data-tab")]);
					//update the data-task attribute of the tab element
					newTabs[i].setAttribute("data-task", task.id);
				}
			} else {
				//the task has no tabs, remove it

				destroyTask(task.id);
				container.remove();
			}
		} else {
			//the task no longer exists, remove it

			destroyTask(task.id);
		}
	});
}

taskOverlay.dragula.on("drop", function () {
	syncStateAndOverlay();
})


text:
package beyond.metrics

import akka.actor.Actor
import akka.actor.ActorLogging
import javax.management.JMX
import javax.management.MBeanServerConnection

object RequestsCounter {
  case object Increase
  val Name: String = "RequestCounter"
}

class RequestsCounter extends Actor with ActorLogging with JMXConnectorMixin {
  private val numberOfRequestsPerSecond: NumberOfRequestsPerSecondMBean = {
    val mbsc: MBeanServerConnection = jmxConnector.getMBeanServerConnection
    JMX.newMBeanProxy(mbsc, NumberOfRequestsPerSecond.objectName, classOf[NumberOfRequestsPerSecondMBean])
  }

  override def receive: Receive = {
    case RequestsCounter.Increase =>
      numberOfRequestsPerSecond.increase()
  }

  override def postStop() {
    super.postStop()
  }
}


text:
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response
from nssrc.com.citrix.netscaler.nitro.service.options import options
from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_exception

from nssrc.com.citrix.netscaler.nitro.util.nitro_util import nitro_util

class appfwprofile_xmlattachmenturl_binding(base_resource) :
	""" Binding class showing the xmlattachmenturl that can be bound to appfwprofile.
	"""
	def __init__(self) :
		self._xmlattachmenturl = ""
		self._xmlmaxattachmentsizecheck = ""
		self._xmlmaxattachmentsize = 0
		self._xmlattachmentcontenttypecheck = ""
		self._xmlattachmentcontenttype = ""
		self._state = ""
		self._comment = ""
		self._name = ""
		self.___count = 0

	@property
	def xmlattachmenturl(self) :
		"""XML attachment URL regular expression length.
		"""
		try :
			return self._xmlattachmenturl
		except Exception as e:
			raise e

	@xmlattachmenturl.setter
	def xmlattachmenturl(self, xmlattachmenturl) :
		"""XML attachment URL regular expression length.
		"""
		try :
			self._xmlattachmenturl = xmlattachmenturl
		except Exception as e:
			raise e

	@property
	def name(self) :
		"""Name of the profile to which to bind an exemption or rule.
Minimum length =  1.
		"""
		try :
			return self._name
		except Exception as e:
			raise e

	@name.setter
	def name(self, name) :
		"""Name of the profile to which to bind an exemption or rule.
Minimum length =  1
		"""
		try :
			self._name = name
		except Exception as e:
			raise e

	@property
	def xmlmaxattachmentsize(self) :
		"""Specify maximum attachment size.
		"""
		try :
			return self._xmlmaxattachmentsize
		except Exception as e:
			raise e

	@xmlmaxattachmentsize.setter
	def xmlmaxattachmentsize(self, xmlmaxattachmentsize) :
		"""Specify maximum attachment size.
		"""
		try :
			self._xmlmaxattachmentsize = xmlmaxattachmentsize
		except Exception as e:
			raise e

	@property
	def xmlmaxattachmentsizecheck(self) :
		"""State if XML Max attachment size Check is ON or OFF. Protects against XML requests with large attachment data.
Possible values = ON, OFF.
		"""
		try :
			return self._xmlmaxattachmentsizecheck
		except Exception as e:
			raise e

	@xmlmaxattachmentsizecheck.setter
	def xmlmaxattachmentsizecheck(self, xmlmaxattachmentsizecheck) :
		"""State if XML Max attachment size Check is ON or OFF. Protects against XML requests with large attachment data.
Possible values = ON, OFF
		"""
		try :
			self._xmlmaxattachmentsizecheck = xmlmaxattachmentsizecheck
		except Exception as e:
			raise e

	@property
	def state(self) :
		"""Enabled.
Possible values = ENABLED, DISABLED.
		"""
		try :
			return self._state
		except Exception as e:
			raise e

	@state.setter
	def state(self, state) :
		"""Enabled.
Possible values = ENABLED, DISABLED
		"""
		try :
			self._state = state
		except Exception as e:
			raise e

	@property
	def xmlattachmentcontenttypecheck(self) :
		"""State if XML attachment content-type check is ON or OFF. Protects against XML requests with illegal attachments.
Possible values = ON, OFF.
		"""
		try :
			return self._xmlattachmentcontenttypecheck
		except Exception as e:
			raise e

	@xmlattachmentcontenttypecheck.setter
	def xmlattachmentcontenttypecheck(self, xmlattachmentcontenttypecheck) :
		"""State if XML attachment content-type check is ON or OFF. Protects against XML requests with illegal attachments.
Possible values = ON, OFF
		"""
		try :
			self._xmlattachmentcontenttypecheck = xmlattachmentcontenttypecheck
		except Exception as e:
			raise e

	@property
	def comment(self) :
		"""Any comments about the purpose of profile, or other useful information about the profile.
		"""
		try :
			return self._comment
		except Exception as e:
			raise e

	@comment.setter
	def comment(self, comment) :
		"""Any comments about the purpose of profile, or other useful information about the profile.
		"""
		try :
			self._comment = comment
		except Exception as e:
			raise e

	@property
	def xmlattachmentcontenttype(self) :
		"""Specify content-type regular expression.
		"""
		try :
			return self._xmlattachmentcontenttype
		except Exception as e:
			raise e

	@xmlattachmentcontenttype.setter
	def xmlattachmentcontenttype(self, xmlattachmentcontenttype) :
		"""Specify content-type regular expression.
		"""
		try :
			self._xmlattachmentcontenttype = xmlattachmentcontenttype
		except Exception as e:
			raise e

	def _get_nitro_response(self, service, response) :
		""" converts nitro response into object and returns the object array in case of get request.
		"""
		try :
			result = service.payload_formatter.string_to_resource(appfwprofile_xmlattachmenturl_binding_response, response, self.__class__.__name__)
			if(result.errorcode != 0) :
				if (result.errorcode == 444) :
					service.clear_session(self)
				if result.severity :
					if (result.severity == "ERROR") :
						raise nitro_exception(result.errorcode, str(result.message), str(result.severity))
				else :
					raise nitro_exception(result.errorcode, str(result.message), str(result.severity))
			return result.appfwprofile_xmlattachmenturl_binding
		except Exception as e :
			raise e

	def _get_object_name(self) :
		""" Returns the value of object identifier argument
		"""
		try :
			if (self.name) :
				return str(self.name)
			return None
		except Exception as e :
			raise e

	@classmethod
	def add(cls, client, resource) :
		try :
			if resource and type(resource) is not list :
				updateresource = appfwprofile_xmlattachmenturl_binding()
				updateresource.name = resource.name
				updateresource.comment = resource.comment
				updateresource.state = resource.state
				updateresource.xmlattachmenturl = resource.xmlattachmenturl
				updateresource.xmlmaxattachmentsizecheck = resource.xmlmaxattachmentsizecheck
				updateresource.xmlattachmentcontenttypecheck = resource.xmlattachmentcontenttypecheck
				updateresource.xmlattachmentcontenttype = resource.xmlattachmentcontenttype
				return updateresource.update_resource(client)
			else :
				if resource and len(resource) > 0 :
					updateresources = [appfwprofile_xmlattachmenturl_binding() for _ in range(len(resource))]
					for i in range(len(resource)) :
						updateresources[i].name = resource[i].name
						updateresources[i].comment = resource[i].comment
						updateresources[i].state = resource[i].state
						updateresources[i].xmlattachmenturl = resource[i].xmlattachmenturl
						updateresources[i].xmlmaxattachmentsizecheck = resource[i].xmlmaxattachmentsizecheck
						updateresources[i].xmlattachmentcontenttypecheck = resource[i].xmlattachmentcontenttypecheck
						updateresources[i].xmlattachmentcontenttype = resource[i].xmlattachmentcontenttype
				return cls.update_bulk_request(client, updateresources)
		except Exception as e :
			raise e

	@classmethod
	def delete(cls, client, resource) :
		try :
			if resource and type(resource) is not list :
				deleteresource = appfwprofile_xmlattachmenturl_binding()
				deleteresource.name = resource.name
				deleteresource.xmlattachmenturl = resource.xmlattachmenturl
				return deleteresource.delete_resource(client)
			else :
				if resource and len(resource) > 0 :
					deleteresources = [appfwprofile_xmlattachmenturl_binding() for _ in range(len(resource))]
					for i in range(len(resource)) :
						deleteresources[i].name = resource[i].name
						deleteresources[i].xmlattachmenturl = resource[i].xmlattachmenturl
				return cls.delete_bulk_request(client, deleteresources)
		except Exception as e :
			raise e

	@classmethod
	def get(cls, service, name) :
		""" Use this API to fetch appfwprofile_xmlattachmenturl_binding resources.
		"""
		try :
			obj = appfwprofile_xmlattachmenturl_binding()
			obj.name = name
			response = obj.get_resources(service)
			return response
		except Exception as e:
			raise e

	@classmethod
	def get_filtered(cls, service, name, filter_) :
		""" Use this API to fetch filtered set of appfwprofile_xmlattachmenturl_binding resources.
		Filter string should be in JSON format.eg: "port:80,servicetype:HTTP".
		"""
		try :
			obj = appfwprofile_xmlattachmenturl_binding()
			obj.name = name
			option_ = options()
			option_.filter = filter_
			response = obj.getfiltered(service, option_)
			return response
		except Exception as e:
			raise e

	@classmethod
	def count(cls, service, name) :
		""" Use this API to count appfwprofile_xmlattachmenturl_binding resources configued on NetScaler.
		"""
		try :
			obj = appfwprofile_xmlattachmenturl_binding()
			obj.name = name
			option_ = options()
			option_.count = True
			response = obj.get_resources(service, option_)
			if response :
				return response[0].__dict__['___count']
			return 0
		except Exception as e:
			raise e

	@classmethod
	def count_filtered(cls, service, name, filter_) :
		""" Use this API to count the filtered set of appfwprofile_xmlattachmenturl_binding resources.
		Filter string should be in JSON format.eg: "port:80,servicetype:HTTP".
		"""
		try :
			obj = appfwprofile_xmlattachmenturl_binding()
			obj.name = name
			option_ = options()
			option_.count = True
			option_.filter = filter_
			response = obj.getfiltered(service, option_)
			if response :
				return response[0].__dict__['___count']
			return 0
		except Exception as e:
			raise e

	class As_scan_location_xmlsql:
		ELEMENT = "ELEMENT"
		ATTRIBUTE = "ATTRIBUTE"

	class Xmlmaxelementdepthcheck:
		ON = "ON"
		OFF = "OFF"

	class Xmlmaxattachmentsizecheck:
		ON = "ON"
		OFF = "OFF"

	class Xmlsoaparraycheck:
		ON = "ON"
		OFF = "OFF"

	class State:
		ENABLED = "ENABLED"
		DISABLED = "DISABLED"

	class Xmlmaxelementnamelengthcheck:
		ON = "ON"
		OFF = "OFF"

	class Isregex_ff:
		REGEX = "REGEX"
		NOTREGEX = "NOTREGEX"

	class Xmlmaxelementscheck:
		ON = "ON"
		OFF = "OFF"

	class Xmlendpointcheck:
		ABSOLUTE = "ABSOLUTE"
		RELATIVE = "RELATIVE"

	class Xmlmaxnamespacescheck:
		ON = "ON"
		OFF = "OFF"

	class Xmlmaxfilesizecheck:
		ON = "ON"
		OFF = "OFF"

	class Xmlmaxattributenamelengthcheck:
		ON = "ON"
		OFF = "OFF"

	class Xmlblockdtd:
		ON = "ON"
		OFF = "OFF"

	class Xmlblockpi:
		ON = "ON"
		OFF = "OFF"

	class Isregex_sql:
		REGEX = "REGEX"
		NOTREGEX = "NOTREGEX"

	class Xmlvalidateresponse:
		ON = "ON"
		OFF = "OFF"

	class Xmlmaxelementchildrencheck:
		ON = "ON"
		OFF = "OFF"

	class Isregex:
		REGEX = "REGEX"
		NOTREGEX = "NOTREGEX"

	class Xmlmaxentityexpansionscheck:
		ON = "ON"
		OFF = "OFF"

	class Xmlmaxnamespaceurilengthcheck:
		ON = "ON"
		OFF = "OFF"

	class As_scan_location_xss:
		FORMFIELD = "FORMFIELD"
		HEADER = "HEADER"
		COOKIE = "COOKIE"

	class Xmlmaxentityexpansiondepthcheck:
		ON = "ON"
		OFF = "OFF"

	class As_scan_location_xmlxss:
		ELEMENT = "ELEMENT"
		ATTRIBUTE = "ATTRIBUTE"

	class Xmlmaxattributevaluelengthcheck:
		ON = "ON"
		OFF = "OFF"

	class As_scan_location_sql:
		FORMFIELD = "FORMFIELD"
		HEADER = "HEADER"
		COOKIE = "COOKIE"

	class Isregex_ffc:
		REGEX = "REGEX"
		NOTREGEX = "NOTREGEX"

	class Xmlattachmentcontenttypecheck:
		ON = "ON"
		OFF = "OFF"

	class Isregex_xmlsql:
		REGEX = "REGEX"
		NOTREGEX = "NOTREGEX"

	class Xmlvalidatesoapenvelope:
		ON = "ON"
		OFF = "OFF"

	class Xmlmaxchardatalengthcheck:
		ON = "ON"
		OFF = "OFF"

	class Xmlminfilesizecheck:
		ON = "ON"
		OFF = "OFF"

	class Isregex_xss:
		REGEX = "REGEX"
		NOTREGEX = "NOTREGEX"

	class Isregex_xmlxss:
		REGEX = "REGEX"
		NOTREGEX = "NOTREGEX"

	class Xmladditionalsoapheaders:
		ON = "ON"
		OFF = "OFF"

	class Xmlmaxattributescheck:
		ON = "ON"
		OFF = "OFF"

	class Action:
		none = "none"
		block = "block"
		log = "log"
		remove = "remove"
		stats = "stats"
		xout = "xout"

	class Xmlblockexternalentities:
		ON = "ON"
		OFF = "OFF"

class appfwprofile_xmlattachmenturl_binding_response(base_response) :
	def __init__(self, length=1) :
		self.appfwprofile_xmlattachmenturl_binding = []
		self.errorcode = 0
		self.message = ""
		self.severity = ""
		self.sessionid = ""
		self.appfwprofile_xmlattachmenturl_binding = [appfwprofile_xmlattachmenturl_binding() for _ in range(length)]


text:
using System.Collections.Generic;
using dto.endpoint.auth.session;

namespace dto.endpoint.positions.get.otc.v1
{

public class PositionsResponse{
	///<Summary>
	///List of positions
	///</Summary>
	public List<OpenPosition> positions { get; set; }
}
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using GeekBudget.Core;

namespace GeekBudget.Application.Tabs
{
    public static class TabErrors
    {
        public static Error TabIdIsRequired => new Error { Id = 100, Description = $"Tab Id is required!" };
        public static Error TabNameIsRequired => new Error { Id = 101, Description = $"Tab Name is required!" };
        public static Error TabTypeIsRequired => new Error { Id = 102, Description = $"Tab Type is required!" };
        public static Error TabWithIdDoesNotExist(int id) => new Error { Id = 103, Description = $"No Tab with id '{id}' was found!" };
    }
}


text:
<!DOCTYPE html>

    <title>CustomElementsRegistry.upgrade</title>


text:
#import "WXComponent+Navigation.h"
#import "WXComponent_internal.h"
#import "WXSDKInstance_private.h"
#import "WXBaseViewController.h"
#import "WXHandlerFactory.h"
#import "WXConvert.h"
#import "WXUtility.h"

#define kBarTintColor @"barTintColor"
#define kBarItemText @"title"
#define kBarItemTextColor @"titleColor"
#define kBarItemIcon  @"icon"

#pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation"

@implementation WXComponent (Navigation)

- (id<WXNavigationProtocol>)navigator
{
    id<WXNavigationProtocol> navigator = [WXHandlerFactory handlerForProtocol:@protocol(WXNavigationProtocol)];
    return navigator;
}

// navigtion configuration
- (void)_setupNavBarWithStyles:(NSMutableDictionary *)styles attributes:(NSMutableDictionary *)attributes
{
    NSString *dataRole = attributes[@"dataRole"];
    if (dataRole && [dataRole isEqualToString:@"navbar"]) {
        styles[@"visibility"] = @"hidden";
        styles[@"position"] = @"fixed";

        self.weexInstance.naviBarStyles = [NSMutableDictionary new];

        [self setNavigationBarHidden:NO];

        NSString *backgroundColor = styles[@"backgroundColor"];
        [self setNavigationBackgroundColor:[WXConvert UIColor:backgroundColor]];
    }

    NSString *position = attributes[@"naviItemPosition"];
    if (position) {
        NSMutableDictionary *data = [NSMutableDictionary new];
        [data setObject:_type forKey:@"type"];
        [data setObject:styles forKey:@"style"];
        [data setObject:attributes forKey:@"attr"];

        if ([position isEqualToString:@"left"]) {
            [self setNavigationItemWithParam:data position:WXNavigationItemPositionLeft];
        }
        else if ([position isEqualToString:@"right"]) {
            [self setNavigationItemWithParam:data position:WXNavigationItemPositionRight];
        }
        else if ([position isEqualToString:@"center"]) {
            [self setNavigationItemWithParam:data position:WXNavigationItemPositionCenter];
        }
        else if ([position isEqualToString:@"rights"]) {
            [self setNavigationItemWithParam:data position:WXNavigationItemPositionRights];
        }

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(observeInstanceState:) name:WX_INSTANCE_NOTIFICATION_UPDATE_STATE object:nil];
    }
}

- (void)_updateNavBarAttributes:(NSDictionary *)attributes
{
    if (attributes[@"data-role"]) {
        NSString *dataRole = attributes[@"data-role"];
        if ([dataRole isEqualToString:@"navbar"]) {
            [self setNavigationBarHidden:NO];

            NSDictionary *style = self.styles[@"style"];
            NSString *backgroundColor = style[@"backgroundColor"];
            [self setNavigationBackgroundColor:[WXConvert UIColor:backgroundColor]];
        }
    }
}

- (void)setNavigationBarHidden:(BOOL)hidden
{
    UIViewController *container = self.weexInstance.viewController;
    id<WXNavigationProtocol> navigator = [self navigator];

    WXPerformBlockOnMainThread(^{
        [navigator setNavigationBarHidden:hidden animated:NO withContainer:container];
    });
}

- (void)setNavigationBackgroundColor:(UIColor *)backgroundColor
{
    if (!backgroundColor) return;

    NSMutableDictionary *styles = self.weexInstance.naviBarStyles;
    [styles setObject:backgroundColor forKey:kBarTintColor];

    UIViewController *container = self.weexInstance.viewController;
    id<WXNavigationProtocol> navigator = [self navigator];

    WXPerformBlockOnMainThread(^{
        [navigator setNavigationBackgroundColor:backgroundColor withContainer:container];
    });
}

- (void)setNavigationItemWithParam:(NSDictionary *)param position:(WXNavigationItemPosition)position
{
    if (!param)  return;

    __weak __block typeof(WXComponent) *weakSelf = self;

    NSArray *array = @[@"center",@"right",@"left",@"more",@"rights"];

    [self _parse:param resultBlock:^(NSDictionary *dict) {
        NSMutableDictionary *styles = weakSelf.weexInstance.naviBarStyles;
        if (position == WXNavigationItemPositionRights) {
            NSArray* arrayRights = [styles objectForKey:array[position]];
            NSMutableArray* rights = [[NSMutableArray alloc] init];
            if (arrayRights) {
                [rights addObjectsFromArray:arrayRights];
            }
            [rights addObject:dict];
            [styles setObject:rights forKey:array[position]];
        }
        else {
            [styles setObject:dict forKey: array[position]];
        }

        UIViewController *container = weakSelf.weexInstance.viewController;
        id<WXNavigationProtocol> navigator = [weakSelf navigator];
        [navigator setWeexInstance:self.weexInstance];

        WXPerformBlockOnMainThread(^{
            [navigator setNavigationItemWithParam:dict position:position completion:nil withContainer:container];
        });
    }];
}

- (void)observeInstanceState:(NSNotification *)notification
{
    WXSDKInstance *instance = notification.object;

    if (instance == self.weexInstance) {
        NSDictionary *userInfo = notification.userInfo;
        WXState state = [userInfo[@"state"] integerValue];
        if (state == WeexInstanceAppear) {
            [self setNavigationWithStyles:self.weexInstance.naviBarStyles];
        }

    }
}

- (void)setNavigationWithStyles:(NSDictionary *)styles
{
    UIViewController *container = self.weexInstance.viewController;
    id<WXNavigationProtocol> navigator = [self navigator];

    if (styles) {
        [navigator setNavigationBarHidden:NO animated:NO withContainer:container];
        [navigator setNavigationBackgroundColor:styles[kBarTintColor] withContainer:container];

        NSArray *array = @[@"center",@"right",@"left",@"more",@"rights"];
        [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (idx == WXNavigationItemPositionRights) {
                [navigator clearNavigationItemWithParam:nil position:idx completion:nil withContainer:container];
                NSArray* rights = styles[obj];
                for (NSDictionary *param in rights) {
                    [navigator setNavigationItemWithParam:param position:idx completion:nil withContainer:container];
                }
            }
            else {
                [navigator setNavigationItemWithParam:styles[obj] position:idx completion:nil withContainer:container];
            }
        }];
    }
    else {
        [navigator setNavigationBarHidden:YES animated:NO withContainer:container];
    }
}

- (void)_parse:(NSDictionary *)param resultBlock:(void(^)(NSDictionary *))result
{
    NSMutableDictionary *dict = [NSMutableDictionary new];
    NSString *type = param[@"type"];

    [dict setObject:self.weexInstance.instanceId forKey:@"instanceId"];
    [dict setObject:self.ref forKey:@"nodeRef"];

    if ([type isEqualToString:@"text"]) {
        NSDictionary *attr = param[@"attr"];
        NSString *title = attr[@"value"];
        if (title) {
            [dict setObject:title forKey:kBarItemText];
        }

        NSDictionary *style = param[@"style"];
        NSString *color = style[@"color"];
        if (color) {
            [dict setObject:color forKey:kBarItemTextColor];
        }
    }
    else if ([type isEqualToString:@"image"]) {
        NSDictionary *attr = param[@"attr"];
        NSString *src = attr[@"src"];
        if (src) {
            [dict setObject:src forKey:kBarItemIcon];
        }
    }
    result(dict);
}

@end


text:
package eu.over9000.cathode.resources;

import eu.over9000.cathode.Result;
import eu.over9000.cathode.data.TopGameList;
import eu.over9000.cathode.data.parameters.OffsetPagination;

/**
 * <pre>
 * /games/top                                  GET			getTopGames(OffsetPagination pagination);
 * </pre>
 */
public interface Games {

	String PATH = "games";

	Result<TopGameList> getTopGames(OffsetPagination pagination);
}


text:
<select #selectList (change)="redditSelect.emit(selectList.value)">
            <option *ngFor="let reddit of availableReddits">
                {{reddit}}
            </option>
</select>


text:
<?php

class Twig_Tests_Extension_IntlTest extends PHPUnit_Framework_TestCase
{
    /**
     * @requires extension intl
     * @requires PHP 5.5
     */
    public function testLocalizedDateFilterWithDateTimeZone()
    {
        class_exists('Twig_Extensions_Extension_Intl');
        $env = $this->getMockBuilder('Twig_Environment')->disableOriginalConstructor()->getMock();

        if (defined('HHVM_VERSION_ID')) {
            $timezone = 'Europe/Paris';
        } else {
            $timezone = '+01:00';
        }

        $date = twig_localized_date_filter($env, new DateTime('2015-01-01T00:00:00', new DateTimeZone('UTC')), 'short', 'long', 'en', $timezone);
        $this->assertEquals('1/1/15 1:00:00 AM GMT+01:00', $date);
    }
}


text:
FROM ruby:2.3.1
RUN apt-get update -qq && apt-get install -y build-essential
RUN curl -sL https://deb.nodesource.com/setup | bash -
RUN apt-get update -qq && apt-get install -y nodejs

RUN mkdir /app

WORKDIR /tmp
COPY Gemfile Gemfile
COPY Gemfile.lock Gemfile.lock
RUN bundle install

WORKDIR /app
CMD bundle exec middleman


text:
'use strict';
var
    local = require('./local'),
    _ = require('underscore');

var maxHistoryEntries = 30;

function extractEditorSources(content) {
    var sources = [];

    for (var i = 0; i < content.length; i++) {
        var component = content[i];
        if (component.content) {
            var subsources = extractEditorSources(component.content);
            if (subsources.length > 0) {
                sources = sources.concat(subsources);
            }
        } else if (component.componentName === 'codeEditor') {
            sources.push({
                lang: component.componentState.lang,
                source: component.componentState.source,
            });
        }
    }

    return sources;
}

function list() {
    var stringifiedHistory = local.get('history');
    return JSON.parse(stringifiedHistory ? stringifiedHistory : '[]');
}

function getArrayWithJustTheCode(editorSources) {
    return _.pluck(editorSources, 'source');
}

function getSimilarSourcesIndex(completeHistory, sourcesToCompareTo) {
    var duplicateIdx = -1;

    for (var i = 0; i < completeHistory.length; i++) {
        var diff = _.difference(sourcesToCompareTo, getArrayWithJustTheCode(completeHistory[i].sources));
        if (diff.length === 0) {
            duplicateIdx = i;
            break;
        }
    }

    return duplicateIdx;
}

function push(stringifiedConfig) {
    var config = JSON.parse(stringifiedConfig);
    var sources = extractEditorSources(config.content);
    if (sources.length > 0) {
        var completeHistory = list();
        var duplicateIdx = getSimilarSourcesIndex(completeHistory, getArrayWithJustTheCode(sources));

        if (duplicateIdx === -1) {
            while (completeHistory.length >= maxHistoryEntries) {
                completeHistory.shift();
            }

            completeHistory.push({
                dt: Date.now(),
                sources: sources,
                config: config,
            });
        } else {
            var entry = completeHistory[duplicateIdx];
            entry.dt = Date.now();
        }

        local.set('history', JSON.stringify(completeHistory));
    }
}

function sortedList() {
    var sorted = list();

    sorted.sort(function (a, b) {
        return b.dt - a.dt;
    });

    return sorted;
}

function sources(language) {
    var sourcelist = [];
    _.each(sortedList(), function (entry) {
        _.each(entry.sources, function (source) {
            if (source.lang === language) {
                sourcelist.push({
                    dt: entry.dt,
                    source: source.source,
                });
            }
        });
    });

    return sourcelist;
}

module.exports = {
    push: _.debounce(push, 500),
    list: list,
    sortedList: sortedList,
    sources: sources,
};


text: extern const mp_obj_module_t time_module;


text:
package org.nanocontainer.webcontainer;

import org.mortbay.jetty.webapp.WebXmlConfiguration;
import org.mortbay.jetty.servlet.ServletHolder;
import org.mortbay.jetty.servlet.FilterHolder;
import org.picocontainer.PicoContainer;
import org.picocontainer.defaults.DefaultPicoContainer;

public class PicoWebXmlConfiguration extends WebXmlConfiguration {

    private PicoContainer parentContainer;

    public PicoWebXmlConfiguration(PicoContainer parentContainer) {
        this.parentContainer = parentContainer;
    }

    protected ServletHolder newServletHolder() {
        return new PicoServletHolder(parentContainer);
    }

    protected FilterHolder newFilterHolder() {
        return new PicoFilterHolder(parentContainer);
    }

    protected Object newListenerInstance(Class clazz) throws InstantiationException, IllegalAccessException {
        DefaultPicoContainer child = new DefaultPicoContainer(parentContainer);
        child.registerComponentImplementation("listener", clazz);
        return child.getComponentInstance("listener");
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Online_Store.Core.Providers;
using Online_Store.Data;
using Online_Store.Models;

namespace Online_Store.Commands.ProductCommands
{
    public class ListProductsOnSaleCommand : Command, ICommand
    {
        public ListProductsOnSaleCommand(IStoreContext context, IWriter writer, IReader reader) : base(context, writer, reader)
        {
        }

        public override string Execute()
        {

            var productsOnSale = base.context.Products.Where(p => p.Sale.PriceReduction > 0).Select(p => p.ProductName);

            StringBuilder result = new StringBuilder();
            foreach (var product in productsOnSale)
            {
                result.Append(product);
            }

            return result.ToString();
        }
    }
}


text:
package net.tridentsdk.server.entity.living;

import net.tridentsdk.base.Position;
import net.tridentsdk.entity.living.Player;
import net.tridentsdk.entity.living.Skeleton;
import net.tridentsdk.entity.types.EntityType;
import net.tridentsdk.event.entity.EntityDamageEvent;
import net.tridentsdk.inventory.Item;
import net.tridentsdk.server.entity.TridentLivingEntity;

import java.util.UUID;

/**
 * Represents a skeleton
 *
 * @author The TridentSDK Team
 */
public class TridentSkeleton extends TridentLivingEntity implements Skeleton {
    public TridentSkeleton(UUID uuid, Position spawnPosition) {
        super(uuid, spawnPosition);
    }

    @Override
    public boolean isWither() {
        return false;
    }

    @Override
    public Item[] equipment() {
        return new Item[0];
    }

    @Override
    public void setEquipment(Item[] stack) {

    }

    @Override
    public EntityDamageEvent lastDamageEvent() {
        return null;
    }

    @Override
    public Player lastPlayerDamager() {
        return null;
    }

    @Override
    public EntityType type() {
        return EntityType.SKELETON;
    }
}


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateEveEveAllianceListMemberCorporations extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('eve_alliancelist_membercorporations', function(Blueprint $table)
		{
		  $table->increments('id');

		  // Id for the many to one relationship from class
		  // EveEveAllianceList
		  $table->integer('allianceID');

		  $table->integer('corporationID');
		  $table->dateTime('startDate');

		  $table->timestamps();
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		Schema::dropIfExists('eve_alliancelist_membercorporations');
	}
}


text:
from abc import ABC, abstractmethod

class List(ABC):

    def __init__(self):
        self._head = None
        self._tail = None
        self._len = 0
        self._currentNode = None
    @abstractmethod
    def __len__(self):
        pass

    @abstractmethod
    def __next__(self):
        pass

    @abstractmethod
    def __getitem__(self, key):
        pass

    @abstractmethod
    def __setitem__(self, key):
        pass

    @abstractmethod
    def __iter__(self):
        pass