text:
module Ci
  class Pipeline < ActiveRecord::Base
    extend Ci::Model
    include HasStatus
    include Importable
    include AfterCommitQueue
    include Presentable

    belongs_to :project
    belongs_to :user
    belongs_to :auto_canceled_by, class_name: 'Ci::Pipeline'

    has_many :auto_canceled_pipelines, class_name: 'Ci::Pipeline', foreign_key: 'auto_canceled_by_id'
    has_many :auto_canceled_jobs, class_name: 'CommitStatus', foreign_key: 'auto_canceled_by_id'

    has_many :statuses, class_name: 'CommitStatus', foreign_key: :commit_id
    has_many :builds, foreign_key: :commit_id
    has_many :trigger_requests, dependent: :destroy, foreign_key: :commit_id

    has_many :pending_builds, -> { pending }, foreign_key: :commit_id, class_name: 'Ci::Build'
    has_many :retryable_builds, -> { latest.failed_or_canceled }, foreign_key: :commit_id, class_name: 'Ci::Build'
    has_many :cancelable_statuses, -> { cancelable }, foreign_key: :commit_id, class_name: 'CommitStatus'
    has_many :manual_actions, -> { latest.manual_actions }, foreign_key: :commit_id, class_name: 'Ci::Build'
    has_many :artifacts, -> { latest.with_artifacts_not_expired }, foreign_key: :commit_id, class_name: 'Ci::Build'

    delegate :id, to: :project, prefix: true

    validates :sha, presence: { unless: :importing? }
    validates :ref, presence: { unless: :importing? }
    validates :status, presence: { unless: :importing? }
    validate :valid_commit_sha, unless: :importing?

    after_create :keep_around_commits, unless: :importing?

    state_machine :status, initial: :created do
      event :enqueue do
        transition created: :pending
        transition [:success, :failed, :canceled, :skipped] => :running
      end

      event :run do
        transition any - [:running] => :running
      end

      event :skip do
        transition any - [:skipped] => :skipped
      end

      event :drop do
        transition any - [:failed] => :failed
      end

      event :succeed do
        transition any - [:success] => :success
      end

      event :cancel do
        transition any - [:canceled] => :canceled
      end

      event :block do
        transition any - [:manual] => :manual
      end

      # IMPORTANT
      # Do not add any operations to this state_machine
      # Create a separate worker for each new operation

      before_transition [:created, :pending] => :running do |pipeline|
        pipeline.started_at = Time.now
      end

      before_transition any => [:success, :failed, :canceled] do |pipeline|
        pipeline.finished_at = Time.now
        pipeline.update_duration
      end

      before_transition any => [:manual] do |pipeline|
        pipeline.update_duration
      end

      before_transition canceled: any - [:canceled] do |pipeline|
        pipeline.auto_canceled_by = nil
      end

      after_transition [:created, :pending] => :running do |pipeline|
        pipeline.run_after_commit { PipelineMetricsWorker.perform_async(pipeline.id) }
      end

      after_transition any => [:success] do |pipeline|
        pipeline.run_after_commit { PipelineMetricsWorker.perform_async(pipeline.id) }
      end

      after_transition [:created, :pending, :running] => :success do |pipeline|
        pipeline.run_after_commit { PipelineSuccessWorker.perform_async(pipeline.id) }
      end

      after_transition do |pipeline, transition|
        next if transition.loopback?

        pipeline.run_after_commit do
          PipelineHooksWorker.perform_async(pipeline.id)
          ExpirePipelineCacheWorker.perform_async(pipeline.id)
        end
      end

      after_transition any => [:success, :failed] do |pipeline|
        pipeline.run_after_commit do
          PipelineNotificationWorker.perform_async(pipeline.id)
        end
      end
    end

    # ref can't be HEAD or SHA, can only be branch/tag name
    scope :latest, ->(ref = nil) do
      max_id = unscope(:select)
        .select("max(#{quoted_table_name}.id)")
        .group(:ref, :sha)

      if ref
        where(ref: ref, id: max_id.where(ref: ref))
      else
        where(id: max_id)
      end
    end

    def self.latest_status(ref = nil)
      latest(ref).status
    end

    def self.latest_successful_for(ref)
      success.latest(ref).order(id: :desc).first
    end

    def self.latest_successful_for_refs(refs)
      success.latest(refs).order(id: :desc).each_with_object({}) do |pipeline, hash|
        hash[pipeline.ref] ||= pipeline
      end
    end

    def self.truncate_sha(sha)
      sha[0...8]
    end

    def self.total_duration
      where.not(duration: nil).sum(:duration)
    end

    def stage(name)
      stage = Ci::Stage.new(self, name: name)
      stage unless stage.statuses_count.zero?
    end

    def stages_count
      statuses.select(:stage).distinct.count
    end

    def stages_name
      statuses.order(:stage_idx).distinct.
        pluck(:stage, :stage_idx).map(&:first)
    end

    def stages
      # TODO, this needs refactoring, see gitlab-ce#26481.

      stages_query = statuses
        .group('stage').select(:stage).order('max(stage_idx)')

      status_sql = statuses.latest.where('stage=sg.stage').status_sql

      warnings_sql = statuses.latest.select('COUNT(*)')
        .where('stage=sg.stage').failed_but_allowed.to_sql

      stages_with_statuses = CommitStatus.from(stages_query, :sg)
        .pluck('sg.stage', status_sql, "(#{warnings_sql})")

      stages_with_statuses.map do |stage|
        Ci::Stage.new(self, Hash[%i[name status warnings].zip(stage)])
      end
    end

    def valid_commit_sha
      if self.sha == Gitlab::Git::BLANK_SHA
        self.errors.add(:sha, " cant be 00000000 (branch removal)")
      end
    end

    def git_author_name
      commit.try(:author_name)
    end

    def git_author_email
      commit.try(:author_email)
    end

    def git_commit_message
      commit.try(:message)
    end

    def git_commit_title
      commit.try(:title)
    end

    def short_sha
      Ci::Pipeline.truncate_sha(sha)
    end

    def commit
      @commit ||= project.commit(sha)
    rescue
      nil
    end

    def branch?
      !tag?
    end

    def stuck?
      pending_builds.any?(&:stuck?)
    end

    def retryable?
      retryable_builds.any?
    end

    def cancelable?
      cancelable_statuses.any?
    end

    def auto_canceled?
      canceled? && auto_canceled_by_id?
    end

    def cancel_running
      Gitlab::OptimisticLocking.retry_lock(cancelable_statuses) do |cancelable|
        cancelable.find_each do |job|
          yield(job) if block_given?
          job.cancel
        end
      end
    end

    def auto_cancel_running(pipeline)
      update(auto_canceled_by: pipeline)

      cancel_running do |job|
        job.auto_canceled_by = pipeline
      end
    end

    def retry_failed(current_user)
      Ci::RetryPipelineService.new(project, current_user)
        .execute(self)
    end

    def mark_as_processable_after_stage(stage_idx)
      builds.skipped.after_stage(stage_idx).find_each(&:process)
    end

    def latest?
      return false unless ref
      commit = project.commit(ref)
      return false unless commit
      commit.sha == sha
    end

    def triggered?
      trigger_requests.any?
    end

    def retried
      @retried ||= (statuses.order(id: :desc) - statuses.latest)
    end

    def coverage
      coverage_array = statuses.latest.map(&:coverage).compact
      if coverage_array.size >= 1
        '%.2f' % (coverage_array.reduce(:+) / coverage_array.size)
      end
    end

    def config_builds_attributes
      return [] unless config_processor

      config_processor.
        builds_for_ref(ref, tag?, trigger_requests.first).
        sort_by { |build| build[:stage_idx] }
    end

    def has_warnings?
      builds.latest.failed_but_allowed.any?
    end

    def config_processor
      return nil unless ci_yaml_file
      return @config_processor if defined?(@config_processor)

      @config_processor ||= begin
        Ci::GitlabCiYamlProcessor.new(ci_yaml_file, project.path_with_namespace)
      rescue Ci::GitlabCiYamlProcessor::ValidationError, Psych::SyntaxError => e
        self.yaml_errors = e.message
        nil
      rescue
        self.yaml_errors = 'Undefined error'
        nil
      end
    end

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

      @ci_yaml_file = project.repository.gitlab_ci_yml_for(sha) rescue nil
    end

    def has_yaml_errors?
      yaml_errors.present?
    end

    def environments
      builds.where.not(environment: nil).success.pluck(:environment).uniq
    end

    # Manually set the notes for a Ci::Pipeline
    # There is no ActiveRecord relation between Ci::Pipeline and notes
    # as they are related to a commit sha. This method helps importing
    # them using the +Gitlab::ImportExport::RelationFactory+ class.
    def notes=(notes)
      notes.each do |note|
        note[:id] = nil
        note[:commit_id] = sha
        note[:noteable_id] = self['id']
        note.save!
      end
    end

    def notes
      Note.for_commit_id(sha)
    end

    def process!
      Ci::ProcessPipelineService.new(project, user).execute(self)
    end

    def update_status
      Gitlab::OptimisticLocking.retry_lock(self) do
        case latest_builds_status
        when 'pending' then enqueue
        when 'running' then run
        when 'success' then succeed
        when 'failed' then drop
        when 'canceled' then cancel
        when 'skipped' then skip
        when 'manual' then block
        end
      end
    end

    def predefined_variables
      [
        { key: 'CI_PIPELINE_ID', value: id.to_s, public: true }
      ]
    end

    def queued_duration
      return unless started_at

      seconds = (started_at - created_at).to_i
      seconds unless seconds.zero?
    end

    def update_duration
      return unless started_at

      self.duration = Gitlab::Ci::PipelineDuration.from_pipeline(self)
    end

    def execute_hooks
      data = pipeline_data
      project.execute_hooks(data, :pipeline_hooks)
      project.execute_services(data, :pipeline_hooks)
    end

    # Merge requests for which the current pipeline is running against
    # the merge request's latest commit.
    def merge_requests
      @merge_requests ||= project.merge_requests
        .where(source_branch: self.ref)
        .select { |merge_request| merge_request.head_pipeline.try(:id) == self.id }
    end

    # All the merge requests for which the current pipeline runs/ran against
    def all_merge_requests
      @all_merge_requests ||= project.merge_requests.where(source_branch: ref)
    end

    def detailed_status(current_user)
      Gitlab::Ci::Status::Pipeline::Factory
        .new(self, current_user)
        .fabricate!
    end

    private

    def pipeline_data
      Gitlab::DataBuilder::Pipeline.build(self)
    end

    def latest_builds_status
      return 'failed' unless yaml_errors.blank?

      statuses.latest.status || 'skipped'
    end

    def keep_around_commits
      return unless project

      project.repository.keep_around(self.sha)
      project.repository.keep_around(self.before_sha)
    end
  end
end


text:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Changelog for package hector_slam_launch
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

0.3.3 (2014-06-15)
------------------

0.3.2 (2014-03-30)
------------------
* Add arguments to launch files for specifying geotiff file path
* Update rviz config to have proper default displays
* deleted quadrotor_uav.launch (moved to hector_quadrotor)
* Contributors: Johannes Meyer, Stefan Kohlbrecher

0.3.1 (2013-10-09)
------------------
* updated rviz config to the new .rviz format
* added changelogs

0.3.0 (2013-08-08)
------------------
* catkinized hector_slam

redpajama_set_name: RedPajamaGithub


text:
require('amdefine/intercept');

var unit = require('../../src/monad/unit');

var mAddOne = function(v) {
    return unit(v + 1);
};

var mAddTwo = function(v) {
    return unit(v + 2);
};

var unWrap = function(v) { return v; };

describe('monad/unit', function() {
    describe('obey monads axioms', function() {
        it('it should fulfil left identity - first law', function() {
            var right = unit(1).bind(mAddOne);
            var left = mAddOne(1);

            right.bind(unWrap).should.be.eql(left.bind(unWrap))
        });
        it('it should fulfil right identity - second law', function() {
            var right = unit(1).bind(unit);
            var left = unit(1);

            right.bind(unWrap).should.be.eql(left.bind(unWrap))
        });
        it('it should fulfil associative identity - third law', function() {
            var right = unit(1).bind(mAddOne).bind(mAddTwo);
            var left = unit(1).bind(function(x) {
                return mAddOne(x).bind(mAddTwo)
            });

            right.bind(unWrap).should.be.eql(left.bind(unWrap))
        });
    });
});


text:
package org.givwenzen.experimental;

import org.givwenzen.GivWenZen;
import org.givwenzen.GivWenZenExecutor;
import org.givwenzen.GivWenZenExecutorCreator;

public class GivWenZenForJUnit implements GivWenZen {

    private GivWenZenExecutor executor;

    /**
     * This executor can be run from jUnit.
     *

     * The main use case is to 'gently' introduce the idea of GWZ to the
     * developers.
     *

     * Here is the idea: there is a new team that didn't use fitnesse at all.
     * For first couple of iterations they write some jUnits with GWZ. After a
     * while the team is familar with the GWZ concept. The issues related to
     * functional testing are resolved (e.g. there is a DB for tests,
     * auto-rollback on tearDown is ready, tests pass consistently) This is
     * finally the time to introduce Fitnesse and refactor the tests to be used
     * in Fitnesse.
     *

     * Example:
     *
     *

     * @DomainSteps
     * public class GivWenZenWithJUnitTest {
     *
     *     GivWenZen gwz = new GivWenZenForJUnit(this);
     *
     *     boolean happy = false;
     *
     *     @DomainStep("i go to the coffee shop")
     *     public void iGoToShop() {
     *         happy = true;
     *     }
     *
     *     @DomainStep("i am happy")
     *     public void iAmInShop() {
     *         assertTrue(happy);
     *     }
     *
     *     @Test
     *     public void shouldVisitCoffeeShop() throws Exception {
     *         gwz.when("i go to the coffee shop");
     *         gwz.then("i am happy");
     *     }
     * }
     *

     *
     * @param test
     */
    public GivWenZenForJUnit(Object test) {
        if (test == null) {
            throw new RuntimeException("test cannot be null");
        }
        // String basePackageForSteps = DomainStepFinder.DEFAULT_STEP_PACKAGE;
        String basePackageForSteps = test.getClass().getPackage().getName()
                + ".";

        executor = GivWenZenExecutorCreator.instance().stepClassBasePackage(
                basePackageForSteps).create();
    }

    @Override
    public Object and(String methodString) throws Exception {
        return executor.and(methodString);
    }

    @Override
    public Object given(String methodString) throws Exception {
        return executor.given(methodString);
    }

    @Override
    public Object then(String methodString) throws Exception {
        return executor.then(methodString);
    }

    @Override
    public Object when(String methodString) throws Exception {
        return executor.when(methodString);
    }
}


text:
package org.bouncycastle.crypto.test;

import java.math.BigInteger;
import java.security.SecureRandom;

import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.crypto.params.ParametersWithRandom;
import org.bouncycastle.crypto.signers.ECNRSigner;
import org.bouncycastle.math.ec.ECConstants;
import org.bouncycastle.math.ec.ECCurve;
import org.bouncycastle.util.BigIntegers;
import org.bouncycastle.util.encoders.Hex;
import org.bouncycastle.util.test.FixedSecureRandom;
import org.bouncycastle.util.test.SimpleTest;

/**
 * ECNR tests.
 */
public class ECNRTest
    extends SimpleTest
{
    /**
     * a basic regression test with 239 bit prime
     */
    BigInteger r = new BigInteger("308636143175167811492623515537541734843573549327605293463169625072911693");
    BigInteger s = new BigInteger("852401710738814635664888632022555967400445256405412579597015412971797143");

    byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("700000017569056646655505781757157107570501575775705779575555657156756655"));

    SecureRandom    k = new FixedSecureRandom(true, kData);

    private void ecNR239bitPrime()
    {
        BigInteger n = new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307");

        ECCurve.Fp curve = new ECCurve.Fp(
            new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q
            new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a
            new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16), // b
            n, ECConstants.ONE);

        ECDomainParameters params = new ECDomainParameters(
            curve,
            curve.decodePoint(Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G
            n);

        ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(
            new BigInteger("876300101507107567501066130761671078357010671067781776716671676178726717"), // d
            params);

        ECNRSigner ecnr = new ECNRSigner();
        ParametersWithRandom param = new ParametersWithRandom(priKey, k);

        ecnr.init(true, param);

        byte[] message = new BigInteger("968236873715988614170569073515315707566766479517").toByteArray();
        BigInteger[] sig = ecnr.generateSignature(message);

        if (!r.equals(sig[0]))
        {
            fail("r component wrong.", r, sig[0]);
        }

        if (!s.equals(sig[1]))
        {
            fail("s component wrong.", s, sig[1]);
        }

        // Verify the signature
        ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
            curve.decodePoint(Hex.decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")), // Q
            params);

        ecnr.init(false, pubKey);
        if (!ecnr.verifySignature(message, sig[0], sig[1]))
        {
            fail("signature fails");
        }
    }

    public String getName()
    {
        return "ECNR";
    }

    public void performTest()
    {
        ecNR239bitPrime();
    }

    public static void main(
        String[]    args)
    {
        runTest(new ECNRTest());
    }
}


text:
/*global jQuery:true */

/*
 * Fake Sizzle using jQuery.
 */
define("tinymce/dom/Sizzle", [], function() {
	// Detect if jQuery is loaded
	if (!window.jQuery) {
		throw new Error("Load jQuery first");
	}

	var $ = jQuery;

	function Sizzle(selector, context, results, seed) {
		return $.find(selector, context, results, seed);
	}

	Sizzle.matches = function(expr, elements) {
		return $(elements).is(expr) ? elements : [];
	};

	return Sizzle;
});


text:
<component name="libraryTable">
  <library name="Gradle: org.apache.httpcomponents:httpmime:4.5">
    <CLASSES>
      <root url="jar://$MAVEN_REPOSITORY$/org/apache/httpcomponents/httpmime/4.5/httpmime-4.5.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES>
      <root url="jar://$MAVEN_REPOSITORY$/org/apache/httpcomponents/httpmime/4.5/httpmime-4.5-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Entities;
using System.Data;

namespace Data
{
    public class OrderDetailData : DataAccessComponent
    {

        /// <summary>
        ///
        /// </summary>
        /// <param name="orderDetail"></param>
        /// <returns></returns>
        public OrderDetail Create(OrderDetail orderD)
        {
            const string sqlStatement = "INSERT INTO dbo.OrderDetail([OrderId], [ProductId], [Price], [Quantity], [CreatedBy]) " +
                "VALUES(@OrderId, @ProductId, @Price, @Quantity, @CreatedBy); SELECT SCOPE_IDENTITY();";

            var connection = Db.CreateOpenConnection();
            using (var cmd = Db.CreateCommand(sqlStatement, connection))
            {
               cmd.Parameters.Add(Db.CreateParameter("@OrderId", orderD.OrderId));
               cmd.Parameters.Add(Db.CreateParameter("@ProductId", orderD.ProductId));
               cmd.Parameters.Add(Db.CreateParameter("@Price", orderD.Price));
               cmd.Parameters.Add(Db.CreateParameter("@Quantity", orderD.Quantity));
               cmd.Parameters.Add(Db.CreateParameter("@CreatedBy", orderD.CreatedBy));
               // Obtener el valor de la primary key.
               orderD.Id = Convert.ToInt32(cmd.ExecuteScalar());
            }

            return orderD;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="orderDetail"></param>
        public void UpdateById(OrderDetail orderD)
        {
            const string sqlStatement = "UPDATE dbo.OrderDetail " +
                "SET [OrderId]=@OrderId, " +
                    "[ProductId]=@ProductId, " +
                    "[Price]=@Price, " +
                    "[Quantity]=@Quantity, " +
                    "[ChangedOn]=@ChangedOn, " +
                    "[ChangedBy]=@ChangedBy " +
                "WHERE [Id]=@Id ";

            var connection = Db.CreateOpenConnection();
            using (var cmd = Db.CreateCommand(sqlStatement, connection))
            {
               cmd.Parameters.Add(Db.CreateParameter("@OrderId", orderD.OrderId));
               cmd.Parameters.Add(Db.CreateParameter("@ProductId", orderD.ProductId));
               cmd.Parameters.Add(Db.CreateParameter("@Price", orderD.Price));
               cmd.Parameters.Add(Db.CreateParameter("@Quantity", orderD.Quantity));
               cmd.Parameters.Add(Db.CreateParameter("@ChangedOn", orderD.ChangedOn));
               cmd.Parameters.Add(Db.CreateParameter("@ChangedBy", orderD.ChangedBy));
               cmd.Parameters.Add(Db.CreateParameter("@Id", orderD.Id));
               cmd.ExecuteNonQuery();
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="id"></param>
        public void DeleteById(int id)
        {
            const string sqlStatement = "DELETE dbo.OrderDetail WHERE [Id]=@Id ";
            var connection = Db.CreateOpenConnection();
            using (var cmd = Db.CreateCommand(sqlStatement, connection))
            {
               cmd.Parameters.Add(Db.CreateParameter("@Id", id));
               cmd.ExecuteNonQuery();
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public OrderDetail SelectById(int id)
        {
            const string sqlStatement = "SELECT [Id], [OrderId], [ProductId], [Price], [Quantity], [CreatedOn], [CreatedBy], [ChangedOn], [ChangedBy] " +
                "FROM dbo.OrderDetail WHERE [Id]=@Id ";

            OrderDetail orderD = null;
            var connection = Db.CreateOpenConnection();
            using (var cmd = Db.CreateCommand(sqlStatement, connection))
            {
               cmd.Parameters.Add(Db.CreateParameter("@Id", id));
               using (var dr = cmd.ExecuteReader())
               {
                   if (dr.Read()) orderD = LoadOrderDetail(dr);
               }
            }

            return orderD;
        }

        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public List<OrderDetail> Select()
        {
            // WARNING! Performance
            const string sqlStatement = "SELECT [Id], [OrderId], [ProductId], [Price], [Quantity], [CreatedOn], [CreatedBy], [ChangedOn], [ChangedBy] FROM dbo.OrderDetail ";

            var result = new List<OrderDetail>();
            var connection = Db.CreateOpenConnection();
            using (var cmd = Db.CreateCommand(sqlStatement, connection))
            {
               using (var dr = cmd.ExecuteReader())
               {
                   while (dr.Read())
                   {
                       var orderD = LoadOrderDetail(dr); // Mapper
                       result.Add(orderD);
                   }
               }
            }

            return result;
        }

        /// <summary>
        /// Crea un nuevo OrderDetail desde un Datareader.
        /// </summary>
        /// <param name="dr">Objeto DataReader.</param>
        /// <returns>Retorna un objeto OrderDetail.</returns>
        private static OrderDetail LoadOrderDetail(IDataReader dr)
        {
            var orderD = new OrderDetail
            {
                Id = GetDataValue<int>(dr, "Id"),
                OrderId = GetDataValue<int>(dr, "OrderId"),
                ProductId = GetDataValue<int>(dr, "ProductId"),
                Price = GetDataValue<double>(dr, "Price"),
                Quantity = GetDataValue<int>(dr, "Quantity"),
                CreatedOn = GetDataValue<DateTime>(dr, "CreatedOn"),
                CreatedBy = GetDataValue<int>(dr, "CreatedBy"),
                ChangedOn = GetDataValue<DateTime>(dr, "ChangedOn"),
                ChangedBy = GetDataValue<int>(dr, "ChangedBy")
            };

            return orderD;
        }

    }
}


text:
package org.apereo.cas.configuration.model.core.services;

import org.apereo.cas.configuration.model.BaseRestEndpointProperties;
import org.apereo.cas.configuration.support.RequiresModule;

import com.fasterxml.jackson.annotation.JsonFilter;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;

import java.io.Serial;

/**
 * This is {@link RestfulServiceRegistryProperties}.
 *
 * @author Misagh Moayyed
 * @since 6.4.0
 */
@RequiresModule(name = "cas-server-support-rest-service-registry")
@Accessors(chain = true)
@Getter
@Setter
@JsonFilter("RestfulServiceRegistryProperties")
public class RestfulServiceRegistryProperties extends BaseRestEndpointProperties {
    @Serial
    private static final long serialVersionUID = 7086088180957285517L;
}


text:
import datetime
import os.path
from collections import defaultdict, OrderedDict

from conference.models import Conference, AttendeeProfile
from django.conf import settings
from django.urls import reverse
from django.contrib.auth.models import User
from assopy import utils as autils
from p3 import models as p3models
from assopy import models as assopy_models
from conference import models as cmodels

from django.contrib.auth.decorators import user_passes_test

### Decorators

def group_required(*group_names):
    """ Check for group membership before granting access to the view.

        You can pass in one or more group names to the decorator. The
        user has to be member of all listed groups.
    """
    def group_membership_check(user):
        if not user.is_authenticated:
            return False
        if user.is_superuser:
            return True
        return bool(user.groups.filter(name__in=group_names))
    return user_passes_test(group_membership_check)

### Helpers
def assign_ticket_to_user(ticket, user=None):
    """ Assign ticket to the given user (defaults to buyer of the
        ticket if not given).
    """
    if user is None:
        user = ticket.user

    # Get or create the TicketConference record associated with the
    # Ticket
    try:
        p3c = ticket.p3_conference
    except p3models.TicketConference.DoesNotExist:
        p3c = None
    if p3c is None:
        p3c = p3models.TicketConference(ticket=ticket)

    # Set attendee name on the ticket
    ticket.name = ('%s %s' % (user.first_name, user.last_name)).strip()
    ticket.user = user
    ticket.save()

    # Associate the email address with the ticket, if possible
    try:
        check_user = autils.get_user_account_from_email(user.email)
    except User.MultipleObjectsReturned:
        # Use a work-around by setting the .assigned_to to '';
        # this only works if the buyer is the attendee and the
        # user will have other issues in the system as well.
        p3c.assigned_to = ''
    else:
        p3c.assigned_to = user.email

    p3c.save()

def spam_recruiter_by_conf(conf):
    """ Return a queryset with the User who have agreed to be
    contacted via email for the purpose of recruiting."""
    tickets = settings.CONFERENCE_TICKETS(conf, ticket_type='conference')
    owned = tickets.filter(p3_conference__assigned_to='')
    assigned = tickets.exclude(p3_conference__assigned_to='')

    first_run = User.objects\
        .filter(\
            id__in=owned.values('user'),\
            attendeeprofile__p3_profile__spam_recruiting=True)

    second_run = User.objects\
        .filter(\
            email__in=assigned.values('p3_conference__assigned_to'),\
            attendeeprofile__p3_profile__spam_recruiting=True)
    return first_run | second_run

from django.core.cache import cache
from django.utils.http import urlquote
from hashlib import md5 as md5_constructor

def template_cache_name(fragment_name, *variables):
    args = md5_constructor(b':'.join([urlquote(var) for var in variables]))
    return 'template.cache.%s.%s' % (fragment_name, args.hexdigest())

def invalidate_template_cache(fragment_name, *variables):
    args = md5_constructor(b':'.join([urlquote(var) for var in variables]))
    cache_key = 'template.cache.%s.%s' % (fragment_name, args.hexdigest())
    cache.delete(cache_key)
    return

# Database access helpers

def clean_title(title):
    """ Clean a talk title. """
    title = title.strip()
    if not title:
        return title

    # Remove whitespace
    title = title.strip()
    # Remove double spaces
    title = title.replace("  ", " ")
    # Remove quotes
    if title[0] == '"' and title[-1] == '"':
        title = title[1:-1]
    return title

def talk_title(talk):
    """ Return a clean talk title given a Talk. """
    # Remove whitespace
    title = talk.title.strip()
    return clean_title(title)

def profile_url(user):
    """ Return the URL of the user profile. """
    return reverse('profiles:profile', args=[user.attendeeprofile.slug])

def talk_schedule(talk):
    """ Return the list of timeslots when the talk is scheduled."""
    slots = []
    events = talk.event_set.all()
    for event in events:
        timerange = event.get_time_range()
        slot = '{}, {}'.format(str(timerange[0]), str(timerange[1]))
        slots.append(slot)
    return slots

def talk_type(talk):
    """ Return the pretty name for the type of the talk."""
    if talk.admin_type:
        typ = talk.get_admin_type_display()
    else:
        typ = talk.get_type_display()
    return typ

def group_talks_by_type(talks):
    """ Return a dict with lists of talks grouped by the type of talk."""
    type_talks = defaultdict(list)
    for talk in talks:
        type_talks[talk_type(talk)].append(talk)

    return type_talks

def group_all_talks_by_admin_type(conference, talk_status='accepted'):
        """ Return a dict with the talks for the `conference`
        with status `talk_status` separated by administrative type. """
        # Group by admin types
        talks = OrderedDict()
        for adm_type, type_name in dict(cmodels.TALK_ADMIN_TYPE).items():
            talks[type_name] = list(cmodels.Talk.objects
                                    .filter(conference=conference,
                                            status=talk_status,
                                            admin_type=adm_type))

        type_groups = {'talk':        ['t_30', 't_45', 't_60'],
                       'interactive': ['i_60'],
                       'training':    ['r_180'],
                       'panel':       ['p_60', 'p_90'],
                       'poster':      ['p_180'],
                       'helpdesk':    ['h_180'],
                      }

        for grp_name, grp_types in type_groups.items():
            grp_talks = []
            for talk_type in grp_types:
                bag = list(cmodels.Talk.objects
                           .filter(conference=conference,
                                   status=talk_status,
                                   type=talk_type,
                                   admin_type=''))
                grp_talks.extend(bag)

            talks[grp_name] = grp_talks

        return talks

def speaker_listing(talk):
    """ Return a list of the speakers' names of the talk."""
    return ['{} {}'.format(speaker.user.first_name, speaker.user.last_name)
            for speaker in talk.get_all_speakers()]

def speaker_emails(talk):
    """ Return a list of the speakers' emails of the talk."""
    return ['{}'.format(speaker.user.email) for speaker in talk.get_all_speakers()]

def speaker_twitters(talk):
    """ Return a list of the speakers' twitter handles of the talk."""
    return ['@{}'.format(speaker.user.attendeeprofile.p3_profile.twitter)
            for speaker in talk.get_all_speakers()]

def get_all_order_tickets(conference=settings.CONFERENCE_CONFERENCE):
    """ Return all valid conference tickets for the conference."""
    def conference_year(conference):
        return conference[-2:]

    year = conference_year(conference)
    orders = assopy_models.Order.objects.filter(_complete=True)
    conf_orders = (order for order in orders if order.code.startswith('O/{}.'.format(year)))
    tickets = (
        ordi.ticket for order in conf_orders
        for ordi in order.orderitem_set.all()
        if ordi.ticket is not None
    )
    conf_order_tkts = [tk for tk in tickets if is_valid_ticket(tk, conference)]
    return conf_order_tkts

def get_orders_from(user):
    """ Return the list of complete orders made by the user. """
    return assopy_models.Order.objects.filter(_complete=True, user=user.id)

def get_tickets_assigned_to(user):
    """ Return the list of tickets assigned to the user. """
    return p3models.TicketConference.objects.filter(assigned_to=user.email)

def is_ticket_assigned_to_someone_else(ticket, user):
    """ Return False if the ticket is assigned to the user, True otherwise."""
    tickets = p3models.TicketConference.objects.filter(ticket_id=ticket.id)

    if not tickets:
        raise AttributeError('Could not find any ticket with id '
                             '{}.'.format(ticket.id))

    if len(tickets) > 1:
        raise RuntimeError('Got more than one ticket from a ticket_id.'
                           'Tickets obtained: {}.'.format(tickets))

    tkt = tickets[0]
    if tkt.ticket.user_id != user.id:
        return True

    if not tkt.assigned_to:
        return False

    if tkt.assigned_to == user.email:
        return False
    else:
        return True

def is_valid_ticket(ticket, conference_name):
    """ Return True if the ticket is a valid conference ticket for the
    given conference.
    """
    tickets = cmodels.Ticket.objects.filter(id=ticket.id,
                                            fare__conference=conference_name,
                                            fare__ticket_type='conference',
                                            orderitem__order___complete=True,
                                            frozen=False,)
    return bool(tickets)

def has_ticket(user, conference_name):
    """ Return True if the user has any valid ticket assigned to him,
    False otherwise."""
    tickets = get_tickets_assigned_to(user)
    if tickets:
        return True

    user_tickets = list(user.ticket_set.all())
    orders = get_orders_from(user)
    if orders:
        order_tkts = [ordi.ticket
                      for order in orders
                      for ordi in order.orderitem_set.all()
                      if ordi.ticket is not None]
        user_tickets.extend(order_tkts)

    for tkt in user_tickets:
        if is_valid_ticket(tkt, conference_name) and \
         not is_ticket_assigned_to_someone_else(tkt, user):
            return True

    return False

def have_tickets(talk, conference_name):
    """ Return True if all speakers of the talk have a ticket,
    False otherwise.
    """
    usrs = talk.get_all_speakers()
    return [has_ticket(user.user, conference_name) for user in usrs]

def talk_track_title(talk):
    """ Return a list of the tracks when the talk is scheduled. """
    event = talk.get_event()
    if not event:
        return []
    return [tr.title for tr in event.tracks.all()]

def talk_votes(talk):
    """ Return a dict[user_id: n_votes] for the given talk."""
    qs = cmodels.VotoTalk.objects.filter(talk=talk.id).all()
    user_votes = []
    for v in qs:
        user_votes.append({v.user_id: v.vote})
    return user_votes

def speaker_companies(talk):
    """ Return a set of the companies of the speakers of the talk."""
    companies = sorted(
        set(speaker.user.attendeeprofile.company
            for speaker in talk.speakers.all()
                if speaker.user.attendeeprofile))
    return companies

def get_profile_company(profile):
    """ Return a (title, company) to generate a textual profile for the user.
    Since users sometimes use Company and Tag with the same content.
    """
    title = ''
    company = ''
    if profile.job_title and profile.company:
        if profile.company.lower().strip() in profile.job_title.lower().strip():
            title = ''
            company = profile.job_title
        else:
            title = profile.job_title
            company = profile.company
    elif profile.job_title:
        title = profile.job_title
    elif profile.company:
        company = profile.company

    return title, company


text:
<!DOCTYPE html>

        <title>My Sample Project</title>
				<link rel="stylesheet" href="css/main.css">

My Sample Project - Main


text:
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="theme-color" content="#000000">

    <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    <link rel="manifest" href="/manifest.json">
    <link rel="shortcut icon" href="/favicon.ico">

    <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
    <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
    <link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5">
    <meta name="apple-mobile-web-app-title" content="React Highcharts Wrapper">
    <meta name="application-name" content="React Highcharts Wrapper">
    <meta name="theme-color" content="#ffffff">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="msapplication-navbutton-color" content="#ff0000">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="msapplication-starturl" content="/">

    <meta property="og:image" content="/og-image.jpg">
    <meta property="og:image:width" content="279">
    <meta property="og:image:height" content="279">
    <meta property="og:description" content="A React wrapper for building Highcharts components.">
    <meta property="og:title" content="React Highcharts Wrapper">
    <meta property="og:url" content="https://react-highcharts-wrapper.firebaseapp.com">

    <meta name="description" content="A React wrapper for building Highcharts components." />
    <meta name="keywords" content="highcharts, react, highcharts-react, react-highcharts, oss, javascript, react provider, react hoc, provider, hoc, dataviz, micro-module, npm" />
    <meta name="author" content="metatags generator">
    <meta name="robots" content="index, follow">
    <meta name="revisit-after" content="1 days">
    <title>React Highcharts Wrapper</title>

      You need to enable JavaScript to run this app.


text:
namespace LinearDataStructures.ADT
{
    public class Stack<T>
    {
        private int initialSize = 16;
        private T[] data;
        private int index;

        public Stack()
        {
            this.data = new T[initialSize];
            this.index = 0;
        }

        public int Count
        {
            get { return index; }
        }

        public T Peek
        {
            get { return this.data[this.Count - 1]; }
        }

        public void Push(T value)
        {
            if(index >= this.data.Length)
            {
                this.ResizeArray();
            }

            this.data[index] = value;
            index++;
        }

        public T Pop()
        {
            index--;
            return this.data[this.Count];
        }

        private void ResizeArray()
        {
            initialSize *= 2;
            T[] dataCopy = new T[initialSize];
            this.data.CopyTo(dataCopy, 0);

            this.data = new T[initialSize];
            dataCopy.CopyTo(this.data, 0);
        }
    }
}


text:
{% extends "zerver/portico.html" %}
{% set entrypoint = "landing-page" %}

{% set PAGE_TITLE = "Zulip for communities" %}

{% set PAGE_DESCRIPTION = "Zulip is designed with communities in mind, including
  open-source projects, research collaborations, and volunteer organizations.
  Reach out for a sponsorship!" %}

{% block customhead %}
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
{% endblock %}

{% block portico_content %}

{% include 'zerver/landing_nav.html' %}

Zulip for communities

            Open-source projects, research collaborations, volunteer
            organizations.
Most communities get an 85%+ discount
            on Zulip Cloud Standard!

            Learn how the Recurse
            Center, Rust language,

and Asciidoctor communities are using Zulip.

                {{ _('Create organization') }}

                {{ _('Request sponsorship') }}

                {{ _('Self-host Zulip') }}

                {{ render_markdown_path('corporate/for/communities.md') }}

            Most communities get an 85%+ discount on Zulip Cloud Standard!

 Join the hundreds of communities we sponsor. Contact
                sales@zulip.com to check whether your organization
                qualifies, or request
                sponsorship today.

                {{ _('Create organization') }}

                {{ _('Request sponsorship') }}

                {{ _('Self-host Zulip') }}

{% endblock %}


text:
from subprocess import call
from subprocess import Popen
from subprocess import check_output
import subprocess
import signal
import sys
import time
import os

# input arguments
lf_bin = None
afl_bin = None
seed_corp = None
out_corp = None
dictio = None
dict_specified = False
# run commands
afl_firstrun_cmd = None
afl_default_run_cmd = None
lf_run_cmd = None
covtracker_run_cmd = None
# minimization commands
make_temp_corpus_dirs = None
afl_minimize_cmd = None
remove_temp_corpus_dirs = None
# runtime
running_fuzz_procs = []
TOTAL_RUNTIME = 60 * 60 * 12  # in seconds
SWITCH_TIME_AFL = 60 * 40  # in seconds
SWITCH_TIME_LF = 60 * 20  # in seconds
runtime_counter = 0
NR_OF_THREADS = 4
dev_null = None
covtracker_dir = None
crashes_dir = None
TEMP_DIR_IN_LIBF = 'temp_in_libfuzzer'
TEMP_DIR_OUT_LIBF = 'temp_out_libfuzzer'
MERGED_DIR_LIBF = 'final_libfuzzer'
TEMP_MINIMIZE_DIR1 = 'temp_minimize_dir1'
TEMP_MINIMIZE_DIR2 = 'temp_minimize_dir2'

''' Functions '''

def parse_arguments():
    global lf_bin, afl_bin, seed_corp, out_corp, dictio, dict_specified
    if not (len(sys.argv) == 5 or len(sys.argv) == 6):
        print '\nUsage:\t\tpython2.7 run_cooperative.py <lf_binary> <afl_binary> <seed_corp_dir> ' \
              '<out_corp_dir> <dictionary(optional)> '
        print 'Usage example:\tpython2.7 run_cooperative.py lf_bin afl_bin cmin_seed_dir output_dir example.dict'
        print '\nMake sure all the test cases are in the root directory of the (afl-cmin minimized) seed corpus.\n'
        sys.exit()
    else:
        lf_bin = str(sys.argv[1])
        afl_bin = str(sys.argv[2])
        seed_corp = str(sys.argv[3])
        out_corp = str(sys.argv[4])
        if len(sys.argv) == 6:
            dict_specified = True
            dictio = str(sys.argv[5])

def validate_input_arguments():
    global lf_bin, afl_bin, seed_corp, out_corp, dictio
    if not (os.path.isdir(seed_corp) is True and os.path.isdir(out_corp) is True
            and os.path.isfile(lf_bin) is True and os.path.isfile(afl_bin) is True):
        print '\nInput arguments validation failed.\n'
        sys.exit()
    if dict_specified is True:
        if not (os.path.isfile(dictio) is True):
            print '\nInput arguments validation failed.\n'
            sys.exit()
    if os.path.isdir(TEMP_DIR_IN_LIBF) or os.path.isdir(TEMP_DIR_OUT_LIBF) or os.path.isdir(MERGED_DIR_LIBF) or \
            os.path.isdir(TEMP_MINIMIZE_DIR1) or os.path.isdir(TEMP_MINIMIZE_DIR2):
        print '\nTemp directory already exist.\n'
        sys.exit()

def generate_run_commands():
    global lf_run_cmd, afl_default_run_cmd, afl_firstrun_cmd, out_corp, seed_corp, lf_bin, dictio
    lf_run_options = ' -jobs=1000 -workers=' + str(NR_OF_THREADS) + ' -print_final_stats=1 -rss_limit_mb=0'
    if dict_specified:
        afl_firstrun_cmd = 'afl-fuzz -i ' + seed_corp + ' -o ' + out_corp + ' -m none -x ' + dictio
        afl_default_run_cmd = 'afl-fuzz -i ' + MERGED_DIR_LIBF + ' -o ' + out_corp + ' -m none -x ' + dictio
        lf_run_cmd = './' + lf_bin + ' ' + TEMP_DIR_OUT_LIBF + ' ' + TEMP_DIR_IN_LIBF + \
                     lf_run_options + ' -dict=' + dictio
    else:
        afl_firstrun_cmd = 'afl-fuzz -i ' + seed_corp + ' -o ' + out_corp + ' -m none'
        afl_default_run_cmd = 'afl-fuzz -i ' + MERGED_DIR_LIBF + ' -o ' + out_corp + ' -m none'
        lf_run_cmd = './' + lf_bin + ' ' + TEMP_DIR_OUT_LIBF + ' ' + TEMP_DIR_IN_LIBF + lf_run_options

def initialize_cooperative_fuzzer():
    global dev_null, out_corp, covtracker_dir, crashes_dir, seed_corp
    print '\nrun_cooperative.py:\t>> Fuzz testing with libFuzzer and AFL.'
    print 'run_cooperative.py:\t>> Number of threads is set to ' + str(NR_OF_THREADS) + '.'
    print 'run_cooperative.py:\t>> Total runtime is set to ' + str(TOTAL_RUNTIME) + ' seconds.'
    print 'run_cooperative.py:\t>> Switch time is set to ' + str(SWITCH_TIME_AFL) + ' seconds.'
    call('echo core >/proc/sys/kernel/core_pattern', stdout=dev_null, stderr=subprocess.STDOUT, shell=True)
    # call('echo performance | tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor', stdout=dev_null,
    #      stderr=subprocess.STDOUT, shell=True)
    covtracker_dir = 'r_cov_' + out_corp
    crashes_dir = 'r_cr_' + out_corp

    # make directories to save state
    call('rm -rf ' + covtracker_dir, stdout=dev_null, stderr=subprocess.STDOUT, shell=True)
    call('rm -rf ' + crashes_dir, stdout=dev_null, stderr=subprocess.STDOUT, shell=True)
    call('mkdir ' + covtracker_dir, stdout=dev_null, stderr=subprocess.STDOUT, shell=True)
    call('mkdir ' + crashes_dir, stdout=dev_null, stderr=subprocess.STDOUT, shell=True)

    # save seed corpus
    cov_save_location = './' + covtracker_dir + '/0'
    cov_save_command = 'cp ./' + seed_corp + '/* ' + cov_save_location
    call('mkdir ' + cov_save_location, stdout=dev_null, stderr=subprocess.STDOUT, shell=True)
    call(cov_save_command, stdout=dev_null, stderr=subprocess.STDOUT, shell=True)

def run_cooperative_fuzzer():
    global dev_null, out_corp, runtime_counter
    dev_null = open(os.devnull, 'w')
    counter = 1
    while True:
        try:
            runtime_counter += SWITCH_TIME_AFL
            exec_afl_iteration(counter)
            runtime_counter += SWITCH_TIME_LF
            exec_lf_iteration(counter)

            if runtime_counter == TOTAL_RUNTIME:
                print '\nrun_cooperative.py:\tFuzz testing has finished after ' + str(TOTAL_RUNTIME) + ' seconds.'
                close_program()

            minimize_corpus()
            counter += 1
        except KeyboardInterrupt:
            print '\nrun_cooperative.py:\tReceived interrupt...exiting.\n'
            close_program()

def exec_afl_iteration(counter):
    global afl_firstrun_cmd, afl_default_run_cmd, dev_null, covtracker_dir, runtime_counter, out_corp
    print '\nrun_cooperative.py:\tAFL - started iteration ' + str(counter) + '.'

    # always start with new output corpus
    call('rm -rf ' + out_corp, stdout=dev_null, stderr=subprocess.STDOUT, shell=True)
    call('mkdir ' + out_corp, stdout=dev_null, stderr=subprocess.STDOUT, shell=True)

    # start AFL from seed corpus, or from libFuzzer input corpus
    if counter == 1:
        afl_run_multi_threaded(afl_firstrun_cmd)
    else:
        afl_run_multi_threaded(afl_default_run_cmd)
    time.sleep(SWITCH_TIME_AFL)

    # clean up
    close_current_fuzz_job()
    store_current_afl_state()
    print 'run_cooperative.py:\tAFL - finished iteration ' + str(counter) + '.'

def afl_run_multi_threaded(run_cmd):
    global dev_null, afl_bin, running_fuzz_procs
    fuzzer_id = 1

    # start main fuzzing instance
    main_run_cmd = run_cmd + ' -M ' + str(fuzzer_id) + ' ./' + afl_bin
    proc = Popen(main_run_cmd, stdout=dev_null, stderr=subprocess.STDOUT, shell=True, preexec_fn=os.setsid)
    running_fuzz_procs.append(proc)

    # start secondary fuzzing instances
    for i in range(NR_OF_THREADS - 1):
        fuzzer_id += 1
        secondary_run_cmd = run_cmd + str(' -S ' + str(fuzzer_id) + ' ./' + afl_bin)
        proc = Popen(secondary_run_cmd, stdout=dev_null, stderr=subprocess.STDOUT, shell=True, preexec_fn=os.setsid)
        running_fuzz_procs.append(proc)

def store_current_afl_state():
    global covtracker_dir, crashes_dir, out_corp

    # save current corpus
    cov_save_location = './' + covtracker_dir + '/' + str(runtime_counter)
    cov_save_command = 'cp ./' + out_corp + '/1/queue/* ' + cov_save_location
    call('mkdir ' + cov_save_location, stdout=dev_null, stderr=subprocess.STDOUT, shell=True)
    call(cov_save_command, stdout=dev_null, stderr=subprocess.STDOUT, shell=True)

    # save crashes
    for thread in range(NR_OF_THREADS):
        thread_instance = thread + 1
        crashes_save_command = 'cp ./' + out_corp + '/' + str(thread_instance) + '/crashes/* ' + crashes_dir
        call(crashes_save_command, stdout=dev_null, stderr=subprocess.STDOUT, shell=True)

def exec_lf_iteration(counter):
    global dev_null, lf_run_cmd, running_fuzz_procs, out_corp
    print '\nrun_cooperative.py:\tlibFuzzer - started iteration ' + str(counter) + '.'

    # prepare directories for libFuzzer
    call('rm -rf ' + TEMP_DIR_IN_LIBF, stdout=dev_null, stderr=subprocess.STDOUT, shell=True)
    call('rm -rf ' + TEMP_DIR_OUT_LIBF, stdout=dev_null, stderr=subprocess.STDOUT, shell=True)
    call('rm -rf ' + MERGED_DIR_LIBF, stdout=dev_null, stderr=subprocess.STDOUT, shell=True)
    call('mkdir ' + TEMP_DIR_IN_LIBF, stdout=dev_null, stderr=subprocess.STDOUT, shell=True)
    call('mkdir ' + TEMP_DIR_OUT_LIBF, stdout=dev_null, stderr=subprocess.STDOUT, shell=True)
    call('mkdir ' + MERGED_DIR_LIBF, stdout=dev_null, stderr=subprocess.STDOUT, shell=True)

    # prepare input corpus and start fuzzing
    get_input_corpus = 'cp ./' + out_corp + '/1/queue/* ' + TEMP_DIR_IN_LIBF
    call(get_input_corpus, stdout=dev_null, stderr=subprocess.STDOUT, shell=True)
    proc = Popen(lf_run_cmd, stdout=dev_null, stderr=subprocess.STDOUT, shell=True, preexec_fn=os.setsid)
    running_fuzz_procs.append(proc)
    time.sleep(SWITCH_TIME_LF)

    # clean up
    close_current_fuzz_job()
    store_current_lf_state()
    print 'run_cooperative.py:\tlibFuzzer - finished iteration ' + str(counter) + '.'

def store_current_lf_state():
    global covtracker_dir, crashes_dir
    call('cp ./' + TEMP_DIR_IN_LIBF + '/* ' + MERGED_DIR_LIBF, stdout=dev_null, stderr=subprocess.STDOUT, shell=True)
    call('cp ./' + TEMP_DIR_OUT_LIBF + '/* ' + MERGED_DIR_LIBF, stdout=dev_null, stderr=subprocess.STDOUT, shell=True)

    # save current corpus
    cov_save_location = './' + covtracker_dir + '/' + str(runtime_counter)
    cov_save_command = 'cp ./' + MERGED_DIR_LIBF + '/* ' + cov_save_location
    call('mkdir ' + cov_save_location, stdout=dev_null, stderr=subprocess.STDOUT, shell=True)
    call(cov_save_command, stdout=dev_null, stderr=subprocess.STDOUT, shell=True)

    # save crashes
    crashes_save_command = 'mv crash-* ' + crashes_dir
    call(crashes_save_command, stdout=dev_null, stderr=subprocess.STDOUT, shell=True)

def minimize_corpus():
    testcases_to_minimize = find_testcases_over_1mb()
    if len(testcases_to_minimize) != 0:
        generate_corpus_minimization_commands()
        print 'run_cooperative.py:\tMinimizing testcases over 1MB...'
        execute_minimization_sequence(testcases_to_minimize)
        print 'run_cooperative.py:\tTestcases minimized.'
    else:
        print 'run_cooperative.py:\tMinimization was not required... continuing without minimization.'

def find_testcases_over_1mb():
    global out_corp
    files_to_minimize = []
    disk_usage_dir = './' + MERGED_DIR_LIBF + '/*'
    disk_usage_output = check_output('du -sh ' + disk_usage_dir, shell=True)
    testcase_list = disk_usage_output.strip().splitlines()

    # create list with paths for testcases that need minimization
    for testcase in testcase_list:
        testcase_size = testcase.split()[0]
        if 'M' in testcase_size:
            files_to_minimize.append(testcase.split()[1])
    return files_to_minimize

def generate_corpus_minimization_commands():
    global afl_minimize_cmd, make_temp_corpus_dirs, remove_temp_corpus_dirs, out_corp, lf_bin, afl_bin
    remove_temp_corpus_dirs = 'rm -rf ' + TEMP_MINIMIZE_DIR1 + ' ' + TEMP_MINIMIZE_DIR2
    make_temp_corpus_dirs = 'mkdir ' + TEMP_MINIMIZE_DIR1 + ' ' + TEMP_MINIMIZE_DIR2
    afl_minimize_cmd = 'afl-cmin -i ' + TEMP_MINIMIZE_DIR1 + ' -o ' + TEMP_MINIMIZE_DIR2 + \
                       ' -m none -- ./' + afl_bin

def execute_minimization_sequence(testcases_to_minimize):
    global make_temp_corpus_dirs, afl_minimize_cmd, remove_temp_corpus_dirs, dev_null, out_corp

    # prepare directories for minimization
    call(remove_temp_corpus_dirs, stdout=dev_null, stderr=subprocess.STDOUT, shell=True)
    call(make_temp_corpus_dirs, stdout=dev_null, stderr=subprocess.STDOUT, shell=True)

    # move test cases that need minimization to a temp directory
    for testcase_path in testcases_to_minimize:
        move_cmd = 'mv ' + testcase_path + ' ' + TEMP_MINIMIZE_DIR1
        call(move_cmd, stdout=dev_null, stderr=subprocess.STDOUT, shell=True)

    # minimize and incorporate minimzed testcases
    call(afl_minimize_cmd, stdout=dev_null, stderr=subprocess.STDOUT, shell=True)
    return_minimized_testcases = 'mv ./' + TEMP_MINIMIZE_DIR2 + '/* ' + MERGED_DIR_LIBF
    call(return_minimized_testcases, stdout=dev_null, stderr=subprocess.STDOUT, shell=True)

def close_program():
    close_current_fuzz_job()
    clean_all_temp_dirs()
    dev_null.close()
    sys.exit()

def close_current_fuzz_job():
    global running_fuzz_procs
    for proc in running_fuzz_procs:
        os.killpg(os.getpgid(proc.pid), signal.SIGTERM)
    running_fuzz_procs = []

def clean_all_temp_dirs():
    call('rm -rf ' + MERGED_DIR_LIBF, stdout=dev_null, stderr=subprocess.STDOUT, shell=True)
    call('rm -rf ' + TEMP_DIR_IN_LIBF, stdout=dev_null, stderr=subprocess.STDOUT, shell=True)
    call('rm -rf ' + TEMP_DIR_OUT_LIBF, stdout=dev_null, stderr=subprocess.STDOUT, shell=True)
    call('rm -rf ' + TEMP_MINIMIZE_DIR1, stdout=dev_null, stderr=subprocess.STDOUT, shell=True)
    call('rm -rf ' + TEMP_MINIMIZE_DIR2, stdout=dev_null, stderr=subprocess.STDOUT, shell=True)

''' Program '''

parse_arguments()
validate_input_arguments()
generate_run_commands()

initialize_cooperative_fuzzer()
run_cooperative_fuzzer()


text:
package org.apache.beam.runners.jet;

import com.hazelcast.jet.Job;
import com.hazelcast.jet.core.JobStatus;
import com.hazelcast.map.IMap;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.annotation.Nonnull;
import org.apache.beam.runners.core.metrics.MetricUpdates;
import org.apache.beam.runners.jet.metrics.JetMetricResults;
import org.apache.beam.sdk.PipelineResult;
import org.apache.beam.sdk.metrics.MetricResults;
import org.joda.time.Duration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/** Jet specific implementation of {@link PipelineResult}. */
@SuppressWarnings({
  "nullness" // TODO(https://issues.apache.org/jira/browse/BEAM-10402)
})
public class JetPipelineResult implements PipelineResult {

  private static final Logger LOG = LoggerFactory.getLogger(JetPipelineResult.class);

  private final Job job;
  private final JetMetricResults metricResults;
  private volatile State terminalState;

  private CompletableFuture<Void> completionFuture;

  JetPipelineResult(@Nonnull Job job, @Nonnull IMap<String, MetricUpdates> metricsAccumulator) {
    this.job = Objects.requireNonNull(job);
    // save the terminal state when the job completes because the `job` instance will become invalid
    // afterwards
    metricResults = new JetMetricResults(metricsAccumulator);
  }

  void setCompletionFuture(CompletableFuture<Void> completionFuture) {
    this.completionFuture = completionFuture;
  }

  void freeze(Throwable throwable) {
    metricResults.freeze();
    terminalState = throwable != null ? State.FAILED : State.DONE;
  }

  @Override
  public State getState() {
    if (terminalState != null) {
      return terminalState;
    }
    JobStatus status = job.getStatus();
    switch (status) {
      case COMPLETED:
        return State.DONE;
      case COMPLETING:
      case RUNNING:
      case STARTING:
        return State.RUNNING;
      case FAILED:
        return State.FAILED;
      case NOT_RUNNING:
      case SUSPENDED:
      case SUSPENDED_EXPORTING_SNAPSHOT:
        return State.STOPPED;
      default:
        LOG.warn("Unhandled " + JobStatus.class.getSimpleName() + ": " + status.name() + "!");
        return State.UNKNOWN;
    }
  }

  @Override
  @SuppressWarnings("EmptyCatch")
  public State cancel() throws IOException {
    if (terminalState != null) {
      throw new IllegalStateException("Job already completed");
    }
    try {
      job.cancel();
      job.join();
    } catch (CancellationException ignored) {
    } catch (Exception e) {
      throw new IOException("Failed to cancel the job: " + e, e);
    }
    return State.FAILED;
  }

  @Override
  public State waitUntilFinish(Duration duration) {
    if (terminalState != null) {
      return terminalState;
    }

    try {
      completionFuture.get(duration.getMillis(), TimeUnit.MILLISECONDS);
      return State.DONE;
    } catch (InterruptedException | TimeoutException e) {
      return getState(); // job should be RUNNING or STOPPED
    } catch (ExecutionException e) {
      throw new CompletionException(e.getCause());
    }
  }

  @Override
  public State waitUntilFinish() {
    return waitUntilFinish(Duration.millis(Long.MAX_VALUE));
  }

  @Override
  public MetricResults metrics() {
    return metricResults;
  }
}


text:
<?php

// Redirect
Header('Location: dashboard.php');

?>

	<title>Deployer</title>
	<link rel="stylesheet" type="text/css" href="css/deployer.css"></link>

Deployer

Update software from repository

Dashboard

Edit Domain Config


text:
app.controller('UserController', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams) {

  var userID = $routeParams.userid; //set this to current patient id $scope.current_user.id

  //patients info
  $http.get('/api/patients/'+ patientID)
    .success(function(data, status, headers, config) {
      console.log(data);
      $scope.patient = data;
  })

  var doctorID = $routeParams.doctorid;

  if (doctorID) {

    $http.get('/api/patients/'+ patientID + '/doctors/' + doctorID)
      .success(function(data, status, headers, config) {
        $scope.doctor = data;
    })
  }
}]);


text:
from django.db import models
from punns.models import Punn
from django.contrib.auth.models import User
from punns.utils import BASE10, BASE62, baseconvert
from django.forms import ModelForm, Textarea
from django.utils.translation import ugettext as _

class Comment(models.Model):
    content = models.TextField(max_length=10000)
    base62id = models.CharField(max_length=140, blank=True)
    author = models.ForeignKey(User)
    punn = models.ForeignKey(Punn)
    karma = models.IntegerField(default=0)
    parent = models.ForeignKey('self',  null=True, blank=True)
    created = models.DateTimeField(auto_now_add = True)
    pub_date = models.DateTimeField(auto_now = True,  null=True, blank=True)
    def __unicode__(self):
        return self.content
    def save(self):
        super(Comment, self).save()
        if not self.base62id:
            self.base62id = baseconvert(str(self.id),BASE10,BASE62)
            self.save()
    @models.permalink
    def get_absolute_url(self):
        return ('punn.views.comment', [str(self.base62id)])


text:
'use strict';

var addFinalProp = require('../utils').addFinalProp;
var mapToObject = require('../utils').mapToObject;
var Platform = require('../enums/Platform');

module.exports = Capabilities;

function Capabilities(instance) {
  addFinalProp(this, '_instance', instance);
}
Capabilities.prototype.asMap = function() {
  return mapToObject(this._instance.asMapSync());
};
Capabilities.prototype.getBrowserName = function() {
  return this._instance.getBrowserNameSync();
};
Capabilities.prototype.getCapability = function(name) {
  return this._instance.getCapabilitySync(name);
};
Capabilities.prototype.getPlatform = function() {
  return new Platform(this._instance.getPlatformSync());
};
Capabilities.prototype.getVersion = function() {
  return this._instance.getVersionSync();
};
Capabilities.prototype.is = function(capabilityName) {
  return this._instance.isSync(capabilityName);
};
Capabilities.prototype.isJavascriptEnabled = function() {
  return this._instance.isJavascriptEnabledSync();
};


text:
class DoubleRange
{
public:
	DoubleRange(double min, double max);

	bool IsInside(double x);
	bool IsInside(DoubleRange *range);
	bool IsOverlapping(DoubleRange *range);

	double Min() const { return min; }
	void Min(const double min) { this->min = min; }

	double Max() const { return min; }
	void Max(const double max) { this->max = max; }

	double Length() const { return max - min; }

private:
	double min, max;
};


text:
package org.mousephenotype.dcc.crawler;

import java.io.File;
import java.util.Timer;
import org.apache.commons.cli.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This is the main application which parses the command line options and starts
 * a crawling session.
 *
 * @author Gagarine Yaikhom <g.yaikhom@har.mrc.ac.uk>
 */
public final class TheApplication {

    private static final Logger LOGGER = LoggerFactory.getLogger(TheApplication.class);

    // used when converting periodicity to sleep time
    public static final long HOUR_TO_MILLISECS = 3600000L;

    // following are various parameters that affect the behaviour of the crawler.
    // Also included is the maximum and minimum values, and the default value
    // that should be used if the user did not specify a value on the command line
    public static final int DEFAULT_POOLSIZE = 10;
    public static final int MIN_POOLSIZE = 1;
    public static final int MAX_POOLSIZE = 10;
    public static final int DEFAULT_NUM_PARALLEL_DOWNLOADS = 1;
    public static final int MIN_NUM_PARALLEL_DOWNLOADS = 1;
    public static final int MAX_NUM_PARALLEL_DOWNLOADS = 10;
    public static final int DEFAULT_MAX_RETRIES = 1;
    public static final int MIN_MAX_RETRIES = 1;
    public static final int MAX_MAX_RETRIES = 5;
    public static final long DEFAULT_PERIODIC_DELAY_IN_HOURS = 0L;
    public static final long MIN_PERIODIC_DELAY_IN_HOURS = 0L;
    public static final String DEFAULT_DATA_DIR = "backup";

    // command line options and their switch keys
    private static final String OPT_HELP = "h";
    private static final String OPT_NUM_PARALLEL_DOWNLOADS = "a";
    private static final String OPT_MAX_RETRIES = "m";
    private static final String OPT_POOL_SIZE = "t";
    private static final String OPT_PERIODIC_DELAY = "p";
    private static final String OPT_DATA_DIR = "d";
    private static final String OPT_SEND_REPORT = "r";
    private static final String OPT_CRAWLER_PROP_FILE = "c";
    private static final String OPT_XMLSERIALISER_PROP_FILE = "s";
    private static final String OPT_XMLVALIDATOR_PROP_FILE = "v";
    private static final String OPT_XMLVALIDATION_RESOURCES_PROP_FILE = "x";
    private static final String OPT_CONTEXT_PROP_FILE = "o";
    private static final Options OPTIONS = new Options();

    // messages to show for each of the command line switches
    static {
        OPTIONS.addOption(OPT_HELP, false, "Show help message on how to use the system.");
        OPTIONS.addOption(OPT_NUM_PARALLEL_DOWNLOADS, true, "Number of parallel downloaders to use.");
        OPTIONS.addOption(OPT_MAX_RETRIES, true, "Maximum number of download retries.");
        OPTIONS.addOption(OPT_POOL_SIZE, true, "Maximum size of the thread pool.");
        OPTIONS.addOption(OPT_PERIODIC_DELAY, true, "Sets the delay (in hours) for periodic runs. If zero, the program returns immediately after processing has finished.");
        OPTIONS.addOption(OPT_DATA_DIR, true, "The path where the downloaded zipped data files will be stored. If unspecified, the current directory where the program is being executed is used.");
        OPTIONS.addOption(OPT_SEND_REPORT, true, "If you wish the crawler to send a report, use this switch and provide a valid email Id");
        OPTIONS.addOption(OPT_XMLSERIALISER_PROP_FILE, true, "The path to the properties file that specifies the XML serialiser configuration.");
        OPTIONS.addOption(OPT_XMLVALIDATOR_PROP_FILE, true, "The path to the properties file that specifies the XML validator configuration.");
        OPTIONS.addOption(OPT_XMLVALIDATION_RESOURCES_PROP_FILE, true, "The path to the properties file that specifies the XML validation resources configuration.");
        OPTIONS.addOption(OPT_CONTEXT_PROP_FILE, true, "The path to the properties file that specifies the context builder configuration.");
        OPTIONS.addOption(OPT_CRAWLER_PROP_FILE, true, "The path to the properties file that specifies the Crawler configuration.");
    }

    // used when showing usage information, or help message
    private static final int NUM_CHARS_PER_ROW = 120;

    // error/success codes when parsing the command line
    private static final int SUCCESS = 0;
    private static final int INVALID_NUM_PARALLEL_DOWNLOADS = 1;
    private static final int INVALID_MAX_RETRIES = 2;
    private static final int INVALID_POOL_SIZE = 3;
    private static final int INVALID_PERIODIC_DELAY = 4;
    private static final int INVALID_DATA_DIR = 5;
    private static final int INVALID_EMAIL_ID = 6;
    private static final int INVALID_CRAWLER_PROP_FILE = 7;
    private static final int INVALID_XMLSERIALISER_PROP_FILE = 8;
    private static final int INVALID_XMLVALIDATOR_PROP_FILE = 9;
    private static final int INVALID_XMLVALIDATION_RESOURCES_PROP_FILE = 10;
    private static final int INVALID_CONTEXT_PROP_FILE = 11;

    // initialise application configuration using the default values
    private int poolSize = DEFAULT_POOLSIZE;
    private int numParallelDownloaders = DEFAULT_NUM_PARALLEL_DOWNLOADS;
    private int maxRetries = DEFAULT_MAX_RETRIES;
    private long periodicDelayInHours = DEFAULT_PERIODIC_DELAY_IN_HOURS;
    private static String dataDirectory = DEFAULT_DATA_DIR;
    private boolean requiresReport = false;
    private String emailId = null;

    // these allow specification of custom target database connection
    // properties, which, if valid, will override the default properties
    // defined in:
    //
    // * mysql.properties of the exportLibrary.xmlserialization project, and
    // * persistence.xml of the phenodcc-crawler-entities project
    //
    // this project inherits these properties from the above projects. the
    // first is used for storing data to phenodcc_raw database, and the second
    // is used for storing tracking data in phenodcc_tracker database.
    private String crawlerPropFile = null;
    private String xmlSerialiserPropFile = null;
    private String xmlValidatorPropFile = null;
    private String xmlValidationResourcesPropFile = null;
    private String contextPropFile = null;

    // application variables
    private final StringBuilder header = new StringBuilder();
    private SessionInitiator processInitiator;

    private void showHelp() {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(NUM_CHARS_PER_ROW, "\n\njava -jar program.jar", null, OPTIONS, null, true);
    }

    private TheApplication() {
        header.append("\nPhenoDCC: File Source Crawler");
        header.append("\nCopyright (c) 2013 Medical Research Council Harwell");
        header.append("\n(http://www.mousephenotype.org)\n\n");
    }

    public static void main(String[] args) {
        SingleInstance si = SingleInstance.getInstance();
        switch (si.check()) {
            case 0:
                LOGGER.debug("No crawler instance is currently running... will start a new instance");
                TheApplication a = new TheApplication();
                a.setup(args);
                a.run();
                break;
            case 1:
                LOGGER.warn("Failure to acquire lock '{}'...", si.getLockPath());
                LOGGER.warn("An instance of the crawler seems to be running...");
                LOGGER.warn("If you kill this instance, you must delete the lock file '{}'", si.getLockPath());
                break;
            case 2:
                LOGGER.warn("Corrupt lock file path '{}'...", si.getLockPath());
                LOGGER.warn("Please verify and delete the lock file path '{}'...", si.getLockPath());
                break;
            default:
                break;
        }
        si.shutdown();
    }

    private void setup(String[] args) {
        LOGGER.info(header.toString());
        if (parseArgs(args)) {
            SettingsManager sm = SettingsManager.getInstance();
            sm.printSettings();
            if (createRequiredDirectories()) {
                processInitiator = new SessionInitiator(dataDirectory, numParallelDownloaders, poolSize, maxRetries);
            } else {
                exit("Failed to create required directories", false);
            }
        } else {
            exit("Error parsing commandline arguments", true);
        }
    }

    private void run() {
        if (periodicDelayInHours > 0) {
            Timer timer = new Timer();
            timer.schedule(processInitiator, 0L, periodicDelayInHours * HOUR_TO_MILLISECS);
        } else {
            processInitiator.run();
            if (requiresReport) {
                sendReport();
            }
            LOGGER.info("Application will now exit...");
        }
    }

    private void cleanupAndExit(int code) {
        SingleInstance si = SingleInstance.getInstance();
        si.shutdown();
        System.exit(code);
    }

    private void exit(String message, boolean h) {
        LOGGER.error(message + "\nApplication will now exit...\n");
        if (h) {
            showHelp();
        }
        cleanupAndExit(1);
    }

    private boolean parseArgs(String[] args) {
        boolean parseResult = false;
        try {
            CommandLineParser parser = new PosixParser();
            CommandLine cmd = parser.parse(OPTIONS, args);
            if (cmd.hasOption(OPT_HELP)) {
                showHelp();
                cleanupAndExit(0);
            } else {
                parseResult = true;
                parseResult &= (getDataDirectory(cmd) == SUCCESS);
                parseResult &= (getNumParallelDownloads(cmd) == SUCCESS);
                parseResult &= (getPoolSize(cmd) == SUCCESS);
                parseResult &= (getMaxRetries(cmd) == SUCCESS);
                parseResult &= (getPeriodicDelay(cmd) == SUCCESS);
                parseResult &= (getSendReport(cmd) == SUCCESS);
                parseResult &= (getCrawlerPropFile(cmd) == SUCCESS);
                parseResult &= (getXmlSerialiserPropFile(cmd) == SUCCESS);
                parseResult &= (getXmlValidatorPropFile(cmd) == SUCCESS);
                parseResult &= (getXmlValidationResourcesPropFile(cmd) == SUCCESS);
                parseResult &= (getContextPropFile(cmd) == SUCCESS);
            }
        } catch (ParseException e) {
            LOGGER.error(e.getMessage());
        }
        return parseResult;
    }

    private int getNumParallelDownloads(CommandLine cmd) {
        int parseResult = SUCCESS;
        if (cmd.hasOption(OPT_NUM_PARALLEL_DOWNLOADS)) {
            numParallelDownloaders = Integer.parseInt(cmd.getOptionValue(OPT_NUM_PARALLEL_DOWNLOADS));
            if (numParallelDownloaders < MIN_NUM_PARALLEL_DOWNLOADS
                    || numParallelDownloaders > MAX_NUM_PARALLEL_DOWNLOADS) {
                LOGGER.error("The number of parallel downloads should be greater than {} and less than {}.",
                        MIN_NUM_PARALLEL_DOWNLOADS, MAX_NUM_PARALLEL_DOWNLOADS);
                parseResult = INVALID_NUM_PARALLEL_DOWNLOADS;
            }
        }
        return parseResult;
    }

    private int getMaxRetries(CommandLine cmd) {
        int parseResult = SUCCESS;
        if (cmd.hasOption(OPT_MAX_RETRIES)) {
            maxRetries = Integer.parseInt(cmd.getOptionValue(OPT_MAX_RETRIES));
            if (maxRetries < MIN_MAX_RETRIES || maxRetries > MAX_MAX_RETRIES) {
                LOGGER.error("The maximum number of download retries should be greater than {} and less than {}.",
                        MIN_MAX_RETRIES, MAX_MAX_RETRIES);
                parseResult = INVALID_MAX_RETRIES;
            }
        }
        return parseResult;
    }

    private int getPoolSize(CommandLine cmd) {
        int parseResult = SUCCESS;
        if (cmd.hasOption(OPT_POOL_SIZE)) {
            poolSize = Integer.parseInt(cmd.getOptionValue(OPT_POOL_SIZE));
            if (poolSize < MIN_POOLSIZE || poolSize > MAX_POOLSIZE) {
                LOGGER.error("The maximum size of the thread pool should be greater than {} and less than {}.",
                        MIN_POOLSIZE, MAX_POOLSIZE);
                parseResult = INVALID_POOL_SIZE;
            }
        }
        return parseResult;
    }

    private int getPeriodicDelay(CommandLine cmd) {
        int parseResult = SUCCESS;
        if (cmd.hasOption(OPT_PERIODIC_DELAY)) {
            periodicDelayInHours = Integer.parseInt(cmd.getOptionValue(OPT_PERIODIC_DELAY));
            if (periodicDelayInHours < MIN_PERIODIC_DELAY_IN_HOURS) {
                LOGGER.error("The periodic delay should be either {} (non-periodic), or a positive number of hours.", MIN_PERIODIC_DELAY_IN_HOURS);
                parseResult = INVALID_PERIODIC_DELAY;
            }
        }
        return parseResult;
    }

    private int getDataDirectory(CommandLine cmd) {
        int parseResult = SUCCESS;
        if (cmd.hasOption(OPT_DATA_DIR)) {
            dataDirectory = cmd.getOptionValue(OPT_DATA_DIR);
            if (dataDirectory == null || dataDirectory.isEmpty()) {
                LOGGER.error("The supplied data storage directory is invalid.");
                parseResult = INVALID_DATA_DIR;
            }
        }
        return parseResult;
    }

    private File getReadableFile(String path) {
        File f = new File(path);
        if (f.exists()) {
            if (f.isFile()) {
                if (f.canRead()) {
                    LOGGER.info("Will use supplied properties file '{}'.", path);
                } else {
                    LOGGER.error("The supplied properties file '{}' is unreadable.", path);
                    f = null;
                }
            } else {
                LOGGER.error("The supplied properties path '{}' is not a file.", path);
                f = null;
            }
        } else {
            LOGGER.error("The supplied properties path '{}' does not exists.", path);
            f = null;
        }
        return f;
    }

    private int getCrawlerPropFile(CommandLine cmd) {
        int parseResult = SUCCESS;
        if (cmd.hasOption(OPT_CRAWLER_PROP_FILE)) {
            crawlerPropFile = cmd.getOptionValue(OPT_CRAWLER_PROP_FILE);
            if (crawlerPropFile == null || crawlerPropFile.isEmpty()) {
                LOGGER.error("The supplied properties file path for Crawler configuration is invalid.");
                parseResult = INVALID_CRAWLER_PROP_FILE;
            } else {
                File f = getReadableFile(crawlerPropFile);
                if (f == null) {
                    parseResult = INVALID_CRAWLER_PROP_FILE;
                } else {
                    SettingsManager sm = SettingsManager.getInstance();
                    sm.setCrawlerPropPath(f.getAbsolutePath());
                    sm.loadCustomConfig(f);
                }
            }
        } else {
            LOGGER.error("Please supply a properties file that specifies the Crawler configuration properties.");
            parseResult = INVALID_CRAWLER_PROP_FILE;
        }
        return parseResult;
    }

    private int getXmlSerialiserPropFile(CommandLine cmd) {
        int parseResult = SUCCESS;
        if (cmd.hasOption(OPT_XMLSERIALISER_PROP_FILE)) {
            xmlSerialiserPropFile = cmd.getOptionValue(OPT_XMLSERIALISER_PROP_FILE);
            if (xmlSerialiserPropFile == null || xmlSerialiserPropFile.isEmpty()) {
                LOGGER.error("The supplied properties file path for XML serialiser configuration is invalid.");
                parseResult = INVALID_XMLSERIALISER_PROP_FILE;
            } else {
                File f = getReadableFile(xmlSerialiserPropFile);
                if (f == null) {
                    parseResult = INVALID_XMLSERIALISER_PROP_FILE;
                } else {
                    SettingsManager sm = SettingsManager.getInstance();
                    sm.setXmlSerialiserPropPath(f.getAbsolutePath());
                }
            }
        }
        return parseResult;
    }

    private int getXmlValidatorPropFile(CommandLine cmd) {
        int parseResult = SUCCESS;
        if (cmd.hasOption(OPT_XMLVALIDATOR_PROP_FILE)) {
            xmlValidatorPropFile = cmd.getOptionValue(OPT_XMLVALIDATOR_PROP_FILE);
            if (xmlValidatorPropFile == null || xmlValidatorPropFile.isEmpty()) {
                LOGGER.error("The supplied properties file path for XML validator configuration is invalid.");
                parseResult = INVALID_XMLVALIDATOR_PROP_FILE;
            } else {
                File f = getReadableFile(xmlValidatorPropFile);
                if (f == null) {
                    parseResult = INVALID_XMLVALIDATOR_PROP_FILE;
                } else {
                    SettingsManager sm = SettingsManager.getInstance();
                    sm.setXmlValidatorPropPath(f.getAbsolutePath());
                }
            }
        }
        return parseResult;
    }

    private int getXmlValidationResourcesPropFile(CommandLine cmd) {
        int parseResult = SUCCESS;
        if (cmd.hasOption(OPT_XMLVALIDATION_RESOURCES_PROP_FILE)) {
            xmlValidationResourcesPropFile = cmd.getOptionValue(OPT_XMLVALIDATION_RESOURCES_PROP_FILE);
            if (xmlValidationResourcesPropFile == null || xmlValidationResourcesPropFile.isEmpty()) {
                LOGGER.error("The supplied properties file path for XML validation resources configuration is invalid.");
                parseResult = INVALID_XMLVALIDATION_RESOURCES_PROP_FILE;
            } else {
                File f = getReadableFile(xmlValidationResourcesPropFile);
                if (f == null) {
                    parseResult = INVALID_XMLVALIDATION_RESOURCES_PROP_FILE;
                } else {
                    SettingsManager sm = SettingsManager.getInstance();
                    sm.setXmlValidationResourcesPropPath(f.getAbsolutePath());
                }
            }
        }
        return parseResult;
    }

    private int getContextPropFile(CommandLine cmd) {
        int parseResult = SUCCESS;
        if (cmd.hasOption(OPT_CONTEXT_PROP_FILE)) {
            contextPropFile = cmd.getOptionValue(OPT_CONTEXT_PROP_FILE);
            if (contextPropFile == null || contextPropFile.isEmpty()) {
                LOGGER.error("The supplied properties file path for context builder configuration is invalid.");
                parseResult = INVALID_CONTEXT_PROP_FILE;
            } else {
                File f = getReadableFile(contextPropFile);
                if (f == null) {
                    parseResult = INVALID_CONTEXT_PROP_FILE;
                } else {
                    SettingsManager sm = SettingsManager.getInstance();
                    sm.setContextPropPath(f.getAbsolutePath());
                }
            }
        }
        return parseResult;
    }

    private int getSendReport(CommandLine cmd) {
        int parseResult = SUCCESS;
        if (cmd.hasOption(OPT_SEND_REPORT)) {
            requiresReport = true;
            emailId = cmd.getOptionValue(OPT_SEND_REPORT);
            if (emailId == null || emailId.isEmpty()) {
                LOGGER.error("The supplied email Id is invalid.");
                parseResult = INVALID_EMAIL_ID;
            }
        }
        return parseResult;
    }

    private boolean createRequiredDirectories() {
        boolean returnValue = false;
        if (createDirectory(dataDirectory + "/add", LOGGER)
                && createDirectory(dataDirectory + "/edit", LOGGER)
                && createDirectory(dataDirectory + "/delete", LOGGER)) {
            returnValue = true;
        }
        return returnValue;
    }

    public static boolean createDirectory(String contentsPath, Logger logger) {
        boolean returnValue = false;
        File f = new File(contentsPath);
        if (f.exists()) {
            if (f.isDirectory()) {
                if (f.canRead()) {
                    if (f.canWrite()) {
                        returnValue = true;
                    } else {
                        logger.error("Cannot write to directory '{}'", contentsPath);
                    }
                } else {
                    logger.error("Cannot read the directory '{}'", contentsPath);
                }
            } else {
                logger.error("Path '{}' is not a directory", contentsPath);
            }
        } else {
            logger.info("Path '{}' does not exists; will try to create", contentsPath);
            if (f.mkdirs()) {
                returnValue = true;
            } else {
                logger.error("Failed to create directory '{}'", contentsPath);
            }
        }
        return returnValue;
    }

    private void sendReport() {
        LOGGER.info("Send session report to '{}'...", emailId);
    }
}


text:
package com.gridlayout.samples;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.gridlayout.GridLayout;

public class GridLayoutVisibilityActivity extends Activity {

    private GridLayout mGridLayout;
    private TextView mTextView1;
    private TextView mTextView2;

    int cycle = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_gridlayout_visibility);

        mGridLayout = (GridLayout) findViewById(R.id.grid_layout);
        mTextView1 = (TextView) findViewById(R.id.textview1);
        mTextView2 = (TextView) findViewById(R.id.textview2);

        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                if (cycle == 0) {
                    mTextView1.setVisibility(View.GONE);
                    mGridLayout.notifyChildVisibilityChanged();
                    cycle++;
                }
                else if (cycle == 1) {
                    mTextView2.setVisibility(View.GONE);
                    mGridLayout.notifyChildVisibilityChanged();
                    cycle++;
                }
                else {
                    mTextView1.setVisibility(View.VISIBLE);
                    mTextView2.setVisibility(View.VISIBLE);
                    mGridLayout.notifyChildVisibilityChanged();
                    cycle = 0;
                }
            }
        });
    }
}


text:
using Bonobo.Git.Server.Configuration;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.DirectoryServices.AccountManagement;
using System.DirectoryServices.ActiveDirectory;
using Serilog;

namespace Bonobo.Git.Server.Helpers
{
    public static class ADHelper
    {
        /// <summary>
        /// There are various sources of domains which we need to check
        /// Try to lazy-enumerate this, so that expensive functions aren't called if they're not necessary
        /// </summary>
        /// <param name="username">The full user name (not stripped, should contain domain if available)</param>
        /// <returns>An Enumerable of domains which can be tried</returns>
        private static IEnumerable<Domain> GetAllDomainPossibilities(string username = "")
        {
            //Skip checking username if none is supplied.
            if(!string.IsNullOrEmpty(username))
            {
                // First we try for the domain in the username
                var parsedDomainName = username.GetDomain();
                var domainFromUsername = GetDomain(parsedDomainName);
                if (domainFromUsername != null)
                {
                    yield return domainFromUsername;
                }
            }

            // The we try the domain in web.config, if there is one
            string defaultDomainName = ConfigurationManager.AppSettings["ActiveDirectoryDefaultDomain"];
            if (!string.IsNullOrEmpty(defaultDomainName))
            {
                var domainFromConfig = GetDomain(defaultDomainName);
                if (domainFromConfig != null)
                {
                    yield return domainFromConfig;
                }
            }

            // Finally try the global catalogue
            GlobalCatalogCollection gcc = Forest.GetCurrentForest().FindAllGlobalCatalogs();
            Log.Information("Searching in {count} global catalogs", gcc.Count);

            // Else try all global catalogs in the current forest.
            foreach (GlobalCatalog gc in gcc)
            {
                Log.Information("Trying GlobalCatalogue {globalCatalog} domain {domain}", gc.Name, gc.Domain.Name);
                yield return gc.Domain;
            }
        }

        /// <summary>
        /// Validates the user against Active directory - will try the domain that are part of the username if present
        /// Alternatively it tries all domains in the current forest.
        /// </summary>
        /// <param name="username">Username with or without domain</param>
        /// <param name="password"></param>
        /// <returns>True on successfull validation</returns>
        public static bool ValidateUser(string username, string password)
        {
            Log.Information("AD: Validating user {UserName}", username);

            string strippedUsername = username.StripDomain();

            foreach (var domain in GetAllDomainPossibilities(username))
            {
                Log.Information("AD: Validating stripped username {StrippedUserName} - against domain {DomainName}",
                    strippedUsername, domain.Name);

                if (ValidateUser(domain, strippedUsername, password))
                {
                    return true;
                }
            }

            Log.Information("AD: Failed to validate user {UserName}", username);

            return false;
        }

        private static bool ValidateUser(Domain domain, string username, string password)
        {
            try
            {
                Log.Information("AD: Validating {UserName} in domain {DomainName}", username, domain.Name);

                using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain.Name))
                {
                    if (pc.ValidateCredentials(username, password, ContextOptions.Negotiate))
                    {
                        Log.Information("AD: Success validating {UserName} in domain {DomainName}", username, domain.Name);
                        return true;
                    }
                    Log.Warning("AD: Validating {UserName} in domain {DomainName} failed", username, domain.Name);
                }
            }
            catch (Exception exp)
            {
                Log.Error(exp, "AD Validate user {username}", username);
            }
            return false;
        }

        private static Domain GetDomain(string parsedDomainName)
        {
            Log.Verbose("ADHelp: Creating directory context with domain: {DomainName}", parsedDomainName);

            Domain domain = null;

            try
            {

                var dc = new DirectoryContext(DirectoryContextType.Domain, parsedDomainName);

                domain = Domain.GetDomain(dc);
            }
            catch (Exception exp)
            {
                Log.Error(exp, "Failed to create Directory context for domain {domain}.", parsedDomainName);
            }

            return domain;
        }
        /// <summary>
        /// Used to get the UserPrincpal based on username - will try the domain that are part of the username if present
        /// </summary>
        /// <param name="username">UPN or SamAccountName</param>
        /// <returns>Userprincipal if found else null</returns>
        public static UserPrincipal GetUserPrincipal(string username)
        {
            var parsedDomainName = username.GetDomain();
            string strippedUsername = username.StripDomain();

            Log.Verbose("GetUserPrincipal: username {UserName}, domain {DomainName}, stripped {StrippedUserName}", username, parsedDomainName, strippedUsername);

            foreach (var domain in GetAllDomainPossibilities(username))
            {
                var user = GetUserPrincipal(domain, strippedUsername);
                if (user != null)
                    return user;
                Log.Warning("Null principal in domain: {DomainName}, user: {UserName}", domain.Name,
                    strippedUsername);
            }

            return null;
        }

        private static UserPrincipal GetUserPrincipal(Domain domain, string username)
        {
            try
            {
                using (var pc = new PrincipalContext(ContextType.Domain, domain.Name))
                {
                    return UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName,username);
                }
            }
            catch (Exception exp)
            {
                Log.Error(exp, "GetUserPrincipal in domain: {DomainName}, user: {UserName}", domain.Name, username);
            }
            return null;
        }
        /// <summary>
        /// Used to get the UserPrinpal from a GUID
        /// </summary>
        /// <param name="id">The GUID of user</param>
        /// <returns>The Userprincipal if found, else null</returns>
        public static UserPrincipal GetUserPrincipal(Guid id)
        {
            foreach (Domain domain in GetAllDomainPossibilities())
            {
                try
                {
                    using (var pc = new PrincipalContext(ContextType.Domain, domain.Name))
                    {
                        Log.Information("Looking for user with guid {guid} in domain {domain}", id.ToString(), domain.Name);

                        var user = UserPrincipal.FindByIdentity(pc, IdentityType.Guid, id.ToString());
                        if (user != null)
                            return user;
                    }
                }
                catch (Exception exp)
                {
                    Log.Error(exp, "AD: Failed to find user with guid {GUID}", id.ToString());
                    // let it fail
                }
            }

            return null;
        }
        /// <summary>
        /// Used to get the members group defined in web.config
        /// Returns the principal context to be able to do further processing on the group, ie fetch users etc.
        /// If the Principal context is disposed, it cannot query any more.
        /// </summary>
        /// <param name="group">The AD membergroup</param>
        /// <returns>Principal context on which the membersgroup was found</returns>
        public static PrincipalContext GetMembersGroup(out GroupPrincipal group)
        {
            return GetPrincipalGroup(ActiveDirectorySettings.MemberGroupName, out group);
        }
        /// <summary>
        /// Gets a principal group by name
        /// Returns the principal context to be able to do further processing on the group, ie fetch users etc.
        /// If the Principal context is disposed, it cannot query any more.
        /// </summary>
        /// <param name="name">The group to search for</param>
        /// <param name="group">The group found</param>
        /// <returns>Principal context on which the group was found.</returns>
        public static PrincipalContext GetPrincipalGroup(string name, out GroupPrincipal group)
        {
            foreach (Domain domain in GetAllDomainPossibilities())
            {
                Log.Information("Searching for group {name} in domain {domain}", name, domain.Name);

                try
                {
                    var pc = new PrincipalContext(ContextType.Domain, domain.Name);
                    group = GroupPrincipal.FindByIdentity(pc, IdentityType.Name, name);
                    if (group != null)
                        return pc;
                }
                catch (Exception exp)
                {
                    Log.Error(exp, "GetPrincipal Group with name: " + name);
                    // let it fail
                }
            }
            throw new ArgumentException("Could not find principal group: " + name);
        }
    }
}


text:
package it.unibz.krdb.sql;

import it.unibz.krdb.sql.api.Attribute;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class TableDefinition extends DataDefinition {

	private static final long serialVersionUID = 1L;

	public TableDefinition(String name) {
		super(name);
	}

	public List<Attribute> getPrimaryKeys() {
		List<Attribute> primaryKeys = new ArrayList<>();
		for (Attribute attr : getAttributes()) {
			if (attr.isPrimaryKey())
				primaryKeys.add(attr);
		}
		return primaryKeys;
	}

	public Map<String, List<Attribute>> getForeignKeys() {
		Map<String, List<Attribute>> foreignKeys = new HashMap<>();
		for (Attribute attr : getAttributes()) {
			if (attr.isForeignKey()) {
				String fkName = attr.getReference().getReferenceName();
				List<Attribute> fkAttributes = foreignKeys.get(fkName);
				if (fkAttributes == null) {
					fkAttributes = new ArrayList<>();
					foreignKeys.put(fkName, fkAttributes);
				}
				fkAttributes.add(attr);
			}
		}
		return foreignKeys;
	}

	@Override
	public String toString() {
		StringBuilder bf = new StringBuilder();
		bf.append(getName());
		bf.append("[");
		boolean comma = false;
		for (Attribute att : getAttributes()) {
			if (comma)
				bf.append(",");

			bf.append(att);
			if (att.isPrimaryKey())
				bf.append(":PK");

			if (att.isForeignKey()) {
				bf.append(":FK:");
				bf.append(String.format("%s(%s)",
						att.getReference().getTableReference(),
						att.getReference().getColumnReference()));
			}
			comma = true;
		}
		bf.append("]");
		return bf.toString();
	}
}


text:
"""
    this is the code to accompany the Lesson 1 (Naive Bayes) mini-project

    use a Naive Bayes Classifier to identify emails by their authors

    authors and labels:
    Sara has label 0
    Chris has label 1

"""

import sys
import os
from time import time
sys.path.append("/Users/selvaprabhakaran/Documents/work/pythonwork/python_ML_git/ud120-projects/tools/")
from email_preprocess import preprocess

# Set cwd
os.chdir("/Users/selvaprabhakaran/Documents/work/pythonwork/python_ML_git/ud120-projects/tools/")

### features_train and features_test are the features for the training
### and testing datasets, respectively
### labels_train and labels_test are the corresponding item labels
features_train, features_test, labels_train, labels_test = preprocess()

#########################################################
### your code goes here ###
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score
clf = GaussianNB()

t0 = time()
clf.fit(features_train, labels_train)
print "Training Time: ", time()-t0, " secs"

t0 = time()
predicteds = clf.predict(features_test)
print "Prediction Time: ", time()-t0, " secs"

# Calc accuracy
print "Accuracy score: ", accuracy_score(labels_test, predicteds), " %"
#########################################################