text:
require 'net/ftp'

module Royalty
  module Reportable # rubocop:disable Metrics/ModuleLength
    extend ActiveSupport::Concern
    include ActionView::Helpers::NumberHelper

    # No longer using Box, write to disk (/tmp) instead: HELIO-4066
    def send_reports(type, reports)
      dir = File.join("/tmp", type, "#{@start_date.strftime("%Y-%m")}_to_#{@end_date.strftime("%Y-%m")}")
      FileUtils.mkdir_p dir
      reports.each do |name, report|
        file = File.join(dir, name)
        File.write(file, CounterReporterService.csv(report))
        Rails.logger.info("[ROYALTY REPORTS] wrote #{file}")
      end
    rescue StandardError => e
      "[ROYALTY REPORTS] Error: #{e}\n#{e.backtrace.join("\n")}"
    end

    def format_hits(items)
      items.each do |item|
        item["Hits"] = number_with_delimiter(item["Hits"])
        item.map { |k, v| item[k] = number_with_delimiter(v) if k.match?(/\w{3}-\d{4}/) } # matches "Jan-2019" or whatever
      end
      items
    end

    def add_hebids(items)
      items.each_with_index do |item, index|
        monograph_noid = item["Parent_Proprietary_ID"]
        monograph_noid_idx = item.keys.index("Parent_Proprietary_ID")
        items[index] = item.to_a.insert(monograph_noid_idx + 1, ["hebid", hebids[monograph_noid]]).to_h
      end
      items
    end

    def add_copyright_holder_to_combined_report(all_items)
      all_items.each_with_index do |item, index|
        monograph_noid = item["Parent_Proprietary_ID"]
        publisher_idx = item.keys.index("Publisher")
        all_items[index] = item.to_a.insert(publisher_idx + 1, ["Copyright Holder", copyright_holders[monograph_noid]]).to_h
      end
      all_items
    end

    def reclassify_isbns(items)
      # Because of metadata cleanup, we can rely on ISBN formats being strict, like:
      # 9780520047983 (hardcover), 9780520319196 (ebook), 9780520319189 (paper)
      # So this exact matching should always work. Supposedly.
      items.each_with_index do |item, index|
        isbns = item["ISBN"].split(",")
        isbn_idx = item.keys.index("ISBN")

        hardcover = ""
        ebook = ""
        paper = ""
        isbns.each do |isbn|
          hardcover = isbn.gsub(/ \(hardcover\)/, "").strip if isbn.match?(/hardcover/)
          ebook = isbn.gsub(/ \(ebook\)/, "").strip if isbn.match?(/ebook/)
          paper = isbn.gsub(/ \(paper\)/, "").strip if isbn.match?(/paper/)
        end

        new_item =     item.to_a.insert(isbn_idx + 1, ["ebook ISBN", ebook])
        new_item = new_item.to_a.insert(isbn_idx + 2, ["hardcover ISBN", hardcover])
        new_item = new_item.to_a.insert(isbn_idx + 3, ["paper ISBN", paper]).to_h
        new_item.delete("ISBN")
        # remove these from the usage report per HELIO-3572
        new_item.delete("Parent_ISBN")
        new_item.delete("Parent_Print_ISSN")
        new_item.delete("Parent_Online_ISSN")
        items[index] = new_item
      end
      items
    end

    def hebids
      return @hebids if @hebids.present?
      @hebids = {}
      docs = ActiveFedora::SolrService.query("{!terms f=press_sim}#{@subdomain}", fl: ['id', 'identifier_tesim'], rows: 100_000)
      docs.each do |doc|
        identifier = doc['identifier_tesim']&.find { |i| i[/^heb_id:\ heb[0-9].*/] } || ''
        @hebids[doc["id"]] = identifier.split(": ")[1]
      end
      @hebids
    end

    def items_by_copyholders(items)
      return @items_by_copyholders if @items_by_copyholders.present?
      @items_by_copyholders = {}
      items.each do |item|
        this_copyholder = copyright_holders[item["Parent_Proprietary_ID"]]
        @items_by_copyholders[this_copyholder] = [] if @items_by_copyholders[this_copyholder].nil?
        @items_by_copyholders[this_copyholder] << item
      end
      @items_by_copyholders
    end

    def copyright_holders
      return @copyright_holders if @copyright_holders
      @copyright_holders = {}
      docs = ActiveFedora::SolrService.query("{!terms f=press_sim}#{@subdomain}", fl: ['id', 'copyright_holder_tesim'], rows: 100_000)
      docs.each do |doc|
        if doc["copyright_holder_tesim"].blank? || doc["copyright_holder_tesim"].first.blank?
          @copyright_holders[doc["id"]] = "no copyright holder"
        else
          @copyright_holders[doc["id"]] = doc["copyright_holder_tesim"].first
        end
      end
      @copyright_holders
    end

    def total_hits_all_rightsholders(items)
      return @total_hits_all_rightsholders if @total_hits_all_rightsholders.present?
      @total_hits_all_rightsholders = 0
      items.each do |item|
        @total_hits_all_rightsholders += item["Hits"].to_i
      end
      @total_hits_all_rightsholders
    end

    def item_report
      CounterReporter::ItemReport.new(params).report
    end
  end
end


text:
angular-route-urls
==================

Example of a simple service (see route-urls.js) to construct application URLs
from Angular's standard routing configuration.

Most of the other files in the repo are an example of how it might be used, but
basically:

1. Give each route a name that is meaningful to your application, e.g.

    ```
    $routeProvider.when("/product/:id/stock/:store", {
        name: "product:stock",
        ... usual stuff ...
    });
    ```

2. Put the `urls` service in the root scope so it's available application-wide.

3. Reference pages by name, together with any params needed to build the URL, e.g.

    ```
    <a href="{{ urls.href('product:stock', {id: 1, store: 'Leeds'}) }}">
        Product 1, Leeds
    </a>
    ```

In the case where each named group in a route URL has a unique name and the
order of the named groups is well known, paths can also be constructed by
passing replacement values as positional args instead of a {name: value} map,
e.g.

    ```
    <a href="{{ urls.href('product:stock', 1, 'Leeds') }}">Product 1, Leeds</a>
    ```

redpajama_set_name: RedPajamaGithub


text:
Whenever a new tab is opened it has a picture, random font and a famous / attributed qoute. This is an extension for the chrome web browser.

**Future Additions**
- Need new image 75
- Button pannel at bottum left
- Automatic Change Every Minute

*All images should be borrowed under a Creative Commons License (pexels.com has plenty)*
*'' fairly low contrast near text area.

`All fonts should be cited in fontcredits.txt`


text:
namespace Telemachy.Planners.Core.Platform.Dialogs
{
    /// <summary>
    /// Represents the contract for a dialog result.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public interface IDialogResult<T>
    {
        /// <summary>
        /// Postive (=true) or negative (=false)
        /// </summary>
        bool Ok { get; }

        /// <summary>
        /// A result value.
        /// </summary>
        T Value { get; }
    }
}


text:
<!doctype html>

    <meta charset="UTF-8">
    <title>sTab</title>

    <link rel="stylesheet" href="app/stylesheets/screen.css">

Histograph

        <input type="text" class="grow"
               ng-model="mainSearch"
               ng-keyup="setFilter($event)"
               ng-show="showSearch">


text:
#!/usr/bin/env node

var fs = require('fs');
var path = require('path');
var url = require('url');

var optimist = require('optimist');
var async = require('async');
var Client = require('service-registry-client').Client;
var log = require('logmagic').local('scripts.generate-fixtures');
var sprintf = require('sprintf').sprintf;
var request = require('rackspace-shared-utils/lib/request');
var origRequest = require('rackspace-shared-utils/lib/request').request;

var client = new Client('joe', 'dev', null, {'debug': true,
  'url': 'http://127.0.0.1:9000/v1.0/',
  'authUrl': 'http://127.0.0.1:23542/v2.0',
  'raw': true});

var PUBLIC_ENDPOINT_URL = 'https://dfw.registry.api.rackspacecloud.com/';
var SERVICE_ID1 = 'dfw1-api';
var HEARTBEAT_TIMEOUT = 3;

var TOKENS = [
  '6bc8d050-f86a-11e1-a89e-ca2ffe480b20',
  '36865510-f7da-11e1-b732-793f90dd0c35'
];

var TIMESTAMPS = [
  1346967146190,
  1346967146370
];

var WRITE_MOCK_REQUESTS = true;

var argv = require('optimist')
    .usage('Usage: $0 --out=<output folder>')
    .default('out', 'fixtures')
    .argv;

var fixtureDirs = [argv.out, path.join(argv.out,'/request'), path.join(argv.out, '/response')];

function writeFixtureFile(fixturePath, data, callback) {
  fs.writeFile(fixturePath, data, callback);
}

function checkDir(dir, callback) {
  log.infof('checkDir');

  fs.mkdir(dir, function(err) {
    if (err && err.code === 'EEXIST') {
      err = null;
    }
    callback(err);
  });
}

function replaceDynamicValues(data) {
  var value, counter = 0, counter1 = 0;

  data.values.forEach(function(value) {
    // Events
    if (value.hasOwnProperty('payload')) {
      if (value.hasOwnProperty('id')) {
        value.id = TOKENS[counter++];
      }

      if (value.hasOwnProperty('timestamp')) {
        value.timestamp = TIMESTAMPS[counter++];
      }
    }
  });

  return data;
}

request.request = function(reqUrl, method, body, options, callback) {
  // We mock the request function so we can save the request fixtures
  var reqPath = url.parse(reqUrl).pathname.replace('/v1.0/7777/', '').replace('/', '-'),
      filePath = sprintf('./fixtures/request/%s-%s.json', reqPath, method.toLowerCase()),
      reqBody = body;

  if (WRITE_MOCK_REQUESTS && reqUrl.indexOf('/v1.0/7777') !== -1 && body) {
    reqBody = JSON.parse(reqBody);

    // Do any body processing here before stringifying it back

    reqBody = JSON.stringify(reqBody, null, 4);
    fs.writeFileSync(filePath, reqBody, 'utf8');
  }

  origRequest.apply(this, arguments);
};

function main() {
  var requestDir = path.join(argv.out, 'request'),
      responseDir = path.join(argv.out, 'response');

  async.waterfall([
    function createFixtureDirs(callback) {
      async.forEachSeries(fixtureDirs, checkDir, callback);
    },

    function getLimits(callback) {
      log.infof('getLimits');
      client.account.getLimits(function(err, data) {
        callback(err, data);
      });
    },

    function writeLimitsFixture(data, callback) {
      log.infof('writeLimitsFixture');
      var fixturePath = sprintf('./%s/limits-get.json', responseDir);

      writeFixtureFile(fixturePath, data.body, callback);
    },

    function getServiceNotFound(callback) {
      log.infof('getServiceNotFound');
      client.services.get('srvNotFound', function(err, data) {
        callback(null, err.response);
      });
    },

    function writeServiceNotFoundFixture(data, callback) {
      log.infof('writeServiceNotFoundFixture');
      var fixturePath = sprintf('./%s/services-not-found-get.json', responseDir),
          fixtureData = JSON.parse(data.body);

      fixtureData.txnId = '.rh-qyek.h-farscape.r-q3i5psGp.c-3.ts-1347320188220.v-0.1';
      writeFixtureFile(fixturePath, JSON.stringify(fixtureData, null, 4), callback);
    },

    function createServiceNoTags(callback) {
      log.infof('createServiceNoTags');
      client.services.create('dfw1-api', HEARTBEAT_TIMEOUT, {}, function(err, data) {
        callback(err);
      });
    },

    function createService(callback) {
      log.infof('createService');
      var payload = {
        'tags': ['database', 'mysql'],
        'metadata': {'region': 'dfw', 'port': '3306', 'ip': '127.0.0.1',
                     'version': '5.5.24-0ubuntu0.12.04.1 (Ubuntu)'}
      };

      client.services.create('dfw1-db1', HEARTBEAT_TIMEOUT, payload, function(err, data) {
        callback(err, JSON.parse(data.body));
      });
    },

    function writeHeartbeatRequestFixture(data, callback) {
      log.infof('writeHeartbeatRequestFixture');
      var fixturePath = sprintf('./%s/service-%s-heartbeat-post.json',
                                requestDir, SERVICE_ID1);

      writeFixtureFile(fixturePath, JSON.stringify(data, null, 4), function() {
        callback(null, data);
      });
    },

    // Heartbeat response is the same as create service response
    function writeHeartbeatResponseFixture(data, callback) {
      data.token = TOKENS[1];

      log.infof('writeHeartbeatRequestFixture');
      var fixturePath = sprintf('./%s/services-%s-heartbeat-post.json',
                                responseDir, SERVICE_ID1);

      writeFixtureFile(fixturePath, JSON.stringify(data, null, 4), callback);
    },

    function getService(callback) {
      log.infof('getService');
      client.services.get('dfw1-db1', function(err, data) {
        callback(err, data);
      });
    },

    function writeServiceFixture(data, callback) {
      log.infof('writeServiceFixture');
      var fixturePath = sprintf('./%s/services-dfw1-db1-get.json', responseDir),
          fixtureData = JSON.parse(data.body);

      writeFixtureFile(fixturePath, JSON.stringify(fixtureData, null, 4), callback);
    },

    function listServices(callback) {
      log.infof('listServices');
      client.services.list(null, function(err, data, nextMarker) {
        callback(err, data);
      });
    },

    function writeListServicesFixture(data, callback) {
      log.infof('writeListServicesFixture');
      var fixturePath = sprintf('%s/services-get.json', responseDir),
          fixtureData = JSON.parse(data.body);

      fixtureData = replaceDynamicValues(fixtureData);
      fixtureData = JSON.stringify(fixtureData, null, 4);
      writeFixtureFile(fixturePath, fixtureData, callback);
    },

    function listServicesForTag(callback) {
      log.infof('listServicesForTag');
      client.services.listForTag('database', {}, function(err, data) {
        callback(err, data);
      });
    },

    function writeListServicesForTagFixture(data, callback) {
      log.infof('writeListServicesForTagFixture');
      var fixturePath = sprintf('%s/services-tag-database-get.json', responseDir),
          fixtureData = JSON.parse(data.body);

      fixtureData = replaceDynamicValues(fixtureData);
      fixtureData = JSON.stringify(fixtureData, null, 4);
      writeFixtureFile(fixturePath, fixtureData, callback);
    },

    function listServicesWithLimit(callback) {
      log.infof('listServicesWithLimit');
      client.services.list({'limit': 1}, function(err, data, nextMarker) {
        callback(err, data);
      });
    },

    function writeFixture(data, callback) {
      var fixturePath = sprintf('%s/services-get-limit-1-page-1.json', responseDir),
          fixtureData = JSON.parse(data.body);

      fixtureData.metadata.next_href = fixtureData.metadata.next_href.replace(/https:\/\/(.*?)\//, PUBLIC_ENDPOINT_URL);
      writeFixtureFile(fixturePath, JSON.stringify(fixtureData, null, 4), callback);
    },

    function listServicesWithMarker(callback) {
      log.infof('listServicesWithLimit');
      client.services.list({'marker': 'dfw1-db1'}, function(err, data, nextMarker) {
        callback(err, data);
      });
    },

    function writeFixture(data, callback) {
      var fixturePath = sprintf('%s/services-get-with-marker-page-2.json', responseDir),
          fixtureData = JSON.parse(data.body);

      writeFixtureFile(fixturePath, JSON.stringify(fixtureData, null, 4), callback);
    },

    function removeService(callback) {
      log.infof('removeService');
      client.services.remove('dfw1-db1', function(err) {
        callback(err);
      });
    },

    function setConfigurationValues(callback) {
      var keys = ['configId', 'configId1', 'configId2'];

      async.forEach(keys, function(key, callback) {
        client.configuration.set(key, 'test value 123456', callback);
      }, callback);
    },

    function getConfigurationValue(callback) {
      client.configuration.get('configId', function(err, data) {
        callback(err, data);
      });
    },

    function writeGetConfigurationFixture(data, callback) {
      log.infof('writeGetConfigurationFixture');
      var fixturePath = sprintf('./%s/configuration-configId-get.json', responseDir);

      writeFixtureFile(fixturePath, data.body, callback);
    },

    function removeConfigurationValue(callback) {
      var key = 'configId';

      client.configuration.remove(key, callback);
    },

    function setConfigurationValuesWithANamespace(callback) {
      WRITE_MOCK_REQUESTS = false;

      var keys = [
        '/production/cassandra/listen_ip',
        '/production/cassandra/listen_port',
        '/production/cassandra/rpc_server/type',
        '/production/cassandra/rpc_server/timeout',
        '/production/zookeeper/listen_ip',
        '/production/zookeeper/listen_port',
      ];

      log.infof('setConfigurationValuesWithANamespace');

      async.forEach(keys, function(key, callback) {
        var value = 'value for ' + key;
        client.configuration.set(key, value, callback);
      }, callback);
    },

    function listConfiguration(callback) {
      WRITE_MOCK_REQUESTS = true;

      log.infof('writeGetConfigurationFixture');
      client.configuration.list({}, function(err, data, nextMarker) {
        callback(err, data);
      });
    },

    function writeListConfigurationFixture(data, callback) {
      var fixturePath = sprintf('./%s/configuration-get.json', responseDir);

      writeFixtureFile(fixturePath, data.body, callback);
    },

    function listConfigurationValuesForANamespace(callback) {
      var fixturePath = sprintf('./%s/configuration-get-for-namespace.json', responseDir);

      log.infof('listConfigurationValuesForANamespace');
      client.configuration.listForNamespace('/production/cassandra', null, function(err, data) {
        writeFixtureFile(fixturePath, data.body, callback);
        callback();
      });
    },

    // Wait before listening events so the services expires and we get timeout
    // event
    function wait(callback) {
      setTimeout(callback, 3200);
    },

    function listEvents(callback) {
      log.infof('listEvents');
      client.events.list(null, {}, function(err, data, nextMarker) {
        callback(err, data);
      });
    },

    function writeEventsFixture(data, callback) {
      log.infof('writeEventsFixture');
      var fixturePath = sprintf('./%s/events-get.json', responseDir),
          fixtureData = JSON.parse(data.body),
          events;

      fixtureData = replaceDynamicValues(fixtureData);
      events = fixtureData.values;
      fixtureData = JSON.stringify(fixtureData, null, 4);
      writeFixtureFile(fixturePath, fixtureData, function(err) {
        callback(err, events);
      });
    },

    function writeEventTypesPartials(events, callback) {
      var typeToFileMap, eventType, fileName, eventItem, fixturePath, data;

      typeToFileMap = {
        'service.join': 'events-partial-service.join.json',
        'service.timeout': 'events-partial-service.timeout.json',
        'service.remove': 'events-partial-service.remove.json',
        'configuration_value.update': 'events-partial-configuration_value.update.json',
        'configuration_value.remove': 'events-partial-configuration_value.remove.json',
      };

      function getMatchingEventItem(type) {
        var eventItem = events.filter(function(item) {
          return (item.type === type);
        })[0];

        return eventItem;
      }

      for (eventType in typeToFileMap) {
        if (typeToFileMap.hasOwnProperty(eventType)) {
          fileName = typeToFileMap[eventType];
          eventItem = getMatchingEventItem(eventType);

          fixturePath = sprintf('./%s/%s', responseDir, fileName);
          data = JSON.stringify(eventItem, null, 4);
          fs.writeFileSync(fixturePath, data, 'utf-8');
        }
      }

      callback();
    }
  ],

  function(err) {
    if (err) {
      log.errorf('Error: ${err}', {'err': err});
      return;
    }

    log.info('Fixture generation successful');
    return;
  });
}

main();


text:
/**
 * `ssl_check=1` requests from Slack - https://api.slack.com/interactivity/slash-commands
 */
package com.slack.api.app_backend.ssl_check;


text:
import numpy as np
from numpy.testing import assert_array_equal

from vispy.testing import run_tests_if_main
from vispy.geometry.meshdata import MeshData

def test_meshdata():
    """Test meshdata Class
       It's a unit square cut in two triangular element
    """
    square_vertices = np.array([[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0]],
                               dtype=np.float)
    square_faces = np.array([[0, 1, 2], [0, 2, 3]], dtype=np.uint)
    square_normals = np.array([[0, 0, 1], [0, 0, 1], [0, 0, 1], [0, 0, 1]],
                              dtype=np.float)
    square_edges = np.array([[0, 1], [0, 2], [0, 3], [1, 2], [2, 3]],
                            dtype=np.uint)

    mesh = MeshData(vertices=square_vertices, faces=square_faces)
    # test vertices and faces assignement
    assert_array_equal(square_vertices, mesh.get_vertices())
    assert_array_equal(square_faces, mesh.get_faces())
    # test normals calculus
    assert_array_equal(square_normals, mesh.get_vertex_normals())
    # test edge calculus
    assert_array_equal(square_edges, mesh.get_edges())

run_tests_if_main()


text:
package io.gatling.core.filter

import org.scalatest.Inspectors
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.mockito.MockitoSugar

class FiltersSpec extends AnyFlatSpec with Matchers with MockitoSugar with Inspectors {
  private val hosts = List(
    "http://takima.fr",
    "http://ebusinessinformation.fr",
    "https://gatling.io"
  )

  private val paths = List(
    "",
    "/infos.html",
    "/assets/images/foo.png",
    "/assets/js/bar.js"
  )

  private val urls = for {
    host <- hosts
    path <- paths
  } yield host + path

  private val allowList = new AllowList(List("http://takima\\.fr.*"))
  private val denyList = new DenyList(List("http[s]?://.*/assets/.*"))

  private def checkRequestAccepted(filters: Filters, partition: (List[String], List[String])): Unit = {
    val (expectedAccepted, expectedRejected) = partition

    forAll(expectedAccepted) {
      filters.accept(_) shouldBe true
    }
    forAll(expectedRejected) {
      filters.accept(_) shouldBe false
    }
  }

  "Filters" should "filter AllowList correctly when DenyList is empty" in {
    checkRequestAccepted(new Filters(allowList, DenyList.Empty), urls.partition(_.contains("takima")))
  }

  it should "filter AllowList then DenyList when both are specified on allow-first mode" in {
    checkRequestAccepted(
      new Filters(allowList, denyList),
      urls.partition { url =>
        url.contains("takima") && !url.contains("assets")
      }
    )
  }

  it should "filter DenyList correctly when AllowList is empty" in {
    checkRequestAccepted(
      new Filters(denyList, AllowList.Empty),
      urls.partition { url =>
        !url.contains("assets")
      }
    )
  }

  it should "filter DenyList then AllowList when both are specified on deny-first mode" in {
    checkRequestAccepted(
      new Filters(denyList, allowList),
      urls.partition { url =>
        !url.contains("assets") && url.contains("takima")
      }
    )
  }

  it should "filter correctly when there are multiple patterns" in {
    val patterns = List(".*foo.*", ".*bar.*")
    val url = "https://gatling.io/foo.html"

    new DenyList(patterns).accept(url) shouldBe false
    new AllowList(patterns).accept(url) shouldBe true
  }

  it should "filter correctly when there are no patterns" in {
    val url = "https://gatling.io/foo.html"
    new DenyList(Nil).accept(url) shouldBe true
    new AllowList(Nil).accept(url) shouldBe true
  }

  it should "be able to deal with incorrect patterns" in {
    val w = new AllowList(List("http://foo\\.com.*", "},{"))
    w.regexes should not be empty
    w.accept("http://foo.com/bar.html") shouldBe true
  }
}


text:
import { Observable } from '../../Observable';
import { delayWhen } from '../../operator/delayWhen';

Observable.prototype.delayWhen = delayWhen;

declare module '../../Observable' {
  interface Observable<T> {
    delayWhen: typeof delayWhen;
  }
}


text:
<?php

use yii\db\Schema;
use yii\db\Migration;

class m150528_130124_discount_request_addField_type extends Migration
{
    public function up()
    {
        $this->addColumn('{{%discount_request}}','type',Schema::TYPE_STRING);
    }

    public function down()
    {
        return $this->dropColumn('{{%discount_request}}','type');
    }

    /*
    // Use safeUp/safeDown to run migration code within a transaction
    public function safeUp()
    {
    }

    public function safeDown()
    {
    }
    */
}


text:
package com.evolveum.midpoint.model.impl.lens;

import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertNotNull;

import java.io.File;
import java.io.IOException;

import javax.xml.bind.JAXBException;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.ContextConfiguration;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;

import com.evolveum.midpoint.model.common.stringpolicy.StringPolicyUtils;
import com.evolveum.midpoint.model.common.stringpolicy.ValuePolicyProcessor;
import com.evolveum.midpoint.model.impl.AbstractInternalModelIntegrationTest;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.util.PrismTestUtil;
import com.evolveum.midpoint.schema.constants.SchemaConstants;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.test.util.TestUtil;
import com.evolveum.midpoint.util.exception.CommunicationException;
import com.evolveum.midpoint.util.exception.ConfigurationException;
import com.evolveum.midpoint.util.exception.ExpressionEvaluationException;
import com.evolveum.midpoint.util.exception.ObjectNotFoundException;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.exception.SecurityViolationException;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.StringLimitType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.StringPolicyType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ValuePolicyType;

@ContextConfiguration(locations = {"classpath:ctx-model-test-main.xml"})
@DirtiesContext(classMode = ClassMode.AFTER_CLASS)
public class TestPasswordPolicy extends AbstractInternalModelIntegrationTest {

    public static final File TEST_DIR =  new File("src/test/resources/lens/ppolicy/");

    private static final transient Trace LOGGER = TraceManager.getTrace(TestPasswordPolicy.class);

    private static final String USER_AB_USERNAME = "ab";
    private static final String USER_AB_FULL_NAME = "Ad Fel";
    private static final String USER_AB_GIVEN_NAME = "Ad";
    private static final String USER_AB_FAMILY_NAME = "Fel";
    private static final String USER_AB_ADDITIONAL_NAME = "x";
    private static final int USERNAME_ATTEMPTS = 200;
    private static final int USER_PROPS_ATTEMPTS = 5000;

    @Autowired(required = true)
    private ValuePolicyProcessor valuePolicyProcessor;

    @Test
    public void stringPolicyUtilsMinimalTest() throws JAXBException, SchemaException, IOException {
        File file = new File(TEST_DIR, "password-policy-minimal.xml");
        ValuePolicyType pp = (ValuePolicyType) PrismTestUtil.parseObject(file).asObjectable();
        StringPolicyType sp = pp.getStringPolicy();
        StringPolicyUtils.normalize(sp);
        AssertJUnit.assertNotNull(sp.getCharacterClass());
        AssertJUnit.assertNotNull(sp.getLimitations().getLimit());
        AssertJUnit.assertTrue(Integer.MAX_VALUE == sp.getLimitations().getMaxLength());
        AssertJUnit.assertTrue(0 == sp.getLimitations().getMinLength());
        AssertJUnit.assertTrue(0 == " !\"#$%&'()*+,-.01234567890:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
                .compareTo(sp.getCharacterClass().getValue()));
    }

    @Test
    public void stringPolicyUtilsComplexTest() {
        final String TEST_NAME = "stringPolicyUtilsComplexTest";
        TestUtil.displayTestTitle(TEST_NAME);

        File file = new File(TEST_DIR, "password-policy-complex.xml");
        ValuePolicyType pp = null;
        try {
            pp = (ValuePolicyType) PrismTestUtil.parseObject(file).asObjectable();
        } catch (Exception e) {
            e.printStackTrace();
        }

        StringPolicyType sp = pp.getStringPolicy();
        StringPolicyUtils.normalize(sp);
    }

    @Test
    public void testPasswordGeneratorComplexNegative() throws Exception {
        final String TEST_NAME = "testPasswordGeneratorComplexNegative";
        TestUtil.displayTestTitle(TEST_NAME);

        Task task = createTask(TEST_NAME);
        OperationResult result = task.getResult();

        File file = new File(TEST_DIR, "password-policy-complex.xml");
        ValuePolicyType pp = (ValuePolicyType) PrismTestUtil.parseObject(file).asObjectable();

        // Make switch some cosistency
        pp.getStringPolicy().getLimitations().setMinLength(2);
        pp.getStringPolicy().getLimitations().setMinUniqueChars(5);

        // WHEN
        TestUtil.displayWhen(TEST_NAME);
        String psswd = valuePolicyProcessor.generate(SchemaConstants.PATH_PASSWORD_VALUE, pp, 10, false, null, TEST_NAME, task, result);

        // THEN
        TestUtil.displayThen(TEST_NAME);
        display("Generated password", psswd);
        result.computeStatus();
        AssertJUnit.assertTrue(result.isAcceptable());
        assertNotNull(psswd);

        // Switch to all must be first :-) to test if there is error
        for (StringLimitType l : pp.getStringPolicy().getLimitations().getLimit()) {
            l.setMustBeFirst(true);
        }
        LOGGER.info("Negative testing: passwordGeneratorComplexTest");
        try {
            valuePolicyProcessor.generate(SchemaConstants.PATH_PASSWORD_VALUE, pp, 10, false, null, TEST_NAME, task, result);
            assertNotReached();
        } catch (ExpressionEvaluationException e) {
            result.computeStatus();
            TestUtil.assertFailure(result);
        }
    }

    @Test
    public void testPasswordGeneratorComplex() throws Exception {
        passwordGeneratorTest("testPasswordGeneratorComplex", "password-policy-complex.xml");
    }

    @Test
    public void testPasswordGeneratorLong() throws Exception {
        passwordGeneratorTest("testPasswordGeneratorLong", "password-policy-long.xml");
    }

    @Test
    public void testPasswordGeneratorNumeric() throws Exception {
        passwordGeneratorTest("testPasswordGeneratorNumeric", "password-policy-numeric.xml");
    }

    @Test
    public void testValueGeneratorMustBeFirst() throws Exception {
        passwordGeneratorTest("testValueGeneratorMustBeFirst", "value-policy-must-be-first.xml");
    }

    @Test
    public void testValueGenerateRandomPin() throws Exception {
        final String TEST_NAME = "testValueGenerateRandomPin";
        TestUtil.displayTestTitle(TEST_NAME);

        Task task = createTask(TEST_NAME);
        OperationResult result = task.getResult();

        ValuePolicyType pp = parsePasswordPolicy("value-policy-random-pin.xml");

        // WHEN
        TestUtil.displayWhen(TEST_NAME);
        String psswd = valuePolicyProcessor.generate(SchemaConstants.PATH_PASSWORD_VALUE, pp, 10, true, null, TEST_NAME, task, result);

        // THEN
        TestUtil.displayThen(TEST_NAME);
        display("Generated password", psswd);
        result.computeStatus();
        TestUtil.assertSuccess(result);
        assertNotNull(psswd);
        assertPassword(psswd, pp);

    }

    @Test
    public void testValueGenerate() throws Exception {
        final String TEST_NAME = "testValueGenerate";
        TestUtil.displayTestTitle(TEST_NAME);

        Task task = createTask(TEST_NAME);
        OperationResult result = task.getResult();

        ValuePolicyType pp = parsePasswordPolicy("value-policy-generate.xml");

        // WHEN
        TestUtil.displayWhen(TEST_NAME);
        String psswd = valuePolicyProcessor.generate(SchemaConstants.PATH_PASSWORD_VALUE, pp, 10, true, null, TEST_NAME, task, result);

        // THEN
        TestUtil.displayThen(TEST_NAME);
        display("Generated password", psswd);
        result.computeStatus();
        TestUtil.assertSuccess(result);
        assertNotNull(psswd);
        assertPassword(psswd, pp);

    }

    @Test
    public void testValueGenerateEmpty() throws Exception {
        final String TEST_NAME = "testValueGenerateEmpty";
        TestUtil.displayTestTitle(TEST_NAME);

        Task task = createTask(TEST_NAME);
        OperationResult result = task.getResult();

        File file = new File(TEST_DIR, "value-policy-generate-empty.xml");
        LOGGER.info("Positive testing {}: {}", "testValueGenerate", "value-policy-generate-empty.xml");
        ValuePolicyType pp = (ValuePolicyType) PrismTestUtil.parseObject(file).asObjectable();

        // WHEN
        TestUtil.displayWhen(TEST_NAME);
        String psswd = valuePolicyProcessor.generate(SchemaConstants.PATH_PASSWORD_VALUE, pp, 10, true, null, TEST_NAME, task, result);

        // THEN
        TestUtil.displayThen(TEST_NAME);
        display("Generated password", psswd);
        result.computeStatus();
        TestUtil.assertSuccess(result);
        assertNotNull(psswd);
        assertPassword(psswd, pp);
    }

    public void passwordGeneratorTest(final String TEST_NAME, String policyFilename) throws JAXBException, SchemaException, IOException, ExpressionEvaluationException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException {
        TestUtil.displayTestTitle(TEST_NAME);

        Task task = createTask(TEST_NAME);
        OperationResult result = task.getResult();

        File file = new File(TEST_DIR, policyFilename);
        LOGGER.info("Positive testing {}: {}", TEST_NAME, policyFilename);
        ValuePolicyType pp = (ValuePolicyType) PrismTestUtil.parseObject(file).asObjectable();

        String psswd;
        // generate minimal size passwd
        for (int i = 0; i < 100; i++) {
            psswd = valuePolicyProcessor.generate(SchemaConstants.PATH_PASSWORD_VALUE, pp, 10, true, null, TEST_NAME, task, result);
            LOGGER.info("Generated password:" + psswd);
            result.computeStatus();
            if (!result.isSuccess()) {
                LOGGER.info("Result:" + result.debugDump());
                AssertJUnit.fail("Password generator failed:\n"+result.debugDump());
            }
            assertNotNull(psswd);
            assertPassword(psswd, pp);
        }
        // genereata to meet as possible
        LOGGER.info("-------------------------");
        // Generate up to possible
        for (int i = 0; i < 100; i++) {
            psswd = valuePolicyProcessor.generate(SchemaConstants.PATH_PASSWORD_VALUE, pp, 10, false, null, TEST_NAME, task, result);
            LOGGER.info("Generated password:" + psswd);
            result.computeStatus();
            if (!result.isSuccess()) {
                LOGGER.info("Result:" + result.debugDump());
            }
            AssertJUnit.assertTrue(result.isSuccess());
            assertNotNull(psswd);

        }
    }

    private void assertPassword(String passwd, ValuePolicyType pp) throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, SecurityViolationException {
        assertPassword(passwd, pp, null);
    }

    private <O extends ObjectType> void assertPassword(String passwd, ValuePolicyType pp, PrismObject<UserType> object) throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, SecurityViolationException {
        Task task = createTask("assertPassword");
        OperationResult result = task.getResult();
        boolean isValid = valuePolicyProcessor.validateValue(passwd, pp, createUserOriginResolver(object), "assertPassword", task, result);
        result.computeStatus();
        if (!result.isSuccess()) {
            AssertJUnit.fail(result.debugDump());
        }
        AssertJUnit.assertTrue("Password not valid (but result is success)", isValid);
    }

    @Test
    public void passwordValidationTestComplex() throws Exception {
        final String TEST_NAME = "passwordValidationTestComplex";
        TestUtil.displayTestTitle(TEST_NAME);

        ValuePolicyType pp = parsePasswordPolicy("password-policy-complex.xml");

        // WHEN, THEN
        AssertJUnit.assertTrue(pwdValidHelper("582a**A", pp));
        AssertJUnit.assertFalse(pwdValidHelper("58", pp));
        AssertJUnit.assertFalse(pwdValidHelper("333a**aGaa", pp));
        AssertJUnit.assertFalse(pwdValidHelper("AAA4444", pp));
    }

    @Test
    public void passwordValidationTestTri() throws Exception {
        final String TEST_NAME = "passwordValidationTestTri";
        TestUtil.displayTestTitle(TEST_NAME);

        ValuePolicyType pp = parsePasswordPolicy("password-policy-tri.xml");

        // WHEN, THEN
        AssertJUnit.assertTrue(pwdValidHelper("Password1", pp));
        AssertJUnit.assertFalse(pwdValidHelper("password1", pp)); // no capital letter
        AssertJUnit.assertFalse(pwdValidHelper("1PASSWORD", pp)); // no lowecase letter
        AssertJUnit.assertFalse(pwdValidHelper("Password", pp)); // no numeral
        AssertJUnit.assertFalse(pwdValidHelper("Pa1", pp)); // too short
        AssertJUnit.assertFalse(pwdValidHelper("PPPPPPPPPPPPPPPPPPPPPPPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa11111111111111111111111111111111111111111111111111111111111111111111", pp)); // too long
    }

    /**
     * MID-1657
     */
    @Test
    public void testUsername() throws Exception {
        final String TEST_NAME = "testUsername";
        TestUtil.displayTestTitle(TEST_NAME);

        PrismObject<UserType> user = createUserAb();
        ValuePolicyType pp = parsePasswordPolicy("password-policy-username.xml");

        // WHEN
        TestUtil.displayWhen(TEST_NAME);

        for (int i = 0; i < USERNAME_ATTEMPTS; i++) {
            Task task = createTask(TEST_NAME+":"+i);
            OperationResult result = task.getResult();

            String psswd = valuePolicyProcessor.generate(SchemaConstants.PATH_PASSWORD_VALUE, pp, 10, true, createUserOriginResolver(user), TEST_NAME, task, result);
            display("Generated password ("+i+")", psswd);

            result.computeStatus();
            TestUtil.assertSuccess(result);
            assertNotNull(psswd);
            assertPassword(psswd, pp, user);

            assertFalse("Generated password that matches the username: "+psswd, psswd.equals(USER_AB_USERNAME));
        }

        // THEN
        TestUtil.displayThen(TEST_NAME);
    }

    /**
     * MID-1657
     */
    @Test
    public void testUserProps() throws Exception {
        final String TEST_NAME = "testUserProps";
        TestUtil.displayTestTitle(TEST_NAME);

        PrismObject<UserType> user = createUserAb();
        display("User", user);
        ValuePolicyType pp = parsePasswordPolicy("password-policy-props.xml");

        // WHEN
        TestUtil.displayWhen(TEST_NAME);

        for (int i = 0; i < USER_PROPS_ATTEMPTS; i++) {
            Task task = createTask(TEST_NAME+":"+i);
            OperationResult result = task.getResult();

            String psswd = valuePolicyProcessor.generate(SchemaConstants.PATH_PASSWORD_VALUE, pp, 10, true, createUserOriginResolver(user), TEST_NAME, task, result);
            display("Generated password ("+i+")", psswd);

            result.computeStatus();
            TestUtil.assertSuccess(result);
            assertNotNull(psswd);
            assertPassword(psswd, pp, user);

            assertNotContains(psswd, USER_AB_USERNAME);
            assertNotContains(psswd, USER_AB_GIVEN_NAME);
            assertNotContains(psswd, USER_AB_ADDITIONAL_NAME);
        }

        // THEN
        TestUtil.displayThen(TEST_NAME);
    }

    private PrismObject<UserType> createUserAb() throws SchemaException {
        PrismObject<UserType> user = createUser(USER_AB_USERNAME, USER_AB_GIVEN_NAME, USER_AB_FAMILY_NAME, true);
        user.asObjectable().setAdditionalName(createPolyStringType(USER_AB_ADDITIONAL_NAME));
        return user;
    }

    private void assertNotContains(String psswd, String val) {
        assertFalse("Generated password "+psswd+" contains value "+val, StringUtils.containsIgnoreCase(psswd, val));
    }

    private ValuePolicyType parsePasswordPolicy(String filename) throws SchemaException, IOException {
        File file = new File(TEST_DIR, filename);
        return (ValuePolicyType) PrismTestUtil.parseObject(file).asObjectable();
    }

    private boolean pwdValidHelper(String password, ValuePolicyType pp) throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, SecurityViolationException {
        Task task = createTask("pwdValidHelper");
        OperationResult result = task.getResult();
        valuePolicyProcessor.validateValue(password, pp, null, "pwdValidHelper", task, result);
        result.computeStatus();
        String msg = "-> Policy "+pp.getName()+", password '"+password+"': "+result.getStatus();
        System.out.println(msg);
        LOGGER.info(msg);
        LOGGER.trace(result.debugDump());
        return (result.isSuccess());
    }
}


text:
package org.apache.arrow.vector.util;

/**
 * An exception that is used to signal that allocation request in bytes is greater than the maximum allowed by
 * {@link org.apache.arrow.memory.BufferAllocator#buffer(int) allocator}.
 *
 *
Operators should handle this exception to split the batch and later resume the execution on the next iteration.

 *
 */
public class OversizedAllocationException extends RuntimeException {
  public OversizedAllocationException() {
    super();
  }

  public OversizedAllocationException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
    super(message, cause, enableSuppression, writableStackTrace);
  }

  public OversizedAllocationException(String message, Throwable cause) {
    super(message, cause);
  }

  public OversizedAllocationException(String message) {
    super(message);
  }

  public OversizedAllocationException(Throwable cause) {
    super(cause);
  }
}


text:
package oldcodes.io_fundamentals;

import java.io.Console;

/**
 * Echo.java -> Job:
 * <p>
 * @since 02/06/2014
 * @version 1.0
 * @author Julio Cesar Nunes de Souza (julio.souza@mobilitasistemas.com.br)
 */
public class Echo {

    public static void main( String[] args ) {
        String str = " ";
        String[] splited = str.split( " " );
        System.out.println( "-> " + splited.length );

        Console console = System.console();
        /*
         * Se a JVM é invocada indiretamente pela IDE, ou se a JVM é invocada a
         * partir de um processo de background, então o chamada de método
         * System.console () irá falhar e retornar nulo.
         */
        if ( console == null ) {
            System.out.println(
                    "Executando app de uma ide... objeto console nao recuperado" );
        }
        else {
            console.printf( console.readLine() );
        }
    }

}


text:
package com.app.qunadai.content.model;

import com.app.qunadai.bean.Message;
import com.app.qunadai.bean.ResetBean;
import com.app.qunadai.content.base.BaseReturnListener;
import com.app.qunadai.content.contract.ForgetContract;
import com.app.qunadai.http.ApiException;
import com.app.qunadai.http.RxHttp;
import com.app.qunadai.http.RxSubscriber;
import com.app.qunadai.utils.RxHolder;

import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by wayne on 2017/5/11.
 */

public class ForgetModelImpl implements ForgetContract.Model {

    private OnReturnDataListener onReturnDataListener;

    public ForgetModelImpl(OnReturnDataListener onReturnDataListener) {
        this.onReturnDataListener = onReturnDataListener;
    }

    public interface OnReturnDataListener extends BaseReturnListener {
        void getForgetSms(Message msg);

        void getForgetSmsFail(String error);

        void resetDone(ResetBean str);

        void resetFail(String error);

        void requestStart();

        void requestEnd();
    }

    @Override
    public void getServerData() {

    }

    @Override
    public void requestForgetSms(String phone) {
        Observable<Message> request = RxHttp.getInstance().getForgetSms(phone);
        Subscription sub = request.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscriber<Message>() {
                    @Override
                    public void onStart() {
                        onReturnDataListener.requestStart();
                        super.onStart();
                    }

                    @Override
                    protected void onError(ApiException ex) {
                        onReturnDataListener.getForgetSmsFail(ex.getDisplayMessage());
                    }

                    @Override
                    protected void onOk(Message bean) {
                        onReturnDataListener.getForgetSms(bean);
                    }

                    @Override
                    protected void requestEnd() {
                        onReturnDataListener.requestEnd();
                    }
                });
        RxHolder.addSubscription(sub);
    }

    @Override
    public void reset(String phone, String sms, String pwd) {
        Observable<ResetBean> request = RxHttp.getInstance().reset(phone, sms, pwd);
        Subscription sub = request.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscriber<ResetBean>() {
                    @Override
                    public void onStart() {
                        onReturnDataListener.requestStart();
                        super.onStart();
                    }

                    @Override
                    protected void onError(ApiException ex) {
                        onReturnDataListener.resetFail(ex.getMessage());
                    }

                    @Override
                    protected void onOk(ResetBean bean) {
                        onReturnDataListener.resetDone(bean);
                    }

                    @Override
                    protected void requestEnd() {
                        onReturnDataListener.requestEnd();
                    }
                });
        RxHolder.addSubscription(sub);
    }
}


text:
package com.bustiblelemons.async;

import android.os.AsyncTask;
import android.os.Build;
import android.util.Pair;

import java.util.concurrent.Executor;

public abstract class AbsSimpleAsync<P, R extends Object> extends AsyncTask<P, Pair<P, R>, R> {

    private Executor executor;

    public AbsSimpleAsync() {
    }

    protected abstract R call(P... params) throws Exception;

    protected abstract boolean onException(Exception e);

    protected boolean onSuccess(R result) {
        return false;
    }

    @Override
    protected R doInBackground(P... arg0) {
        if (arg0 == null) {
            throw new NullPointerException("params cannot be null");
        }
        try {
            return call(arg0);
        } catch (Exception e) {
            onException(e);
        }
        return null;
    }

    public void publishProgress(P param, R result) {
        publishProgress(Pair.create(param, result));
    }

    protected abstract void onProgressUpdate(P param, R result);

    @Override
    protected void onProgressUpdate(Pair<P, R>... values) {
        super.onProgressUpdate(values);
        for (Pair<P, R> v : values) {
            if (v != null) {
                onProgressUpdate(v.first, v.second);
            }
        }
    }

    @Override
    protected void onPostExecute(R result) {
        super.onPostExecute(result);
    }

    public AsyncTask<P, Pair<P, R>, R> executeCrossPlatform(P... params) {
        return executeCrossPlatform(getExecutor(), params);
    }

    public AsyncTask<P, Pair<P, R>, R> executeCrossPlatform(Executor executor, P... params) {
        return Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB ?
                this.executeOnExecutor(executor, params) : this.execute(params);
    }

    private Executor getExecutor() {
        return executor == null ?
                executor = ExecutorsProvider.getExecutor(getClass(), getExecutorType()) : executor;
    }

    protected ExecutorsProvider.Type getExecutorType() {
        return ExecutorsProvider.Type.SINGLE;
    }
}


text:
NSString * _Nonnull const TSDKCustomDataTypeDateString = @"Date";
NSString * _Nonnull const TSDKCustomDataTypeMenuString = @"Menu";
NSString * _Nonnull const TSDKCustomDataTypeBoolString = @"Check Box";
NSString * _Nonnull const TSDKCustomDataTypeTextString = @"Text";

@implementation TSDKCustomField
@dynamic name, teamId, options, helpText, kind, linkTeam, linkCustomData;

+ (NSString *)SDKType {
    return @"custom_field";
}

- (TSDKCustomDataFieldType)fieldType {
    return [TSDKCustomField fieldTypeForString:self.kind];
}

- (void)setFieldType:(TSDKCustomDataFieldType)fieldType {
    [self setString:[TSDKCustomField fieldTypeStringForFieldType:fieldType] forKey:@"kind"];
}

- (BOOL)teamCanEdit {
    return YES; // Team level fields always return true. This field is used for League Custom Fields.
}

- (BOOL)teamCanRead {
    return YES; // Team level fields always return true. This field is used for League Custom Fields.
}

- (BOOL)required {
    return NO;  // Team level fields are never required. This field is used for League Custom Fields.
}

+ (TSDKCustomDataFieldType)fieldTypeForString:(NSString *)kind {
    if ([[kind uppercaseString] isEqualToString:[TSDKCustomDataTypeDateString uppercaseString]]) {
        return TSDKCustomDataFieldTypeDate;
    } else if ([[kind uppercaseString] isEqualToString:[TSDKCustomDataTypeMenuString uppercaseString]]) {
        return TSDKCustomDataFieldTypeMenu;
    } else if ([[kind uppercaseString] isEqualToString:[TSDKCustomDataTypeBoolString uppercaseString]]) {
        return TSDKCustomDataFieldTypeBool;
    } else if ([[kind uppercaseString] isEqualToString:[TSDKCustomDataTypeTextString uppercaseString]]) {
        return TSDKCustomDataFieldTypeText;
    } else {
        return TSDKCustomDataFieldTypeUnknown;
    }
}

+ (NSString *)fieldTypeStringForFieldType:(TSDKCustomDataFieldType)fieldType {
    NSArray *fieldTypeStringArray = @[TSDKCustomDataTypeDateString,
                                       TSDKCustomDataTypeMenuString,
                                       TSDKCustomDataTypeBoolString,
                                       TSDKCustomDataTypeTextString];
    if (fieldType != TSDKCustomDataFieldTypeUnknown) {
        return fieldTypeStringArray[fieldType];
    } else {
        return TSDKCustomDataTypeTextString;
    }
}

@end


text:
/************ UI CONTROL ************/
// Update user form according to usertype
function profile_user_form_usertype() {
  var profile_user_form = $('#profile_user_form');
  var usertype = profile_user_form.find('#usertype input[name=usertype]:checked');
  var current_usertype;

  if (!usertype.length) {
    return;
  }

  current_usertype = usertype.val();

  profile_user_form.find('input[data-usertype]').each(function() {
    var input = $(this);
    var tr = input.closest('tr');

    if (input.data('usertype') == current_usertype) {
      tr.show();
      //tr.fadeIn();
    } else {
      tr.hide();
      //tr.fadeOut();
    }
  });
}

// Add links to Profile controls
function profile_control_links(elem) {
  var links;

  if (typeof(elem) === 'undefined') {
    links = $('a.profile_control');
  } else {
    links = elem.find('a.profile_control');
  }
  links.each(function() {
    var btn = $(this);
    btn.click(function() {
      profile_control(btn);
      return false;
    });
  });

  $('#profile_form').on('keypress', {btn_enter: $('#profile_update')}, enter_click).find(':input:enabled:visible:first').focus();
  $('#profile_user_form input[name=usertype]').change(profile_user_form_usertype);
  $('#id_phone_0, #id_phone2_0, #id_alerting_phone_0').select2();
  $('#id_language, #id_timezone, #id_country, #id_country2, #id_currency, #id_groups').select2({width: '100%'});
  profile_user_form_usertype();
  profile_billing_address();
}

function profile_billing_address() {
  if(!$('#id_different_billing').is(':checked')) {
    $('#billing_address_details').hide();
    //$('#billing_address_details').fadeOut();
  } else {
    $('#billing_address_details').show();
    //$('#billing_address_details').fadeIn();
  }
}

// Profile control commands
function profile_control(btn) {
  if (!btn.length || btn.hasClass('disabled')) {
    return false;
  }

  var action = btn.attr('id').split('_');
  var mod;
  btn.addClass('disabled');
  setTimeout(function() { btn.removeClass('disabled'); }, 2000);

  switch(action[1]) {
    case 'update':
    case 'update2':
    case 'update3':
    case 'update4':
      var page = $('#profile_page');
      var form = page.find('#profile_form');
      form.find(':input').removeProp('disabled');
      return ajax('POST', page.data('source'), ATIMEOUT, function(data, textStatus, jqXHR) {
        if (jqXHR.status == 278) {
          ajax_move(null, jqXHR.getResponseHeader('Location'));
        } else {
          page.html(data);
          profile_control_links(page);
          scroll_to_form_error(form);
        }
      }, form.serialize(), null, btn);

    case 'display-apikeys':
      var apikeys = $('#profile_apikey_list');
      return ajax('GET', apikeys.data('source'), ATIMEOUT, function(data, textStatus, jqXHR) {
          apikeys.html(data);
          init_copy_text_to_clipboard();
        });

    case 'password':
      mod = $('#profile_password_modal');
      return vm_modal(mod, btn, function() {
        var form = mod.find('form');
        return ajax('POST', form.data('source'), ATIMEOUT, function(data, textStatus, jqXHR) {
          if (jqXHR.status == 278) {
            mod.modal('hide');
            ajax_move(null, jqXHR.getResponseHeader('Location'));
          } else {
            form.html(data);
          }
        }, form.serialize());
      });

    case 'addsshkey':
      mod = $('#profile_addsshkey_modal');
      return vm_modal(mod, btn, function() {
        var form = mod.find('form');
        return ajax('POST', form.data('source'), ATIMEOUT, function(data, textStatus, jqXHR) {
          if (jqXHR.status == 278) {
            mod.modal('hide');
            ajax_move(null, jqXHR.getResponseHeader('Location'));
          } else {
            form.html(data);
          }
        }, form.serialize());
      });

    case 'deletesshkey':
      mod = $('#profile_deletesshkey_modal');
      return vm_modal(mod, btn, function() {
        var form = mod.find('form');
        var post = form.serializeArray();
        post.push({'name': 'name', 'value': btn.data('name')});
        return ajax('POST', form.data('source'), ATIMEOUT, function(data, textStatus, jqXHR) {
          if (jqXHR.status == 278) {
            mod.modal('hide');
            ajax_move(null, jqXHR.getResponseHeader('Location'));
          }
        }, $.param(post));
      });

    case 'verifyemail':
    case 'verifyphone':
      mod = $('#profile_activation_modal');
      return vm_modal(mod, btn, function() {
        var form = mod.find('form');
        return ajax('POST', form.data('source'), ATIMEOUT, function(data, textStatus, jqXHR) {
          if (jqXHR.status == 278) {
            mod.modal('hide');
            ajax_move(null, jqXHR.getResponseHeader('Location'));
          } else {
            form.html(data);
          }
        }, form.serialize());
      });

    default:
      return false;
  }
}


text:
require 'minitest/autorun'
require 'botany'


text:
A dark, flattened theme meant to be used with [Shadow UI](https://atom.io/packages/shadow).

![Screenshot](https://f.cloud.github.com/assets/69169/2289498/4c3cb0ec-a009-11e3-8dbd-077ee11741e5.gif)


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * EDACCManageComputationMethodDialog.java
 *
 * Created on 15.10.2010, 22:53:52
 */

package edacc;

import edacc.model.ComputationMethod;
import edacc.model.ComputationMethodAlreadyExistsException;
import edacc.model.ComputationMethodDoesNotExistException;
import edacc.model.ComputationMethodSameMD5AlreadyExists;
import edacc.model.ComputationMethodSameNameAlreadyExists;
import edacc.model.NoComputationMethodBinarySpecifiedException;
import edacc.model.NoConnectionToDBException;
import edacc.properties.ComputationMethodTableSelectionListener;
import edacc.properties.ComputationMethodTableModel;
import edacc.properties.ManageComputationMethodController;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 *
 * @author rretz
 */
public class EDACCManageComputationMethodDialog extends javax.swing.JDialog {
    private ManageComputationMethodController controller;
    private ComputationMethodTableModel tableModel;
    private File selectedFile;
    private EDACCManagePropertyDialog main;

    /** Creates new form EDACCManageComputationMethodDialog */
    public EDACCManageComputationMethodDialog(java.awt.Frame parent, boolean modal, EDACCManagePropertyDialog main) {
        super(parent, modal);
        initComponents();

        this.main = main;
        // initialize the tableComputationMethod
        tableModel = new ComputationMethodTableModel();
        controller = new ManageComputationMethodController(this, panelMain, tableModel);
        tableComputationMethod.setModel(tableModel);
        tableComputationMethod.getSelectionModel().addListSelectionListener(new ComputationMethodTableSelectionListener(tableComputationMethod, controller));

    }

    private EDACCManageComputationMethodDialog(JFrame jFrame, boolean b) {
        super(jFrame, b);
        initComponents();
    }

    EDACCManageComputationMethodDialog(JFrame mainFrame, boolean b, EDACCCreateEditInstanceClassDialog aThis) {
        throw new UnsupportedOperationException("Not yet implemented");
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jFileChooser1 = new javax.swing.JFileChooser();
        panelMain = new javax.swing.JPanel();
        jSplitPane1 = new javax.swing.JSplitPane();
        panelTable = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tableComputationMethod = new javax.swing.JTable();
        buttonNew = new javax.swing.JButton();
        buttonRemove = new javax.swing.JButton();
        PanelEdit = new javax.swing.JPanel();
        panelDetails = new javax.swing.JPanel();
        labelName = new javax.swing.JLabel();
        textFieldName = new javax.swing.JTextField();
        labelDescription = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        textAreaDescription = new javax.swing.JTextArea();
        labelBinary = new javax.swing.JLabel();
        buttonChooseBinary = new javax.swing.JButton();
        labelBinaryName = new javax.swing.JLabel();
        buttonSave = new javax.swing.JButton();
        buttonDone = new javax.swing.JButton();

        jFileChooser1.setName("jFileChooser1"); // NOI18N

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(edacc.EDACCApp.class).getContext().getResourceMap(EDACCManageComputationMethodDialog.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setMinimumSize(new java.awt.Dimension(600, 440));
        setName("Form"); // NOI18N

        panelMain.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("panelMain.border.title"))); // NOI18N
        panelMain.setName("panelMain"); // NOI18N

        jSplitPane1.setDividerLocation(185);
        jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
        jSplitPane1.setResizeWeight(0.5);
        jSplitPane1.setName("jSplitPane1"); // NOI18N

        panelTable.setName("panelTable"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        tableComputationMethod.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tableComputationMethod.setName("tableComputationMethod"); // NOI18N
        jScrollPane1.setViewportView(tableComputationMethod);

        buttonNew.setText(resourceMap.getString("buttonNew.text")); // NOI18N
        buttonNew.setName("buttonNew"); // NOI18N
        buttonNew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonNewActionPerformed(evt);
            }
        });

        buttonRemove.setText(resourceMap.getString("buttonRemove.text")); // NOI18N
        buttonRemove.setName("buttonRemove"); // NOI18N
        buttonRemove.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonRemoveActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout panelTableLayout = new javax.swing.GroupLayout(panelTable);
        panelTable.setLayout(panelTableLayout);
        panelTableLayout.setHorizontalGroup(
            panelTableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelTableLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelTableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 619, Short.MAX_VALUE)
                    .addGroup(panelTableLayout.createSequentialGroup()
                        .addComponent(buttonNew)
                        .addGap(18, 18, 18)
                        .addComponent(buttonRemove)))
                .addContainerGap())
        );

        panelTableLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {buttonNew, buttonRemove});

        panelTableLayout.setVerticalGroup(
            panelTableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelTableLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 123, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(panelTableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buttonNew)
                    .addComponent(buttonRemove))
                .addGap(16, 16, 16))
        );

        jSplitPane1.setLeftComponent(panelTable);

        PanelEdit.setName("PanelEdit"); // NOI18N

        panelDetails.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        panelDetails.setName("panelDetails"); // NOI18N

        labelName.setText(resourceMap.getString("labelName.text")); // NOI18N
        labelName.setName("labelName"); // NOI18N

        textFieldName.setText(resourceMap.getString("textFieldName.text")); // NOI18N
        textFieldName.setDragEnabled(true);
        textFieldName.setEnabled(false);
        textFieldName.setName("textFieldName"); // NOI18N

        labelDescription.setText(resourceMap.getString("labelDescription.text")); // NOI18N
        labelDescription.setName("labelDescription"); // NOI18N

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        textAreaDescription.setColumns(20);
        textAreaDescription.setRows(5);
        textAreaDescription.setWrapStyleWord(true);
        textAreaDescription.setEnabled(false);
        textAreaDescription.setName("textAreaDescription"); // NOI18N
        jScrollPane2.setViewportView(textAreaDescription);

        labelBinary.setText(resourceMap.getString("labelBinary.text")); // NOI18N
        labelBinary.setName("labelBinary"); // NOI18N

        buttonChooseBinary.setText(resourceMap.getString("buttonChooseBinary.text")); // NOI18N
        buttonChooseBinary.setEnabled(false);
        buttonChooseBinary.setName("buttonChooseBinary"); // NOI18N
        buttonChooseBinary.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonChooseBinaryActionPerformed(evt);
            }
        });

        labelBinaryName.setText(resourceMap.getString("labelBinaryName.text")); // NOI18N
        labelBinaryName.setName("labelBinaryName"); // NOI18N

        javax.swing.GroupLayout panelDetailsLayout = new javax.swing.GroupLayout(panelDetails);
        panelDetails.setLayout(panelDetailsLayout);
        panelDetailsLayout.setHorizontalGroup(
            panelDetailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelDetailsLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelDetailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(labelName)
                    .addComponent(labelDescription)
                    .addComponent(labelBinary))
                .addGap(33, 33, 33)
                .addGroup(panelDetailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(panelDetailsLayout.createSequentialGroup()
                        .addComponent(buttonChooseBinary)
                        .addGap(18, 18, 18)
                        .addComponent(labelBinaryName))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 505, Short.MAX_VALUE)
                    .addComponent(textFieldName, javax.swing.GroupLayout.DEFAULT_SIZE, 505, Short.MAX_VALUE))
                .addContainerGap())
        );
        panelDetailsLayout.setVerticalGroup(
            panelDetailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelDetailsLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelDetailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelName)
                    .addComponent(textFieldName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(panelDetailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(panelDetailsLayout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(labelDescription))
                    .addGroup(panelDetailsLayout.createSequentialGroup()
                        .addGap(8, 8, 8)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 68, Short.MAX_VALUE)))
                .addGap(18, 18, 18)
                .addGroup(panelDetailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buttonChooseBinary)
                    .addComponent(labelBinary)
                    .addComponent(labelBinaryName))
                .addContainerGap())
        );

        buttonSave.setText(resourceMap.getString("buttonSave.text")); // NOI18N
        buttonSave.setEnabled(false);
        buttonSave.setName("buttonSave"); // NOI18N
        buttonSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonSaveActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout PanelEditLayout = new javax.swing.GroupLayout(PanelEdit);
        PanelEdit.setLayout(PanelEditLayout);
        PanelEditLayout.setHorizontalGroup(
            PanelEditLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(PanelEditLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(PanelEditLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(panelDetails, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(buttonSave))
                .addContainerGap())
        );
        PanelEditLayout.setVerticalGroup(
            PanelEditLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, PanelEditLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(panelDetails, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(buttonSave)
                .addContainerGap())
        );

        jSplitPane1.setRightComponent(PanelEdit);

        javax.swing.GroupLayout panelMainLayout = new javax.swing.GroupLayout(panelMain);
        panelMain.setLayout(panelMainLayout);
        panelMainLayout.setHorizontalGroup(
            panelMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelMainLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 641, Short.MAX_VALUE)
                .addContainerGap())
        );
        panelMainLayout.setVerticalGroup(
            panelMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelMainLayout.createSequentialGroup()
                .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 405, Short.MAX_VALUE)
                .addContainerGap())
        );

        buttonDone.setText(resourceMap.getString("buttonDone.text")); // NOI18N
        buttonDone.setName("buttonDone"); // NOI18N
        buttonDone.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonDoneActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(panelMain, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(buttonDone, javax.swing.GroupLayout.Alignment.TRAILING))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(panelMain, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(buttonDone)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void buttonNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonNewActionPerformed
        controller.newComputationMethod();
    }//GEN-LAST:event_buttonNewActionPerformed

    private void buttonChooseBinaryActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonChooseBinaryActionPerformed
        jFileChooser1.setFileSelectionMode(JFileChooser.FILES_ONLY);
        int returnVal = jFileChooser1.showOpenDialog(panelMain);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
             selectedFile = jFileChooser1.getSelectedFile();
             labelBinaryName.setText(selectedFile.getName());
        }
    }//GEN-LAST:event_buttonChooseBinaryActionPerformed

    private void buttonDoneActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonDoneActionPerformed
        this.setVisible(false);
        main.loadComputationMethods();
    }//GEN-LAST:event_buttonDoneActionPerformed

    private void buttonRemoveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonRemoveActionPerformed
        if(tableComputationMethod.getSelectedRow() == -1){
            JOptionPane.showMessageDialog(this,
                "Nothing is selected. Select a computation method in the table.",
                "Error",
                JOptionPane.ERROR_MESSAGE);
        }else {
            try {
                controller.removeComputationMethod(tableComputationMethod.convertRowIndexToModel(tableComputationMethod.getSelectedRow()));
            } catch (NoConnectionToDBException ex) {
                Logger.getLogger(EDACCManageComputationMethodDialog.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SQLException ex) {
                Logger.getLogger(EDACCManageComputationMethodDialog.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ComputationMethodAlreadyExistsException ex) {
                Logger.getLogger(EDACCManageComputationMethodDialog.class.getName()).log(Level.SEVERE, null, ex);
            } catch (NoComputationMethodBinarySpecifiedException ex) {
                Logger.getLogger(EDACCManageComputationMethodDialog.class.getName()).log(Level.SEVERE, null, ex);
            } catch (FileNotFoundException ex) {
                Logger.getLogger(EDACCManageComputationMethodDialog.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ComputationMethodSameNameAlreadyExists ex) {
                Logger.getLogger(EDACCManageComputationMethodDialog.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ComputationMethodSameMD5AlreadyExists ex) {
                Logger.getLogger(EDACCManageComputationMethodDialog.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    }//GEN-LAST:event_buttonRemoveActionPerformed

    private void buttonSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSaveActionPerformed
        if(textFieldName.getText().equals("")){
             JOptionPane.showMessageDialog(this,
                "You must specify the name of the computation method.",
                "Error",
                JOptionPane.ERROR_MESSAGE);
        }else if(labelBinaryName.getText().equals("")){
            JOptionPane.showMessageDialog(this,
                "You have to select a binary for the computation method.",
                "Error",
                JOptionPane.ERROR_MESSAGE);
        }else {
            try {
                controller.saveComputationMethod(textFieldName.getText(), textAreaDescription.getText(), selectedFile);
            } catch (NoConnectionToDBException ex) {
                Logger.getLogger(EDACCManageComputationMethodDialog.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SQLException ex) {
                Logger.getLogger(EDACCManageComputationMethodDialog.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ComputationMethodAlreadyExistsException ex) {
                Logger.getLogger(EDACCManageComputationMethodDialog.class.getName()).log(Level.SEVERE, null, ex);
            } catch (NoComputationMethodBinarySpecifiedException ex) {
                Logger.getLogger(EDACCManageComputationMethodDialog.class.getName()).log(Level.SEVERE, null, ex);
            } catch (FileNotFoundException ex) {
                Logger.getLogger(EDACCManageComputationMethodDialog.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(EDACCManageComputationMethodDialog.class.getName()).log(Level.SEVERE, null, ex);
            } catch (NoSuchAlgorithmException ex) {
                Logger.getLogger(EDACCManageComputationMethodDialog.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ComputationMethodSameNameAlreadyExists ex) {
                Logger.getLogger(EDACCManageComputationMethodDialog.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ComputationMethodSameMD5AlreadyExists ex) {
                Logger.getLogger(EDACCManageComputationMethodDialog.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    }//GEN-LAST:event_buttonSaveActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                EDACCManageComputationMethodDialog dialog = new EDACCManageComputationMethodDialog(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel PanelEdit;
    private javax.swing.JButton buttonChooseBinary;
    private javax.swing.JButton buttonDone;
    private javax.swing.JButton buttonNew;
    private javax.swing.JButton buttonRemove;
    private javax.swing.JButton buttonSave;
    private javax.swing.JFileChooser jFileChooser1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JLabel labelBinary;
    private javax.swing.JLabel labelBinaryName;
    private javax.swing.JLabel labelDescription;
    private javax.swing.JLabel labelName;
    private javax.swing.JPanel panelDetails;
    private javax.swing.JPanel panelMain;
    private javax.swing.JPanel panelTable;
    private javax.swing.JTable tableComputationMethod;
    private javax.swing.JTextArea textAreaDescription;
    private javax.swing.JTextField textFieldName;
    // End of variables declaration//GEN-END:variables

      public void initialize(){
        try {
            controller.loadComputationMethods();
            clearInputFields();
        } catch (NoConnectionToDBException ex) {
            Logger.getLogger(EDACCManageComputationMethodDialog.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(EDACCManageComputationMethodDialog.class.getName()).log(Level.SEVERE, null, ex);
        }
      }

    public void clearInputFields() {
        textFieldName.setText("");
        textAreaDescription.setText("");
        selectedFile = null;
        labelBinaryName.setText("");
    }

    public void enableInputFields(boolean enable) {
        textFieldName.setEnabled(enable);
        textAreaDescription.setEnabled(enable);
        buttonChooseBinary.setEnabled(enable);
        buttonSave.setEnabled(enable);
    }

    public void showComputationMethod(ComputationMethod computationMethod) {
        textFieldName.setText(computationMethod.getName());
        textAreaDescription.setText(computationMethod.getDescription());
        labelBinaryName.setText(computationMethod.getBinaryName());
    }

    public void enableEditInputFields(boolean b) {
        textFieldName.setEnabled(b);
        textAreaDescription.setEnabled(b);
        buttonSave.setEnabled(b);
    }

}


text:
class CreatePlayers < ActiveRecord::Migration[5.0]
  def change
    create_table :players do |t|
      t.string :name
      t.integer :remote_id
      t.string :team_abbreviation
      t.string :position

      t.timestamps
    end
  end
end


text:
if (typeof define !== 'function') {
  var define = require('amdefine')(module);
}
define(function (require, exports, module) {
  'use strict';

  var fs = require('fs');
  var Promise = require('../promise').Promise;

  exports.loadAsync = function loadAsync(url) {
    var deferred = new Promise();
    fs.readFile(url, function(err, data) {
      if (err) {
        var ex = new IOError(err.message);
        deferred.reject(ex);
      } else {
        deferred.fulfill(data.toString());
      }
    });
    return deferred;
  };

  exports.loadSync = function loadSync(url) {
    try {
      var data = fs.readFileSync(url);
    } catch(e) {
      throw new IOError(e.message);
    }
    return data.toString();
  };

  function IOError(message) {
    this.name = 'IOError';
    this.message = message;
  }
  IOError.prototype = Object.create(Error.prototype);
  IOError.prototype.constructor = IOError;

  exports.Error = IOError;

});


text:
BROKER_URL = 'amqp://jssuser:freebeer2342@localhost:5672/jssvhost'
CELERY_RESULT_BACKEND = 'rpc://'

CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_ACCEPT_CONTENT=['json']
CELERY_TIMEZONE = 'Europe/Berlin'
CELERY_RESULT_BACKEND = 'rpc://'
CELERY_ENABLE_UTC = True


text:
package main

import (
	"errors"
	"os"

	"github.com/meeko/meekod/supervisor/data"

	"github.com/tchap/gocli"
	"github.com/wsxiaoys/terminal/color"
)

func init() {
	app.MustRegisterSubcommand(&gocli.Command{
		UsageLine: "upgrade ALIAS",
		Short:     "upgrade an installed agent",
		Long: `
  Upgrading an agent means that its sources are updated and the executable
  is rebuilt, replacing the old executable if successful. Then the agent
  process is restarted if running.
        `,
		Action: runUpgrade,
	})
}

func runUpgrade(cmd *gocli.Command, args []string) {
	if len(args) != 1 {
		cmd.Usage()
		os.Exit(2)
	}

	if err := _runUpgrade(args[0]); err != nil {
		color.Fprintf(os.Stderr, "\n@{r}Error: %s@{|}\n", err)
		os.Exit(1)
	}

	color.Println("\n@{g}Success@{|}")
}

func _runUpgrade(alias string) error {
	// Read the config file.
	cfg, err := LoadConfig(flagConfig)
	if err != nil {
		return err
	}

	// Send the clone request to the server.
	var reply data.UpgradeReply
	err = SendRequest(cfg.Address, cfg.AccessToken, MethodUpgrade, &data.UpgradeArgs{
		Token: []byte(cfg.ManagementToken),
		Alias: alias,
	}, &reply)
	if err != nil {
		return err
	}
	if reply.Error != "" {
		return errors.New(reply.Error)
	}

	return nil
}


text:
import Ember from 'ember';

export function initialize(/*application */) {
  Ember.LinkComponent.reopen({
    attributeBindings: ['tooltip', 'data-placement'],

    // Set activeParent=true on a {{link-to}} to automatically propagate the active
    // class to the parent element (like <li>{{link-to}}</li>)
    activeParent: false,

    addActiveObserver: function() {
      if ( this.get('activeParent') ) {
        this.addObserver('active', this, 'activeChanged');
        this.activeChanged();
      }
    }.on('didInsertElement'),

    activeChanged() {
      if ( this.isDestroyed || this.isDestroying ) {
        return;
      }

      this.$().parent().toggleClass('active', this.get('active'));
    }
  });

}

export default {
  name: 'extend-ember-link',
  initialize: initialize
};


text:
  <title>Java Application Stub</title>
  <meta http-equiv="Content-type" content="text/html; charset=iso-8859-1" />
  <meta http-equiv="Content-Language" content="en-us" />
  <meta name="ROBOTS" content="ALL" />
  <link href="styles.css" rel="stylesheet" media="all" type="text/css" />

JarBundler - Java Application Stub

The Java Launching stub file  is located inside of your application bundle in the
subdirectory "<tt>Contents/MacOS/</tt>". The default name for this file is "<tt>JavaApplicationStub</tt>".
It is used by the Mac OS X system  read the
applications plist and then launch the Java VM with the appropriate properties such as the
classpath and main class name.

When run on OS X system, the JarBundler ANT task uses the current copy of the <tt>JavaApplicationStub</tt>
from the developer's disk.  Starting with JarBundler 1.8 the attribute <tt>stubfile</tt> can be used to
set the name of the <tt>JavaApplicationStub</tt> file copied from the system framework. If the
stub file referenced by the <tt>stubfile</tt> attribute exists, that file will be used along with
it's filename.

When the JarBundler ANT task is used under Windows or Linux, a copy of the <tt>JavaApplicationStub</tt>
must be supplied by the developer. This cannot be built from source but must be obtained from
a Mac OS X system.

Java Launching Stub as a Symbolic Link

Creating a bundle with the your current copy of Java Launching Stub
could lead to a future situation where the <tt>JavaApplicationStub</tt> file
could become incompatible with a future OS X update.

Under Mac OS X one
could replace the "<tt>JavaApplicationStub</tt>" file with a symbolic link to the user's current
copy.  This should guarentee that
the end user would always be using a current copy of the stub file.  I have used this technique on
several versions of OS X and have not have had any reported problems with its use.

Obviously, if you have used a stub file name which is different than the one shown in the
example below you will have to make changes to both the delete and the symbolic link commands.

This is not yet an option of the JarBundler task but can be accomplished with the following lines
of ANT code after building the bundle. NB: This will not work when building under
Windows and is untested under Linux.

   .
   .
   .
  </jarbundler>

  <!-- Delete the JavaApplicationStub and replace it with a symbolic link -->
  <!--   which should work on older and future versions of OS X           -->

  <delete file="${release}/${name}.app/Contents/MacOS/JavaApplicationStub"/>
  <exec executable="ln">
    <arg line="-s /System/Library/Frameworks/JavaVM.framework/Resources/MacOS/JavaApplicationStub"/>
    <arg value="${release}/${name}.app/Contents/MacOS/JavaApplicationStub"/>
  </exec>

</target>

A Known problem with Java launching stub

In early 2006 an Apple upgrade to Quicktime (7.0.4) caused
older versions of "<tt>JavaApplicationStub</tt>" to fail to start up.  These old copies came from developers
who first created the application bundle as a directory and then created new applications by
replacing the JAR files within the bundle and not replacing "<tt>JavaApplicationStub</tt>" with a more current
copy.


text:
import * as constants from "../constants";
import * as helpers from "../common/helpers";
import * as semver from "semver";
import * as path from "path";

export enum VersionInformationType {
	UpToDate = "UpToDate",
	UpdateAvailable = "UpdateAvailable",
	NotInstalled = "NotInstalled"
}

class VersionsService implements IVersionsService {
	private static UP_TO_DATE_MESSAGE = "up to date";
	private static UPDATE_AVAILABLE_MESSAGE = "Update available";
	private static NOT_INSTALLED_MESSAGE = "not installed";

	private projectData: IProjectData;

	constructor(private $fs: IFileSystem,
		private $packageInstallationManager: IPackageInstallationManager,
		private $injector: IInjector,
		private $logger: ILogger,
		private $staticConfig: Config.IStaticConfig,
		private $pluginsService: IPluginsService,
		private $terminalSpinnerService: ITerminalSpinnerService) {
		this.projectData = this.getProjectData();
	}

	public async getNativescriptCliVersion(): Promise<IVersionInformation> {
		const currentCliVersion = this.$staticConfig.version;
		const latestCliVersion = await this.$packageInstallationManager.getLatestVersion(constants.NATIVESCRIPT_KEY_NAME);

		return {
			componentName: constants.NATIVESCRIPT_KEY_NAME,
			currentVersion: currentCliVersion,
			latestVersion: latestCliVersion
		};
	}

	public async getTnsCoreModulesVersion(): Promise<IVersionInformation> {
		const latestTnsCoreModulesVersion = await this.$packageInstallationManager.getLatestVersion(constants.TNS_CORE_MODULES_NAME);
		const nativescriptCoreModulesInfo: IVersionInformation = {
			componentName: constants.TNS_CORE_MODULES_NAME,
			latestVersion: latestTnsCoreModulesVersion
		};

		if (this.projectData) {
			const nodeModulesPath = path.join(this.projectData.projectDir, constants.NODE_MODULES_FOLDER_NAME);
			const tnsCoreModulesPath = path.join(nodeModulesPath, constants.TNS_CORE_MODULES_NAME);
			if (!this.$fs.exists(nodeModulesPath) ||
				!this.$fs.exists(tnsCoreModulesPath)) {
				await this.$pluginsService.ensureAllDependenciesAreInstalled(this.projectData);
			}

			const currentTnsCoreModulesVersion = this.$fs.readJson(path.join(tnsCoreModulesPath, constants.PACKAGE_JSON_FILE_NAME)).version;
			nativescriptCoreModulesInfo.currentVersion = currentTnsCoreModulesVersion;
		}

		return nativescriptCoreModulesInfo;
	}

	public async getRuntimesVersions(): Promise<IVersionInformation[]> {
		const runtimes: string[] = [
			constants.TNS_ANDROID_RUNTIME_NAME,
			constants.TNS_IOS_RUNTIME_NAME
		];

		let projectConfig: any;

		if (this.projectData) {
			projectConfig = this.$fs.readJson(this.projectData.projectFilePath);
		}

		const runtimesVersions: IVersionInformation[] = await Promise.all(runtimes.map(async (runtime: string) => {
			const latestRuntimeVersion = await this.$packageInstallationManager.getLatestVersion(runtime);
			const runtimeInformation: IVersionInformation = {
				componentName: runtime,
				latestVersion: latestRuntimeVersion
			};

			if (projectConfig) {
				const projectRuntimeInformation = projectConfig.nativescript && projectConfig.nativescript[runtime];
				if (projectRuntimeInformation) {
					const runtimeVersionInProject = projectRuntimeInformation.version;
					runtimeInformation.currentVersion = runtimeVersionInProject;
				}
			}

			return runtimeInformation;
		}));

		return runtimesVersions;
	}

	public async getAllComponentsVersions(): Promise<IVersionInformation[]> {
		let allComponents: IVersionInformation[] = [];

		const nativescriptCliInformation: IVersionInformation = await this.getNativescriptCliVersion();
		if (nativescriptCliInformation) {
			allComponents.push(nativescriptCliInformation);
		}

		if (this.projectData) {
			const nativescriptCoreModulesInformation: IVersionInformation = await this.getTnsCoreModulesVersion();
			if (nativescriptCoreModulesInformation) {
				allComponents.push(nativescriptCoreModulesInformation);
			}

			const runtimesVersions: IVersionInformation[] = await this.getRuntimesVersions();
			allComponents = allComponents.concat(runtimesVersions);
		}

		return allComponents
			.map(componentInformation => {
				if (componentInformation.currentVersion) {
					if (this.hasUpdate(componentInformation)) {
						componentInformation.type = VersionInformationType.UpdateAvailable;
						componentInformation.message = `${VersionsService.UPDATE_AVAILABLE_MESSAGE} for component ${componentInformation.componentName}. Your current version is ${componentInformation.currentVersion} and the latest available version is ${componentInformation.latestVersion}.`;
					} else {
						componentInformation.type = VersionInformationType.UpToDate;
						componentInformation.message = `Component ${componentInformation.componentName} has ${componentInformation.currentVersion} version and is ${VersionsService.UP_TO_DATE_MESSAGE}.`;
					}
				} else {
					componentInformation.type = VersionInformationType.NotInstalled;
					componentInformation.message = `Component ${componentInformation.componentName} is ${VersionsService.NOT_INSTALLED_MESSAGE}.`;
				}

				return componentInformation;
			});
	}

	public async printVersionsInformation(): Promise<void> {
		const versionsInformation = await this.$terminalSpinnerService.execute<IVersionInformation[]>({
			text: `Getting NativeScript components versions information...`
		}, () => this.getAllComponentsVersions());

		if (!helpers.isInteractive()) {
			versionsInformation.map(componentInformation => this.$logger.info(componentInformation.message));
		}

		_.forEach(versionsInformation, componentInformation => {
			const spinner = this.$terminalSpinnerService.createSpinner();
			spinner.text = componentInformation.message;

			switch (componentInformation.type) {
				case VersionInformationType.UpToDate:
					spinner.succeed();
					break;
				case VersionInformationType.UpdateAvailable:
					spinner.warn();
					break;
				case VersionInformationType.NotInstalled:
					spinner.fail();
					break;
			}
		});
	}

	private getProjectData(): IProjectData {
		try {
			const projectData: IProjectData = this.$injector.resolve("projectData");
			projectData.initializeProjectData();
			return projectData;
		} catch (error) {
			return null;
		}
	}

	private hasUpdate(component: IVersionInformation): boolean {
		return semver.lt(component.currentVersion, component.latestVersion);
	}
}

$injector.register("versionsService", VersionsService);


text:
grep -q 'secure_path' /etc/sudoers || sed -i -e '/Defaults\s\+env_reset/a Defaults\tsecure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"' /etc/sudoers

sed -i -e 's/^%sudo.*/%sudo ALL=(ALL) NOPASSWD: ALL/' /etc/sudoers


text:
package org.apache.nifi.web.api.entity;

import io.swagger.annotations.ApiModelProperty;
import org.apache.nifi.web.api.dto.AffectedComponentDTO;
import org.apache.nifi.web.api.dto.ProcessGroupNameDTO;

import javax.xml.bind.annotation.XmlRootElement;
import java.util.Objects;

/**
 * A serialized representation of this class can be placed in the entity body of a response to the API.
 * This particular entity holds a reference to component that references a variable.
 */
@XmlRootElement(name = "affectedComponentEntity")
public class AffectedComponentEntity extends ComponentEntity implements Permissible<AffectedComponentDTO> {

    private AffectedComponentDTO component;
    private ProcessGroupNameDTO processGroup;
    private String referenceType;

    /**
     * @return variable referencing components that is being serialized
     */
    @Override
    public AffectedComponentDTO getComponent() {
        return component;
    }

    @Override
    public void setComponent(AffectedComponentDTO component) {
        this.component = component;
    }

    @ApiModelProperty("The Process Group that the component belongs to")
    public ProcessGroupNameDTO getProcessGroup() {
        return processGroup;
    }

    public void setProcessGroup(ProcessGroupNameDTO processGroup) {
        this.processGroup = processGroup;
    }

    @ApiModelProperty(value="The type of component referenced",
        allowableValues = AffectedComponentDTO.COMPONENT_TYPE_PROCESSOR + "," + AffectedComponentDTO.COMPONENT_TYPE_CONTROLLER_SERVICE + ", "
                + AffectedComponentDTO.COMPONENT_TYPE_INPUT_PORT + ", " + AffectedComponentDTO.COMPONENT_TYPE_OUTPUT_PORT + ", "
                + AffectedComponentDTO.COMPONENT_TYPE_REMOTE_INPUT_PORT + ", " + AffectedComponentDTO.COMPONENT_TYPE_REMOTE_OUTPUT_PORT)
    public String getReferenceType() {
        return referenceType;
    }

    public void setReferenceType(String referenceType) {
        this.referenceType = referenceType;
    }

    @Override
    public String toString() {
        return component == null ? "AffectedComponent[No Component]" : component.toString();
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(getId());
    }

    @Override
    public boolean equals(final Object obj) {
        if (obj == this) {
            return true;
        }
        if (!(obj instanceof AffectedComponentEntity)) {
            return false;
        }

        return Objects.equals(getId(), ((AffectedComponentEntity) obj).getId());
    }
}