text:
from __future__ import unicode_literals, absolute_import
import os
import re
import sys
import struct
import getopt
import platform
import threading
import webbrowser

import ardublocklyserver.server
import ardublocklyserver.compilersettings

def open_browser(open_file):
    """
    Start a browser in a separate thread after waiting for half a second.
    """
    def _open_browser():
        webbrowser.get().open('http://localhost:%s/%s' %
                              (ardublocklyserver.server.PORT, open_file))

    thread = threading.Timer(0.5, _open_browser)
    thread.start()

def find_ardublockly_dir(search_path):
    """
    Navigates within each node of a given path and tries to find the Ardublockly
    project root directory. It assumes that the project root with have an folder
    name ardublockly with an index.html file inside.
    This function is required because this script can end up in executable form
    in different locations of the project folder, and a literal relative path
    should not be assumed.

    :param search_path: Path in which to find the Ardublockly root project
                      folder.
    :return: Path to the Ardublockly root folder.
             If not found returns None.
    """
    path_to_navigate = os.path.normpath(search_path)
    # Navigate through each path node starting at the bottom until there are
    # no folders left
    while path_to_navigate:
        # Check if file /ardublokly/index.html exists within current path
        if os.path.isfile(
                os.path.join(path_to_navigate, 'ardublockly', 'index.html')):
            # Found the right folder, return it
            return path_to_navigate
        path_to_navigate = os.path.dirname(path_to_navigate)

    # The right folder wasn't found, so return input path
    return None

def parsing_cl_args():
    """
    Processes the command line arguments. Arguments supported:
    -h / --help
    -s / --serverroot <working directory>

    :return: Dictionary with available options(keys) and value(value).
    """
    # Set option defaults
    launch_browser = True
    server_root = None
    find_project_root = False

    if len(sys.argv) == 1:
        print("No command line arguments found.")
    else:
        try:
            opts, args = getopt.getopt(
                sys.argv[1:],
                'hs:bf',
                ['help', 'serverroot=', 'nobrowser', 'findprojectroot'])
        except getopt.GetoptError as e:
            print('There was a problem parsing the command line arguments:')
            print('\t%s' % e)
            sys.exit(1)

        for opt, arg in opts:
            if opt in ('-h', '--help'):
                print('Help flag parsed, these are the current options:\n')
                print('\t-s <folder>\tSets the server working directory.')
                print('\t-b\t\tSuppresses opening the local browser.')
                sys.exit(0)
            if opt in ('-s', '--serverroot'):
                # Windows only issue: In BlocklyRequestHandler, if chdir is fed
                # an 'incorrect' path like 'C:' instead of 'C:\' or C:/' it
                # fails silently maintaining the current working directory.
                # Use regular expressions to catch this corner case.
                if re.match("^[a-zA-Z]:$", arg):
                    print('The windows drive letter needs to end in a slash, ' +
                          'eg. %s\\' % arg)
                    sys.exit(1)
                # Check if the value is a valid directory
                arg = os.path.normpath(arg)
                if os.path.isdir(arg):
                    server_root = arg
                    print ('Parsed "%s" flag with "%s" value.' % (opt, arg))
                else:
                    print('Invalid directory "' + arg + '".')
                    sys.exit(1)
            elif opt in ('-b', '--nobrowser'):
                launch_browser = False
                print ('Parsed "%s" flag. No browser will be opened.' % opt)
            elif opt in ('-f', '--findprojectroot'):
                find_project_root = True
                print ('Parsed "%s" flag. The ardublockly project root will be '
                       'set as the server root directory.' % opt)
            else:
                print('Flag ' + opt + ' not recognised.')

    return find_project_root, launch_browser, server_root

def main():
    """
    Initialises the Settings singleton, resolves paths, and starts the server.
    """
    print('Running Python %s (%s bit) on %s' % (platform.python_version(),
          (struct.calcsize('P') * 8), platform.platform()))

    print('\n\n======= Parsing Command line arguments =======\n')
    find_project_root, launch_browser, server_root = parsing_cl_args()

    print('\n\n======= Resolving server and project paths =======\n')
    # Based on command line options, set the server root to the ardublockly
    # project root directory, a directory specified in the arguments, or by
    # default to the project root directory.
    this_file_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
    ardublockly_root_dir = find_ardublockly_dir(this_file_dir)
    if ardublockly_root_dir is None:
        print('The Ardublockly project root folder could not be found within '
              'the %s directory !' % this_file_dir)
        sys.exit(1)
    print("Ardublockly root directory: %s" % ardublockly_root_dir)

    if find_project_root is True or server_root is None:
        server_root = ardublockly_root_dir
    else:
        # Arguments have set a server root, and to not find ardublockly dir
        if not os.path.commonprefix([server_root, ardublockly_root_dir]):
            print('The Ardublockly project folder needs to be accessible from '
                  'the server root directory !')
    print("Selected server root: %s" % server_root)

    print('\n\n======= Loading Settings =======')
    # ServerCompilerSettings is a singleton, no need to save instance
    ardublocklyserver.compilersettings.ServerCompilerSettings(
        ardublockly_root_dir)

    print('\n\n======= Starting Server =======\n')
    if launch_browser:
        # Find the relative path from server root to ardublockly html
        ardublockly_html_dir = os.path.join(ardublockly_root_dir, 'ardublockly')
        relative_path = os.path.relpath(ardublockly_html_dir, server_root)
        print("Ardublockly page relative path from server root: %s" %
              relative_path)
        open_browser(relative_path)

    ardublocklyserver.server.start_server(server_root)

if __name__ == '__main__':
    main()


text:
require "test_helper"
require "database/setup"
require "active_support/testing/method_call_assertions"

class ActiveStorage::OneAttachedTest < ActiveSupport::TestCase
  include ActiveJob::TestHelper
  include ActiveSupport::Testing::MethodCallAssertions

  setup do
    @user = User.create!(name: "Josh")
  end

  teardown do
    ActiveStorage::Blob.all.each(&:delete)
  end

  test "attaching an existing blob to an existing record" do
    @user.avatar.attach create_blob(filename: "funky.jpg")
    assert_equal "funky.jpg", @user.avatar.filename.to_s

    assert_not_nil @user.avatar_attachment
    assert_not_nil @user.avatar_blob
  end

  test "attaching an existing blob from a signed ID to an existing record" do
    @user.avatar.attach create_blob(filename: "funky.jpg").signed_id
    assert_equal "funky.jpg", @user.avatar.filename.to_s
  end

  test "attaching an existing blob from a signed ID passes record" do
    blob = create_blob(filename: "funky.jpg")
    arguments = [blob.signed_id, record: @user]
    assert_called_with(ActiveStorage::Blob, :find_signed!, arguments, returns: blob) do
      @user.avatar.attach blob.signed_id
    end
  end

  test "attaching a new blob from a Hash to an existing record" do
    @user.avatar.attach io: StringIO.new("STUFF"), filename: "town.jpg", content_type: "image/jpeg"
    assert_equal "town.jpg", @user.avatar.filename.to_s
  end

  test "attaching a new blob from a Hash to an existing record passes record" do
    hash = { io: StringIO.new("STUFF"), filename: "town.jpg", content_type: "image/jpeg" }
    blob = ActiveStorage::Blob.build_after_unfurling(**hash)
    arguments = [hash.merge(record: @user, service_name: nil)]
    assert_called_with(ActiveStorage::Blob, :build_after_unfurling, arguments, returns: blob) do
      @user.avatar.attach hash
    end
  end

  test "attaching a new blob from an uploaded file to an existing record" do
    @user.avatar.attach fixture_file_upload("racecar.jpg")
    assert_equal "racecar.jpg", @user.avatar.filename.to_s
  end

  test "attaching a new blob from an uploaded file to an existing record passes record" do
    upload = fixture_file_upload("racecar.jpg")
    def upload.open
      @io ||= StringIO.new("")
    end
    arguments = { io: upload.open, filename: upload.original_filename, content_type: upload.content_type, record: @user, service_name: nil }
    blob = ActiveStorage::Blob.build_after_unfurling(**arguments)
    assert_called_with(ActiveStorage::Blob, :build_after_unfurling, [arguments], returns: blob) do
      @user.avatar.attach upload
    end
  end

  test "attaching a blob to a record returns the attachment" do
    avatar = @user.avatar.attach create_blob(filename: "funky.jpg")
    assert_instance_of ActiveStorage::Attached::One, avatar
    assert_equal avatar.key, @user.avatar.key
    assert_equal avatar.name.to_s, @user.avatar.name.to_s
    assert_equal avatar.filename.to_s, @user.avatar.filename.to_s
  end

  test "attaching an existing blob to an existing, changed record" do
    @user.name = "Tina"
    assert @user.changed?

    @user.avatar.attach create_blob(filename: "funky.jpg")
    assert_equal "funky.jpg", @user.avatar.filename.to_s
    assert_not @user.avatar.persisted?
    assert @user.will_save_change_to_name?

    @user.save!
    assert_equal "funky.jpg", @user.reload.avatar.filename.to_s
  end

  test "attaching an existing blob from a signed ID to an existing, changed record" do
    @user.name = "Tina"
    assert @user.changed?

    @user.avatar.attach create_blob(filename: "funky.jpg").signed_id
    assert_equal "funky.jpg", @user.avatar.filename.to_s
    assert_not @user.avatar.persisted?
    assert @user.will_save_change_to_name?

    @user.save!
    assert_equal "funky.jpg", @user.reload.avatar.filename.to_s
  end

  test "attaching a new blob from a Hash to an existing, changed record" do
    @user.name = "Tina"
    assert @user.changed?

    @user.avatar.attach io: StringIO.new("STUFF"), filename: "town.jpg", content_type: "image/jpeg"
    assert_equal "town.jpg", @user.avatar.filename.to_s
    assert_not @user.avatar.persisted?
    assert @user.will_save_change_to_name?

    @user.save!
    assert_equal "town.jpg", @user.reload.avatar.filename.to_s
  end

  test "attaching a new blob from an uploaded file to an existing, changed record" do
    @user.name = "Tina"
    assert @user.changed?

    @user.avatar.attach fixture_file_upload("racecar.jpg")
    assert_equal "racecar.jpg", @user.avatar.filename.to_s
    assert_not @user.avatar.persisted?
    assert @user.will_save_change_to_name?

    @user.save!
    assert_equal "racecar.jpg", @user.reload.avatar.filename.to_s
  end

  test "updating an existing record to attach an existing blob" do
    @user.update! avatar: create_blob(filename: "funky.jpg")
    assert_equal "funky.jpg", @user.avatar.filename.to_s
  end

  test "updating an existing record to attach an existing blob from a signed ID" do
    @user.update! avatar: create_blob(filename: "funky.jpg").signed_id
    assert_equal "funky.jpg", @user.avatar.filename.to_s
  end

  test "successfully updating an existing record to attach a new blob from an uploaded file" do
    @user.avatar = fixture_file_upload("racecar.jpg")
    assert_equal "racecar.jpg", @user.avatar.filename.to_s
    assert_not ActiveStorage::Blob.service.exist?(@user.avatar.key)

    @user.save!
    assert ActiveStorage::Blob.service.exist?(@user.avatar.key)
  end

  test "unsuccessfully updating an existing record to attach a new blob from an uploaded file" do
    assert_not @user.update(name: "", avatar: fixture_file_upload("racecar.jpg"))
    assert_equal "racecar.jpg", @user.avatar.filename.to_s
    assert_not ActiveStorage::Blob.service.exist?(@user.avatar.key)
  end

  test "successfully replacing an existing, dependent attachment on an existing record" do
    create_blob(filename: "funky.jpg").tap do |old_blob|
      @user.avatar.attach old_blob

      perform_enqueued_jobs do
        @user.avatar.attach create_blob(filename: "town.jpg")
      end

      assert_equal "town.jpg", @user.avatar.filename.to_s
      assert_not ActiveStorage::Blob.exists?(old_blob.id)
      assert_not ActiveStorage::Blob.service.exist?(old_blob.key)
    end
  end

  test "replacing an existing, independent attachment on an existing record" do
    @user.cover_photo.attach create_blob(filename: "funky.jpg")

    assert_no_enqueued_jobs only: ActiveStorage::PurgeJob do
      @user.cover_photo.attach create_blob(filename: "town.jpg")
    end

    assert_equal "town.jpg", @user.cover_photo.filename.to_s
  end

  test "replacing an attached blob on an existing record with itself" do
    create_blob(filename: "funky.jpg").tap do |blob|
      @user.avatar.attach blob

      assert_no_changes -> { @user.reload.avatar_attachment.id } do
        assert_no_enqueued_jobs do
          @user.avatar.attach blob
        end
      end

      assert_equal "funky.jpg", @user.avatar.filename.to_s
      assert ActiveStorage::Blob.service.exist?(@user.avatar.key)
    end
  end

  test "successfully updating an existing record to replace an existing, dependent attachment" do
    create_blob(filename: "funky.jpg").tap do |old_blob|
      @user.avatar.attach old_blob

      perform_enqueued_jobs do
        @user.update! avatar: create_blob(filename: "town.jpg")
      end

      assert_equal "town.jpg", @user.avatar.filename.to_s
      assert_not ActiveStorage::Blob.exists?(old_blob.id)
      assert_not ActiveStorage::Blob.service.exist?(old_blob.key)
    end
  end

  test "successfully updating an existing record to replace an existing, independent attachment" do
    @user.cover_photo.attach create_blob(filename: "funky.jpg")

    assert_no_enqueued_jobs only: ActiveStorage::PurgeJob do
      @user.update! cover_photo: create_blob(filename: "town.jpg")
    end

    assert_equal "town.jpg", @user.cover_photo.filename.to_s
  end

  test "unsuccessfully updating an existing record to replace an existing attachment" do
    @user.avatar.attach create_blob(filename: "funky.jpg")

    assert_no_enqueued_jobs do
      assert_not @user.update(name: "", avatar: fixture_file_upload("racecar.jpg"))
    end

    assert_equal "racecar.jpg", @user.avatar.filename.to_s
    assert_not ActiveStorage::Blob.service.exist?(@user.avatar.key)
  end

  test "updating an existing record to replace an attached blob with itself" do
    create_blob(filename: "funky.jpg").tap do |blob|
      @user.avatar.attach blob

      assert_no_enqueued_jobs do
        assert_no_changes -> { @user.reload.avatar_attachment.id } do
          @user.update! avatar: blob
        end
      end
    end
  end

  test "removing a dependent attachment from an existing record" do
    create_blob(filename: "funky.jpg").tap do |blob|
      @user.avatar.attach blob

      assert_enqueued_with job: ActiveStorage::PurgeJob, args: [ blob ] do
        @user.avatar.attach nil
      end

      assert_not @user.avatar.attached?
    end
  end

  test "removing an independent attachment from an existing record" do
    create_blob(filename: "funky.jpg").tap do |blob|
      @user.cover_photo.attach blob

      assert_no_enqueued_jobs only: ActiveStorage::PurgeJob do
        @user.cover_photo.attach nil
      end

      assert_not @user.cover_photo.attached?
    end
  end

  test "updating an existing record to remove a dependent attachment" do
    create_blob(filename: "funky.jpg").tap do |blob|
      @user.avatar.attach blob

      assert_enqueued_with job: ActiveStorage::PurgeJob, args: [ blob ] do
        @user.update! avatar: nil
      end

      assert_not @user.avatar.attached?
    end
  end

  test "updating an existing record to remove an independent attachment" do
    create_blob(filename: "funky.jpg").tap do |blob|
      @user.cover_photo.attach blob

      assert_no_enqueued_jobs only: ActiveStorage::PurgeJob do
        @user.update! cover_photo: nil
      end

      assert_not @user.cover_photo.attached?
    end
  end

  test "analyzing a new blob from an uploaded file after attaching it to an existing record" do
    perform_enqueued_jobs do
      @user.avatar.attach fixture_file_upload("racecar.jpg")
    end

    assert @user.avatar.reload.analyzed?
    assert_equal 4104, @user.avatar.metadata[:width]
    assert_equal 2736, @user.avatar.metadata[:height]
  end

  test "analyzing a new blob from an uploaded file after attaching it to an existing record via update" do
    perform_enqueued_jobs do
      @user.update! avatar: fixture_file_upload("racecar.jpg")
    end

    assert @user.avatar.reload.analyzed?
    assert_equal 4104, @user.avatar.metadata[:width]
    assert_equal 2736, @user.avatar.metadata[:height]
  end

  test "analyzing a directly-uploaded blob after attaching it to an existing record" do
    perform_enqueued_jobs do
      @user.avatar.attach directly_upload_file_blob(filename: "racecar.jpg")
    end

    assert @user.avatar.reload.analyzed?
    assert_equal 4104, @user.avatar.metadata[:width]
    assert_equal 2736, @user.avatar.metadata[:height]
  end

  test "analyzing a directly-uploaded blob after attaching it to an existing record via updates" do
    perform_enqueued_jobs do
      @user.update! avatar: directly_upload_file_blob(filename: "racecar.jpg")
    end

    assert @user.avatar.reload.analyzed?
    assert_equal 4104, @user.avatar.metadata[:width]
    assert_equal 2736, @user.avatar.metadata[:height]
  end

  test "creating an attachment as part of an autosave association through nested attributes" do
    group = Group.create!(users_attributes: [{ name: "John", avatar: { io: StringIO.new("STUFF"), filename: "town.jpg", content_type: "image/jpeg" } }])
    group.save!
    new_user = User.find_by(name: "John")
    assert new_user.avatar.attached?
  end

  test "updating an attachment as part of an autosave association" do
    group = Group.create!(users: [@user])
    @user.avatar = fixture_file_upload("racecar.jpg")
    group.save!
    @user.reload
    assert @user.avatar.attached?
  end

  test "attaching an existing blob to a new record" do
    User.new(name: "Jason").tap do |user|
      user.avatar.attach create_blob(filename: "funky.jpg")
      assert user.new_record?
      assert_equal "funky.jpg", user.avatar.filename.to_s

      user.save!
      assert_equal "funky.jpg", user.reload.avatar.filename.to_s
    end
  end

  test "attaching an existing blob from a signed ID to a new record" do
    User.new(name: "Jason").tap do |user|
      user.avatar.attach create_blob(filename: "funky.jpg").signed_id
      assert user.new_record?
      assert_equal "funky.jpg", user.avatar.filename.to_s

      user.save!
      assert_equal "funky.jpg", user.reload.avatar.filename.to_s
    end
  end

  test "attaching a new blob from a Hash to a new record" do
    User.new(name: "Jason").tap do |user|
      user.avatar.attach io: StringIO.new("STUFF"), filename: "town.jpg", content_type: "image/jpeg"
      assert user.new_record?
      assert user.avatar.attachment.new_record?
      assert user.avatar.blob.new_record?
      assert_equal "town.jpg", user.avatar.filename.to_s
      assert_not ActiveStorage::Blob.service.exist?(user.avatar.key)

      user.save!
      assert user.avatar.attachment.persisted?
      assert user.avatar.blob.persisted?
      assert_equal "town.jpg", user.reload.avatar.filename.to_s
      assert ActiveStorage::Blob.service.exist?(user.avatar.key)
    end
  end

  test "attaching a new blob from an uploaded file to a new record" do
    User.new(name: "Jason").tap do |user|
      user.avatar.attach fixture_file_upload("racecar.jpg")
      assert user.new_record?
      assert user.avatar.attachment.new_record?
      assert user.avatar.blob.new_record?
      assert_equal "racecar.jpg", user.avatar.filename.to_s
      assert_not ActiveStorage::Blob.service.exist?(user.avatar.key)

      user.save!
      assert user.avatar.attachment.persisted?
      assert user.avatar.blob.persisted?
      assert_equal "racecar.jpg", user.reload.avatar.filename.to_s
      assert ActiveStorage::Blob.service.exist?(user.avatar.key)
    end
  end

  test "creating a record with an existing blob attached" do
    user = User.create!(name: "Jason", avatar: create_blob(filename: "funky.jpg"))
    assert_equal "funky.jpg", user.reload.avatar.filename.to_s
  end

  test "creating a record with an existing blob from a signed ID attached" do
    user = User.create!(name: "Jason", avatar: create_blob(filename: "funky.jpg").signed_id)
    assert_equal "funky.jpg", user.reload.avatar.filename.to_s
  end

  test "creating a record with a new blob from an uploaded file attached" do
    User.new(name: "Jason", avatar: fixture_file_upload("racecar.jpg")).tap do |user|
      assert user.new_record?
      assert user.avatar.attachment.new_record?
      assert user.avatar.blob.new_record?
      assert_equal "racecar.jpg", user.avatar.filename.to_s
      assert_not ActiveStorage::Blob.service.exist?(user.avatar.key)

      user.save!
      assert_equal "racecar.jpg", user.reload.avatar.filename.to_s
    end
  end

  test "creating a record with an unexpected object attached" do
    error = assert_raises(ArgumentError) { User.create!(name: "Jason", avatar: :foo) }
    assert_equal "Could not find or build blob: expected attachable, got :foo", error.message
  end

  test "analyzing a new blob from an uploaded file after attaching it to a new record" do
    perform_enqueued_jobs do
      user = User.create!(name: "Jason", avatar: fixture_file_upload("racecar.jpg"))
      assert user.avatar.reload.analyzed?
      assert_equal 4104, user.avatar.metadata[:width]
      assert_equal 2736, user.avatar.metadata[:height]
    end
  end

  test "analyzing a directly-uploaded blob after attaching it to a new record" do
    perform_enqueued_jobs do
      user = User.create!(name: "Jason", avatar: directly_upload_file_blob(filename: "racecar.jpg"))
      assert user.avatar.reload.analyzed?
      assert_equal 4104, user.avatar.metadata[:width]
      assert_equal 2736, user.avatar.metadata[:height]
    end
  end

  test "detaching" do
    create_blob(filename: "funky.jpg").tap do |blob|
      @user.avatar.attach blob
      assert @user.avatar.attached?

      perform_enqueued_jobs do
        @user.avatar.detach
      end

      assert_not @user.avatar.attached?
      assert ActiveStorage::Blob.exists?(blob.id)
      assert ActiveStorage::Blob.service.exist?(blob.key)
    end
  end

  test "detaching when record is not persisted" do
    create_blob(filename: "funky.jpg").tap do |blob|
      user = User.new
      user.avatar.attach blob
      assert user.avatar.attached?

      perform_enqueued_jobs do
        user.avatar.detach
      end

      assert_not user.avatar.attached?
      assert ActiveStorage::Blob.exists?(blob.id)
      assert ActiveStorage::Blob.service.exist?(blob.key)
    end
  end

  test "purging" do
    create_blob(filename: "funky.jpg").tap do |blob|
      @user.avatar.attach blob
      assert @user.avatar.attached?

      assert_changes -> { @user.updated_at } do
        @user.avatar.purge
      end
      assert_not @user.avatar.attached?
      assert_not ActiveStorage::Blob.exists?(blob.id)
      assert_not ActiveStorage::Blob.service.exist?(blob.key)
    end
  end

  test "purging an attachment with a shared blob" do
    create_blob(filename: "funky.jpg").tap do |blob|
      @user.avatar.attach blob
      assert @user.avatar.attached?

      another_user = User.create!(name: "John")
      another_user.avatar.attach blob
      assert another_user.avatar.attached?

      @user.avatar.purge
      assert_not @user.avatar.attached?
      assert ActiveStorage::Blob.exists?(blob.id)
      assert ActiveStorage::Blob.service.exist?(blob.key)
    end
  end

  test "purging when record is not persisted" do
    create_blob(filename: "funky.jpg").tap do |blob|
      user = User.new
      user.avatar.attach blob
      assert user.avatar.attached?

      attachment = user.avatar.attachment
      user.avatar.purge

      assert_not user.avatar.attached?
      assert attachment.destroyed?
      assert_not ActiveStorage::Blob.exists?(blob.id)
      assert_not ActiveStorage::Blob.service.exist?(blob.key)
    end
  end

  test "purging delete changes when record is not persisted" do
    user = User.new
    user.avatar = nil

    user.avatar.purge

    assert_nil user.attachment_changes["avatar"]
  end

  test "purging later" do
    create_blob(filename: "funky.jpg").tap do |blob|
      @user.avatar.attach blob
      assert @user.avatar.attached?

      perform_enqueued_jobs do
        assert_changes -> { @user.updated_at } do
          @user.avatar.purge_later
        end
      end

      assert_not @user.avatar.attached?
      assert_not ActiveStorage::Blob.exists?(blob.id)
      assert_not ActiveStorage::Blob.service.exist?(blob.key)
    end
  end

  test "purging an attachment later with shared blob" do
    create_blob(filename: "funky.jpg").tap do |blob|
      @user.avatar.attach blob
      assert @user.avatar.attached?

      another_user = User.create!(name: "John")
      another_user.avatar.attach blob
      assert another_user.avatar.attached?

      perform_enqueued_jobs do
        @user.avatar.purge_later
      end

      assert_not @user.avatar.attached?
      assert ActiveStorage::Blob.exists?(blob.id)
      assert ActiveStorage::Blob.service.exist?(blob.key)
    end
  end

  test "purging an attachment later when record is not persisted" do
    create_blob(filename: "funky.jpg").tap do |blob|
      user = User.new
      user.avatar.attach blob
      assert user.avatar.attached?

      attachment = user.avatar.attachment
      perform_enqueued_jobs do
        user.avatar.purge_later
      end

      assert_not user.avatar.attached?
      assert attachment.destroyed?
      assert_not ActiveStorage::Blob.exists?(blob.id)
      assert_not ActiveStorage::Blob.service.exist?(blob.key)
    end
  end

  test "purging dependent attachment later on destroy" do
    create_blob(filename: "funky.jpg").tap do |blob|
      @user.avatar.attach blob

      perform_enqueued_jobs do
        @user.destroy!
      end

      assert_not ActiveStorage::Blob.exists?(blob.id)
      assert_not ActiveStorage::Blob.service.exist?(blob.key)
    end
  end

  test "not purging independent attachment on destroy" do
    create_blob(filename: "funky.jpg").tap do |blob|
      @user.cover_photo.attach blob

      assert_no_enqueued_jobs do
        @user.destroy!
      end
    end
  end

  test "duped record does not share attachments" do
    @user.avatar.attach create_blob(filename: "funky.jpg")

    assert_not_equal @user.avatar.attachment, @user.dup.avatar.attachment
  end

  test "duped record does not share attachment changes" do
    @user.avatar.attach create_blob(filename: "funky.jpg")
    assert_not_predicate @user, :changed_for_autosave?

    @user.dup.avatar.attach create_blob(filename: "town.jpg")
    assert_not_predicate @user, :changed_for_autosave?
  end

  test "clearing change on reload" do
    @user.avatar = create_blob(filename: "funky.jpg")
    assert @user.avatar.attached?

    @user.reload
    assert_not @user.avatar.attached?
  end

  test "overriding attached reader" do
    @user.avatar.attach create_blob(filename: "funky.jpg")

    assert_equal "funky.jpg", @user.avatar.filename.to_s

    begin
      User.class_eval do
        def avatar
          super.filename.to_s.reverse
        end
      end

      assert_equal "gpj.yknuf", @user.avatar
    ensure
      User.remove_method :avatar
    end
  end

  test "attaching a new blob from a Hash with a custom service" do
    with_service("mirror") do
      @user.avatar.attach io: StringIO.new("STUFF"), filename: "town.jpg", content_type: "image/jpeg"
      @user.cover_photo.attach io: StringIO.new("STUFF"), filename: "town.jpg", content_type: "image/jpeg"

      assert_instance_of ActiveStorage::Service::MirrorService, @user.avatar.service
      assert_instance_of ActiveStorage::Service::DiskService, @user.cover_photo.service
    end
  end

  test "attaching a new blob from an uploaded file with a custom_service" do
    with_service("mirror") do
      @user.avatar.attach fixture_file_upload("racecar.jpg")
      @user.cover_photo.attach fixture_file_upload("racecar.jpg")

      assert_instance_of ActiveStorage::Service::MirrorService, @user.avatar.service
      assert_instance_of ActiveStorage::Service::DiskService, @user.cover_photo.service
    end
  end

  test "raises error when misconfigured service is passed" do
    error = assert_raises ArgumentError do
      User.class_eval do
        has_one_attached :featured_photo, service: :unknown
      end
    end

    assert_match(/Cannot configure service :unknown for User#featured_photo/, error.message)
  end

  test "creating variation by variation name" do
    @user.avatar_with_variants.attach fixture_file_upload("racecar.jpg")
    variant = @user.avatar_with_variants.variant(:thumb).processed

    image = read_image(variant)
    assert_equal "JPEG", image.type
    assert_equal 100, image.width
    assert_equal 67, image.height
  end

  test "raises error when unknown variant name is used" do
    @user.avatar_with_variants.attach fixture_file_upload("racecar.jpg")

    error = assert_raises ArgumentError do
      @user.avatar_with_variants.variant(:unknown).processed
    end

    assert_match(/Cannot find variant :unknown for User#avatar_with_variants/, error.message)
  end
end

redpajama_set_name: RedPajamaGithub


text:
package org.hswebframework.web.authorization.oauth2.server.support.code;

/**
 *
 * @author zhouhao
 */
public interface AuthorizationCodeService {
    String createAuthorizationCode(AuthorizationCodeRequest request);

    AuthorizationCode consumeAuthorizationCode(String code);
}


text:
INSERT INTO public.dbprefixsections (
name, abbreviation, "position", hidden, id) VALUES (
'ssss'::text, 'sss'::text, '0'::smallint, false::boolean, 1)
 returning id;

INSERT INTO public.dbprefixboards (
section_id, uri, dir, navbar_position, title, subtitle, description, max_file_size, max_threads, default_style, locked, force_anonymous, autosage_after, no_images_after, max_message_length, min_message_length, allow_embeds, redirect_to_thread, require_file, enable_catalog) VALUES (
'1'::bigint, 'drrr'::text, 'dr'::character varying(45), '0'::smallint, 'title'::character varying(45), 'subtitle'::character varying(64), 'descr'::character varying(64), '456456'::integer, '444'::smallint, 'idk'::character varying(45), false::boolean, true::boolean, '33'::smallint, '44'::smallint, '4435'::smallint, '23'::smallint, true::boolean, true::boolean, true::boolean, true::boolean)
 returning id;

INSERT INTO public.dbprefixthreads (
board_id) VALUES (
'1'::bigint)

 returning id;INSERT INTO public.dbprefixthreads (
board_id) VALUES (
'1'::bigint)
 returning id;

 INSERT INTO public.dbprefixposts (
thread_id, is_top_post, ip, message, message_raw, password, created_on) VALUES (
'1'::bigint, true::boolean, '1'::integer, 'ffff'::text, 'ddddd'::text, 'ffff'::text, '2020-04-12 20:51:25.438903')
 returning id;

 INSERT INTO public.dbprefixposts (
thread_id, ip, message, message_raw, password, created_on) VALUES (
'1'::bigint, '1'::integer, 'sss'::text, 'ssss'::text, 'ssss'::text, '2020-04-12 20:51:52.465178')
 returning id;

  INSERT INTO public.dbprefixposts (
thread_id, is_top_post, ip, message, message_raw, password, created_on) VALUES (
'2'::bigint, true::boolean, '1'::integer, 'ffff'::text, 'ddddd'::text, 'ffff'::text, '2020-03-12 20:51:25.438903')
 returning id;

 INSERT INTO public.dbprefixposts (
thread_id, ip, message, message_raw, password, created_on) VALUES (
'2'::bigint, '1'::integer, 'sss'::text, 'ssss'::text, 'ssss'::text, '2020-03-12 20:51:52.465178')
 returning id;

 INSERT INTO public.dbprefixfiles (
post_id, file_order, original_filename, filename, checksum, file_size, is_spoilered, thumbnail_width, thumbnail_height, width, height) VALUES (
'2'::bigint, '0'::integer, '2a'::character varying(255), '2a'::character varying(45), '1'::integer, '1'::integer, false::boolean, '5'::integer, '5'::integer, '10'::integer, '10'::integer)
 returning id;

 INSERT INTO public.dbprefixfiles (
post_id, file_order, original_filename, filename, checksum, file_size, is_spoilered, thumbnail_width, thumbnail_height, width, height) VALUES (
'1'::bigint, '0'::integer, '1a'::character varying(255), '1a'::character varying(45), '2'::integer, '2'::integer, false::boolean, '5'::integer, '5'::integer, '10'::integer, '10'::integer)
 returning id;

 INSERT INTO public.dbprefixfiles (
post_id, file_order, original_filename, filename, checksum, file_size, is_spoilered, thumbnail_width, thumbnail_height, width, height) VALUES (
'3'::bigint, '0'::integer, '3a'::character varying(255), '3a'::character varying(45), '3'::integer, '3'::integer, false::boolean, '5'::integer, '5'::integer, '10'::integer, '10'::integer)
 returning id;

 INSERT INTO public.dbprefixfiles (
post_id, file_order, original_filename, filename, checksum, file_size, is_spoilered, thumbnail_width, thumbnail_height, width, height) VALUES (
'2'::bigint, '1'::integer, '2b'::character varying(255), '2b'::character varying(45), '4'::integer, '4'::integer, false::boolean, '5'::integer, '5'::integer, '10'::integer, '10'::integer)
 returning id;

 INSERT INTO public.dbprefixfiles (
post_id, file_order, original_filename, filename, checksum, file_size, is_spoilered, thumbnail_width, thumbnail_height, width, height) VALUES (
'3'::bigint, '1'::integer, '3b'::character varying(255), '3b'::character varying(45), '5'::integer, '5'::integer, false::boolean, '55'::integer, '5'::integer, '10'::integer, '10'::integer)
 returning id;


text:
import java.io.*;
import java.util.regex.Matcher;

public class MaslSerial implements Serial {

    private PrintStream     output;             // output stream

    // public constructor
    public MaslSerial() {
        output = System.out;
    }

    // set output stream
    public void setOutput( PrintStream out ) {
        if ( null != out ) {
            output = out;
        }
    }

    // populate
    public void populate( String classname, String[] value ) {
        // check args
        if ( classname == null || classname.equals("") || value == null )
            return;

        // print the classname
        output.print( classname );

        // if there are args
        if ( value.length > 0 && value[0] != null ) {

            // print all args
            for ( String arg : value ) {
                output.print( "," );

                // print arg
                output.print( serial_MASL_encode( arg ) );
            }
        }

        // print newline
        output.println();
    }

    /*
     * serial_MASL_encode
     *
     * This function encodes a serial MASL string, replacing
     * special characters according to the following table:
     *
     * | Character | Encoding |
     * |:---------:|:--------:|
     * | %         | %25      |
     * | ,         | %2C      |
     * | \n        | %0A      |
     * | \r        | %0D      |
     *
     * expects a string to encode as an argument
     */
    private String serial_MASL_encode( String str ) {
        if ( null == str ) return null;
        return str.replaceAll( "%", "%25" ).replaceAll( ",", "%2C" ).replaceAll( "\n", "%0A" ).replaceAll( "\r", "%0D" );
    }

}


text:
package br.com.six2six.fixturefactory.transformer;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class PrimitiveTransformerTest {

    @Test
    public void shouldNotAcceptNonStringValue() {
        assertFalse(new PrimitiveTransformer().accepts(new Object(), long.class));
    }

    @Test
    public void shouldNotAcceptNonPrimitiveTarget() {
        assertFalse(new PrimitiveTransformer().accepts("1", Object.class));
    }

    @Test
    public void shouldAcceptStringToNumericType() {
        assertTrue(new PrimitiveTransformer().accepts("1", int.class));
    }

    @Test
    public void shouldAcceptStringToBooleanType() {
        assertTrue(new PrimitiveTransformer().accepts("1", boolean.class));
    }

    @Test
    public void shouldTransformToNumberTarget() {
        long result = new PrimitiveTransformer().transform("1", long.class);
        assertEquals(1L, result);
    }

    @Test
    public void shouldTransformToBooleanTarget() {
        boolean result = new PrimitiveTransformer().transform("true", boolean.class);
        assertTrue(result);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  #%L
  Fabric8 :: Container :: Karaf
  %%
  Copyright (C) 2014 Red Hat
  %%
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
  #L%
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>io.fabric8.poc</groupId>
        <artifactId>fabric8-container</artifactId>
        <version>2.0.0-SNAPSHOT</version>
    </parent>

    <artifactId>fabric8-container-karaf</artifactId>
    <name>Fabric8 :: Container :: Karaf</name>
    <packaging>pom</packaging>

    <modules>
        <module>distro</module>
        <module>features</module>
        <module>managed</module>
        <module>patch</module>
        <module>attributes</module>

    </modules>

</project>


text:
{% load i18n %}<!DOCTYPE html>

    <meta charset="utf-8"/>
    <meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible">
    <meta name="viewport" content="width=device-width"/>
    <title>Blogpost preview – 1%Club</title>

    <link rel="stylesheet" href="{{ STATIC_URL }}css/screen.css"
          media="screen"/>

{# wrapper has a fixed width because everything is relative to that. #}
{# Hence the body receives an overflow-x instead of shrinking the wrapper.  #}

{% if blogpost.title %}{{ blogpost.title }}{% else %}
                {% trans "Blog post preview" %}{% endif %}

            {% trans "now" %}

                {{ request.user.get_full_name|default:request.user.username }}
                1%CREW


text:
import { browserHistory } from 'react-router';
import {
  POSTING_DISCUSSION_START,
  POSTING_DISCUSSION_END,
  POSTING_DISCUSSION_SUCCESS,
  POSTING_DISCUSSION_FAILURE,

  UPDATE_DISCUSSION_TITLE,
  UPDATE_DISCUSSION_CONTENT,
  UPDATE_DISCUSSION_PIN_STATUS,
  UPDATE_DISCUSSION_TAGS,

  CLEAR_SUCCESS_MESSAGE,
} from './constants';
import { postDiscussionApi } from './api';

/**
 * post a new discussion
 * @param  {ObjectId} userId
 * @param  {ObjectId} forumId
 * @param  {String} currentForum
 * @return {action}
 */
export const postDiscussion = (userId, forumId, currentForum) => {
  return (dispatch, getState) => {
    dispatch({ type: POSTING_DISCUSSION_START });

    // validate discussion inputs
    // discussion values are in redux state
    const {
      title,
      content,
      tags,
      pinned,
    } = getState().newDiscussion;

    let validated = true;

    if (!userId || !forumId) {
      validated = false;
      return dispatch({
        type: POSTING_DISCUSSION_FAILURE,
        payload: 'Something is wrong with user/forum.',
      });
    }

    if (title === null || title.length < 15) {
      validated = false;
      return dispatch({
        type: POSTING_DISCUSSION_FAILURE,
        payload: 'Title should be at least 15 characters.',
      });
    }

    if (content === null || content.length === 0) {
      validated = false;
      return dispatch({
        type: POSTING_DISCUSSION_FAILURE,
        payload: 'Please write some content before posting.',
      });
    }

    if (tags === null || tags.length === 0) {
      validated = false;
      return dispatch({
        type: POSTING_DISCUSSION_FAILURE,
        payload: 'Please provide some tags.',
      });
    }

    // make api call if post is validated
    if (validated) {
      postDiscussionApi({
        userId,
        forumId,
        title,
        content,
        tags,
        pinned,
      }).then(
        (data) => {
          if (data.data.postCreated === true) {
            dispatch({ type: POSTING_DISCUSSION_SUCCESS });
            setTimeout(() => { dispatch({ type: CLEAR_SUCCESS_MESSAGE }); }, 2000);

            // issue a redirect to the newly reacted discussion
            browserHistory.push(`/${currentForum}/discussion/${data.data.discussion_slug}`);
          } else {
            dispatch({
              type: POSTING_DISCUSSION_FAILURE,
              payload: 'Something is wrong at our server end. Please try again later',
            });
          }
        },
        (error) => {
          dispatch({
            type: POSTING_DISCUSSION_FAILURE,
            payload: error,
          });
        }
      );
    }
  };
};

/**
 * update the discussion title in redux state (controlled input)
 * @param  {String} value
 * @return {action}
 */
export const updateDiscussionTitle = (value) => {
  return {
    type: UPDATE_DISCUSSION_TITLE,
    payload: value,
  };
};

/**
 * update discussion content in redux state (controlled input)
 * @param  {Object} value
 * @return {action}
 */
export const updateDiscussionContent = (value) => {
  return {
    type: UPDATE_DISCUSSION_CONTENT,
    payload: value,
  };
};

/**
 * update discussion pinned status in redux state (controlled input)
 * @param  {Boolean} value
 * @return {action}
 */
export const updateDiscussionPinStatus = (value) => {
  return {
    type: UPDATE_DISCUSSION_PIN_STATUS,
    payload: value,
  };
};

/**
 * update discussion tags in redux state (controlled input)
 * @param  {Array} value
 * @return {action}
 */
export const updateDiscussionTags = (value) => {
  return {
    type: UPDATE_DISCUSSION_TAGS,
    payload: value,
  };
};


text:
package progen.context;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

public class UninitializedContextExceptionTest {

  @Rule
  public ExpectedException exception = ExpectedException.none();

  @Test
  public void test() {
      exception.expect(UninitializedContextException.class);
      exception.expectMessage("No inicialized properties. First call makeInstance() method.");
      throw new UninitializedContextException();
    }

}


text:
package com.amazonservices.mws.products.model;

import javax.xml.bind.annotation.*;

import com.amazonservices.mws.client.*;

/**
 * GetLowestPricedOffersForSKUResponse complex type.
 *
 * XML schema:
 *
 * <pre>
 * <complexType name="GetLowestPricedOffersForSKUResponse">
 *    <complexContent>
 *       <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *          <sequence>
 *             <element name="GetLowestPricedOffersForSKUResult" type="{http://mws.amazonservices.com/schema/Products/2011-10-01}GetLowestPricedOffersForSKUResult" minOccurs="0"/>
 *             <element name="ResponseMetadata" type="{http://mws.amazonservices.com/schema/Products/2011-10-01}ResponseMetadata" minOccurs="0"/>
 *          </sequence>
 *       </restriction>
 *    </complexContent>
 * </complexType>
 * </pre>
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name="GetLowestPricedOffersForSKUResponse", propOrder={
    "getLowestPricedOffersForSKUResult",
    "responseMetadata"
})
@XmlRootElement(name = "GetLowestPricedOffersForSKUResponse")
public class GetLowestPricedOffersForSKUResponse extends AbstractMwsObject implements MWSResponse {

    @XmlElement(name="GetLowestPricedOffersForSKUResult")
    private GetLowestPricedOffersForSKUResult getLowestPricedOffersForSKUResult;

    @XmlElement(name="ResponseMetadata")
    private ResponseMetadata responseMetadata;

    @XmlTransient
    private ResponseHeaderMetadata responseHeaderMetadata;

    /**
     * Get the value of GetLowestPricedOffersForSKUResult.
     *
     * @return The value of GetLowestPricedOffersForSKUResult.
     */
    public GetLowestPricedOffersForSKUResult getGetLowestPricedOffersForSKUResult() {
        return getLowestPricedOffersForSKUResult;
    }

    /**
     * Set the value of GetLowestPricedOffersForSKUResult.
     *
     * @param getLowestPricedOffersForSKUResult
     *            The new value to set.
     */
    public void setGetLowestPricedOffersForSKUResult(GetLowestPricedOffersForSKUResult getLowestPricedOffersForSKUResult) {
        this.getLowestPricedOffersForSKUResult = getLowestPricedOffersForSKUResult;
    }

    /**
     * Check to see if GetLowestPricedOffersForSKUResult is set.
     *
     * @return true if GetLowestPricedOffersForSKUResult is set.
     */
    public boolean isSetGetLowestPricedOffersForSKUResult() {
        return getLowestPricedOffersForSKUResult != null;
    }

    /**
     * Set the value of GetLowestPricedOffersForSKUResult, return this.
     *
     * @param getLowestPricedOffersForSKUResult
     *             The new value to set.
     *
     * @return This instance.
     */
    public GetLowestPricedOffersForSKUResponse withGetLowestPricedOffersForSKUResult(GetLowestPricedOffersForSKUResult getLowestPricedOffersForSKUResult) {
        this.getLowestPricedOffersForSKUResult = getLowestPricedOffersForSKUResult;
        return this;
    }

    /**
     * Get the value of ResponseMetadata.
     *
     * @return The value of ResponseMetadata.
     */
    public ResponseMetadata getResponseMetadata() {
        return responseMetadata;
    }

    /**
     * Set the value of ResponseMetadata.
     *
     * @param responseMetadata
     *            The new value to set.
     */
    public void setResponseMetadata(ResponseMetadata responseMetadata) {
        this.responseMetadata = responseMetadata;
    }

    /**
     * Check to see if ResponseMetadata is set.
     *
     * @return true if ResponseMetadata is set.
     */
    public boolean isSetResponseMetadata() {
        return responseMetadata != null;
    }

    /**
     * Set the value of ResponseMetadata, return this.
     *
     * @param responseMetadata
     *             The new value to set.
     *
     * @return This instance.
     */
    public GetLowestPricedOffersForSKUResponse withResponseMetadata(ResponseMetadata responseMetadata) {
        this.responseMetadata = responseMetadata;
        return this;
    }

    /**
     * Get the value of ResponseHeaderMetadata.
     *
     * @return The value of ResponseHeaderMetadata.
     */
    public ResponseHeaderMetadata getResponseHeaderMetadata() {
        return responseHeaderMetadata;
    }

    /**
     * Set the value of ResponseHeaderMetadata.
     *
     * @param responseHeaderMetadata
     *            The new value to set.
     */
    public void setResponseHeaderMetadata(ResponseHeaderMetadata responseHeaderMetadata) {
        this.responseHeaderMetadata = responseHeaderMetadata;
    }

    /**
     * Check to see if ResponseHeaderMetadata is set.
     *
     * @return true if ResponseHeaderMetadata is set.
     */
    public boolean isSetResponseHeaderMetadata() {
        return responseHeaderMetadata != null;
    }

    /**
     * Set the value of ResponseHeaderMetadata, return this.
     *
     * @param responseHeaderMetadata
     *             The new value to set.
     *
     * @return This instance.
     */
    public GetLowestPricedOffersForSKUResponse withResponseHeaderMetadata(ResponseHeaderMetadata responseHeaderMetadata) {
        this.responseHeaderMetadata = responseHeaderMetadata;
        return this;
    }

    /**
     * Read members from a MwsReader.
     *
     * @param r
     *      The reader to read from.
     */
    @Override
    public void readFragmentFrom(MwsReader r) {
        getLowestPricedOffersForSKUResult = r.read("GetLowestPricedOffersForSKUResult", GetLowestPricedOffersForSKUResult.class);
        responseMetadata = r.read("ResponseMetadata", ResponseMetadata.class);
    }

    /**
     * Write members to a MwsWriter.
     *
     * @param w
     *      The writer to write to.
     */
    @Override
    public void writeFragmentTo(MwsWriter w) {
        w.write("GetLowestPricedOffersForSKUResult", getLowestPricedOffersForSKUResult);
        w.write("ResponseMetadata", responseMetadata);
    }

    /**
     * Write tag, xmlns and members to a MwsWriter.
     *
     * @param w
     *         The Writer to write to.
     */
    @Override
    public void writeTo(MwsWriter w) {
        w.write("http://mws.amazonservices.com/schema/Products/2011-10-01", "GetLowestPricedOffersForSKUResponse",this);
    }

    /** Default constructor. */
    public GetLowestPricedOffersForSKUResponse() {
        super();
    }

}


text:
/**
 * a global class
 */
class GlobalClass {
  /**
   * the global class constructor
   * @param {number} - first param
   * @param {string} - second param
   * @throws {string} A serious error occurred.
   * @example
   * var one = 1
   */
  constructor (one, two) {
    /**
     * an instance property
     * @type {number}
     */
    this.propOne = 1
  }

  /** a static method */
  static shat () {}

  /** parent method one */
  methodOne () {}
  /** parent method two */
  methodTwo () {}
}

/**
 * the child of global class
 * @extends GlobalClass
 */
class GlobalChildClass extends GlobalClass {
  constructor () {
    /** an instance property */
    this.propThree = 1
  }

  /** overridden child methodTwo */
  methodTwo () {}
}


text:
#include "constants.h"
#include "ips_simple.h"
#include "ips_with_cuda.h"
#include <unistd.h>
#include <stdio.h>

IPS_simple* strategy = new IPS_simple();
//IPS_with_cuda* strategy = new IPS_with_cuda();

struct timespec start, stop;

void step(){

    switch(Constants::STEP_STATE){
        case Constants::RAW:
            //next state
            Constants::STEP_STATE = Constants::LAPLACE;
            break;
        case Constants::BLUR:
            strategy->processBlur();
            //next state
            Constants::STEP_STATE = Constants::SUBS;
            break;
        case Constants::LAPLACE:
            strategy->processLaplacian();
            //next state
            Constants::STEP_STATE = Constants::BLUR;
            break;
        case Constants::EDGES:
            //strategy->processEdge();
            //next state
            Constants::STEP_STATE = Constants::CONTOURNS;
            break;
        case Constants::SUBS:
            strategy->processSubs();
            //next state
            Constants::STEP_STATE = Constants::EDGES;
            break;
        case Constants::CONTOURNS:
            //strategy->processContourns();
            break;
    }
}

//pasar como argumento el path completo de la imagen lana.jpg
int main( int argc, char** argv )
{
    remove(Constants::IMG_RAW_BLUR);
    remove(Constants::IMG_RAW_LAPLACE);
    remove(Constants::IMG_REF_BLUR);
    remove(Constants::IMG_REF_LAPLACE);
    remove(Constants::IMG_SUBS);
    remove(Constants::IMG_EDGES);
    remove(Constants::IMG_CONTOURNS);
    remove(Constants::IMG_FINAL);

    /*	*/
    printf("inicio de la ejecucion\n");
    clock_t startProgram = clock();

    for ( int j=0; j<6; j++){
        step();
    }

    clock_t stopProgram = clock();
    double elapsedProgram = (double)difftime(startProgram, stopProgram) * 1000.0 / CLOCKS_PER_SEC;
    printf("Tiempo de ejecucion TOTAL:\t\t%f\tms \n", std::abs(elapsedProgram) );
    printf("fin  de la ejecucion\n");

}


text:
import { Container } from "../Container";
import { Particle } from "../Particle";
export declare class Collider {
    private readonly container;
    private readonly particle;
    constructor(container: Container, particle: Particle);
    collide(p2: Particle): void;
}


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

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

class nstimeout(base_resource) :
	""" Configuration for timeout resource. """
	def __init__(self) :
		self._zombie = 0
		self._client = 0
		self._server = 0
		self._httpclient = 0
		self._httpserver = 0
		self._tcpclient = 0
		self._tcpserver = 0
		self._anyclient = 0
		self._anyserver = 0
		self._halfclose = 0
		self._nontcpzombie = 0
		self._reducedfintimeout = 0
		self._reducedrsttimeout = 0
		self._newconnidletimeout = 0

	@property
	def zombie(self) :
		"""Interval, in seconds, at which the NetScaler zombie cleanup process must run. This process cleans up inactive TCP connections.
Default value: 120
Minimum length =  1
Maximum length =  600.
		"""
		try :
			return self._zombie
		except Exception as e:
			raise e

	@zombie.setter
	def zombie(self, zombie) :
		"""Interval, in seconds, at which the NetScaler zombie cleanup process must run. This process cleans up inactive TCP connections.
Default value: 120
Minimum length =  1
Maximum length =  600
		"""
		try :
			self._zombie = zombie
		except Exception as e:
			raise e

	@property
	def client(self) :
		"""Client idle timeout (in seconds).  If zero, the service-type default value is taken when service is created.
Maximum length =  18000.
		"""
		try :
			return self._client
		except Exception as e:
			raise e

	@client.setter
	def client(self, client) :
		"""Client idle timeout (in seconds).  If zero, the service-type default value is taken when service is created.
Maximum length =  18000
		"""
		try :
			self._client = client
		except Exception as e:
			raise e

	@property
	def server(self) :
		"""Server idle timeout (in seconds).  If zero, the service-type default is taken when service is created.
Maximum length =  18000.
		"""
		try :
			return self._server
		except Exception as e:
			raise e

	@server.setter
	def server(self, server) :
		"""Server idle timeout (in seconds).  If zero, the service-type default is taken when service is created.
Maximum length =  18000
		"""
		try :
			self._server = server
		except Exception as e:
			raise e

	@property
	def httpclient(self) :
		"""Global idle timeout, in seconds, for client connections of HTTP service type. This value is over ridden by the client timeout that is configured on individual entities.
Maximum length =  18000.
		"""
		try :
			return self._httpclient
		except Exception as e:
			raise e

	@httpclient.setter
	def httpclient(self, httpclient) :
		"""Global idle timeout, in seconds, for client connections of HTTP service type. This value is over ridden by the client timeout that is configured on individual entities.
Maximum length =  18000
		"""
		try :
			self._httpclient = httpclient
		except Exception as e:
			raise e

	@property
	def httpserver(self) :
		"""Global idle timeout, in seconds, for server connections of HTTP service type. This value is over ridden by the server timeout that is configured on individual entities.
Maximum length =  18000.
		"""
		try :
			return self._httpserver
		except Exception as e:
			raise e

	@httpserver.setter
	def httpserver(self, httpserver) :
		"""Global idle timeout, in seconds, for server connections of HTTP service type. This value is over ridden by the server timeout that is configured on individual entities.
Maximum length =  18000
		"""
		try :
			self._httpserver = httpserver
		except Exception as e:
			raise e

	@property
	def tcpclient(self) :
		"""Global idle timeout, in seconds, for non-HTTP client connections of TCP service type. This value is over ridden by the client timeout that is configured on individual entities.
Maximum length =  18000.
		"""
		try :
			return self._tcpclient
		except Exception as e:
			raise e

	@tcpclient.setter
	def tcpclient(self, tcpclient) :
		"""Global idle timeout, in seconds, for non-HTTP client connections of TCP service type. This value is over ridden by the client timeout that is configured on individual entities.
Maximum length =  18000
		"""
		try :
			self._tcpclient = tcpclient
		except Exception as e:
			raise e

	@property
	def tcpserver(self) :
		"""Global idle timeout, in seconds, for non-HTTP server connections of TCP service type. This value is over ridden by the server timeout that is configured on entities.
Maximum length =  18000.
		"""
		try :
			return self._tcpserver
		except Exception as e:
			raise e

	@tcpserver.setter
	def tcpserver(self, tcpserver) :
		"""Global idle timeout, in seconds, for non-HTTP server connections of TCP service type. This value is over ridden by the server timeout that is configured on entities.
Maximum length =  18000
		"""
		try :
			self._tcpserver = tcpserver
		except Exception as e:
			raise e

	@property
	def anyclient(self) :
		"""Global idle timeout, in seconds, for non-TCP client connections. This value is over ridden by the client timeout that is configured on individual entities.
Maximum length =  31536000.
		"""
		try :
			return self._anyclient
		except Exception as e:
			raise e

	@anyclient.setter
	def anyclient(self, anyclient) :
		"""Global idle timeout, in seconds, for non-TCP client connections. This value is over ridden by the client timeout that is configured on individual entities.
Maximum length =  31536000
		"""
		try :
			self._anyclient = anyclient
		except Exception as e:
			raise e

	@property
	def anyserver(self) :
		"""Global idle timeout, in seconds, for non TCP server connections. This value is over ridden by the server timeout that is configured on individual entities.
Maximum length =  31536000.
		"""
		try :
			return self._anyserver
		except Exception as e:
			raise e

	@anyserver.setter
	def anyserver(self, anyserver) :
		"""Global idle timeout, in seconds, for non TCP server connections. This value is over ridden by the server timeout that is configured on individual entities.
Maximum length =  31536000
		"""
		try :
			self._anyserver = anyserver
		except Exception as e:
			raise e

	@property
	def halfclose(self) :
		"""Idle timeout, in seconds, for connections that are in TCP half-closed state.
Default value: 10
Minimum length =  1
Maximum length =  600.
		"""
		try :
			return self._halfclose
		except Exception as e:
			raise e

	@halfclose.setter
	def halfclose(self, halfclose) :
		"""Idle timeout, in seconds, for connections that are in TCP half-closed state.
Default value: 10
Minimum length =  1
Maximum length =  600
		"""
		try :
			self._halfclose = halfclose
		except Exception as e:
			raise e

	@property
	def nontcpzombie(self) :
		"""Interval at which the zombie clean-up process for non-TCP connections should run. Inactive IP NAT connections will be cleaned up.
Default value: 60
Minimum length =  1
Maximum length =  600.
		"""
		try :
			return self._nontcpzombie
		except Exception as e:
			raise e

	@nontcpzombie.setter
	def nontcpzombie(self, nontcpzombie) :
		"""Interval at which the zombie clean-up process for non-TCP connections should run. Inactive IP NAT connections will be cleaned up.
Default value: 60
Minimum length =  1
Maximum length =  600
		"""
		try :
			self._nontcpzombie = nontcpzombie
		except Exception as e:
			raise e

	@property
	def reducedfintimeout(self) :
		"""Alternative idle timeout for new TCP NATPCB connections.
Default value: 30
Minimum length =  1
Maximum length =  300.
		"""
		try :
			return self._reducedfintimeout
		except Exception as e:
			raise e

	@reducedfintimeout.setter
	def reducedfintimeout(self, reducedfintimeout) :
		"""Alternative idle timeout for new TCP NATPCB connections.
Default value: 30
Minimum length =  1
Maximum length =  300
		"""
		try :
			self._reducedfintimeout = reducedfintimeout
		except Exception as e:
			raise e

	@property
	def reducedrsttimeout(self) :
		"""Timer interval(in seconds) for NATPCB for tcp flow.
Default value: 30
Minimum length =  1
Maximum length =  300.
		"""
		try :
			return self._reducedrsttimeout
		except Exception as e:
			raise e

	@reducedrsttimeout.setter
	def reducedrsttimeout(self, reducedrsttimeout) :
		"""Timer interval(in seconds) for NATPCB for tcp flow.
Default value: 30
Minimum length =  1
Maximum length =  300
		"""
		try :
			self._reducedrsttimeout = reducedrsttimeout
		except Exception as e:
			raise e

	@property
	def newconnidletimeout(self) :
		"""Timer interval(in seconds) for new NATPCB for tcp connections.
Default value: 4
Minimum length =  1
Maximum length =  120.
		"""
		try :
			return self._newconnidletimeout
		except Exception as e:
			raise e

	@newconnidletimeout.setter
	def newconnidletimeout(self, newconnidletimeout) :
		"""Timer interval(in seconds) for new NATPCB for tcp connections.
Default value: 4
Minimum length =  1
Maximum length =  120
		"""
		try :
			self._newconnidletimeout = newconnidletimeout
		except Exception as e:
			raise e

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

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

	@classmethod
	def update(cls, client, resource) :
		""" Use this API to update nstimeout.
		"""
		try :
			if type(resource) is not list :
				updateresource = nstimeout()
				updateresource.zombie = resource.zombie
				updateresource.client = resource.client
				updateresource.server = resource.server
				updateresource.httpclient = resource.httpclient
				updateresource.httpserver = resource.httpserver
				updateresource.tcpclient = resource.tcpclient
				updateresource.tcpserver = resource.tcpserver
				updateresource.anyclient = resource.anyclient
				updateresource.anyserver = resource.anyserver
				updateresource.halfclose = resource.halfclose
				updateresource.nontcpzombie = resource.nontcpzombie
				updateresource.reducedfintimeout = resource.reducedfintimeout
				updateresource.reducedrsttimeout = resource.reducedrsttimeout
				updateresource.newconnidletimeout = resource.newconnidletimeout
				return updateresource.update_resource(client)
		except Exception as e :
			raise e

	@classmethod
	def unset(cls, client, resource, args) :
		""" Use this API to unset the properties of nstimeout resource.
		Properties that need to be unset are specified in args array.
		"""
		try :
			if type(resource) is not list :
				unsetresource = nstimeout()
				return unsetresource.unset_resource(client, args)
		except Exception as e :
			raise e

	@classmethod
	def get(cls, client, name="", option_="") :
		""" Use this API to fetch all the nstimeout resources that are configured on netscaler.
		"""
		try :
			if not name :
				obj = nstimeout()
				response = obj.get_resources(client, option_)
			return response
		except Exception as e :
			raise e

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


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="prefs_port_entry_values" translatable="false">
        <item>7</item>
        <item>9</item>
    </string-array>

    <string-array name="prefs_port_entries" translatable="false">
        <item>Port 7</item>
        <item>Port 9</item>
    </string-array>
</resources>


text:
/**
 * Int32Type.hpp -
 * @author: Jonathan Beard
 * @version: Sat May 25 20:56:40 2013
 */
#ifndef _INT32TYPE_HPP_
#define _INT32TYPE_HPP_  1

#include <cstdint>
#include "IntType.hpp"

namespace Node{

class Int32Type : public IntType {
public:
   Int32Type();

};

} /* end namespace Node */

#endif /* END _INT32TYPE_HPP_ */


text:
package s3

import (
	"bytes"
	"errors"
	"io/ioutil"
	"net/url"
	"os"

	"golang.org/x/text/unicode/norm"

	"io"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/credentials"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/s3"
	"github.com/aws/aws-sdk-go/service/s3/s3manager"
	"github.com/livesense-inc/fanlin/lib/content"
	"github.com/livesense-inc/fanlin/lib/error"
)

var s3GetSourceFunc = getS3ImageBinary

// Test dedicated function
func setS3GetFunc(f func(config *aws.Config, bucket, key string, file *os.File) (io.Reader, error)) {
	s3GetSourceFunc = f
}

func GetImageBinary(c *content.Content) (io.Reader, error) {
	if c == nil {
		return nil, errors.New("content is nil")
	}
	s3url := c.SourcePlace
	u, err := url.Parse(s3url)
	if err != nil {
		return nil, imgproxyerr.New(imgproxyerr.WARNING, errors.New("can not parse s3 url"))
	}

	file, err := ioutil.TempFile(os.TempDir(), "s3_img")
	defer func() {
		os.Remove(file.Name())
		file.Close()
	}()
	if err != nil {
		return nil, imgproxyerr.New(imgproxyerr.ERROR, err)
	}

	bucket := u.Host

	if region, ok := c.Meta["region"].(string); ok {
		path, err := url.QueryUnescape(u.EscapedPath())
		if err != nil {
			return nil, err
		}
		if form, ok := c.Meta["norm_form"].(string); ok {
			path, err = NormalizePath(path, form)
			if err != nil {
				return nil, err
			}
		}
		config := createAwsConfig(region, c.Meta)
		return s3GetSourceFunc(config, bucket, path, file)
	}
	return nil, imgproxyerr.New(imgproxyerr.ERROR, errors.New("can not parse configure"))
}

// createAwsConfig generate the service configuration
func createAwsConfig(region string, meta map[string]interface{}) *aws.Config {
	if env_credential, ok := meta["use_env_credential"].(bool); ok && env_credential {
		cred := credentials.NewEnvCredentials()
		return &aws.Config{
			Region:      aws.String(region),
			Credentials: cred,
		}
	}
	return &aws.Config{
		Region: aws.String(region),
	}
}

func NormalizePath(path string, form string) (string, error) {
	switch form {
	case "nfd":
		return norm.NFD.String(path), nil
	case "nfc":
		return norm.NFC.String(path), nil
	case "nfkc":
		return norm.NFKC.String(path), nil
	case "nfkd":
		return norm.NFKD.String(path), nil
	}
	return "", imgproxyerr.New(imgproxyerr.WARNING, errors.New("invalid normalization form("+form+")"))
}

func getS3ImageBinary(config *aws.Config, bucket, key string, file *os.File) (io.Reader, error) {
	downloader := s3manager.NewDownloader(session.New(config))
	_, err := downloader.Download(file,
		&s3.GetObjectInput{
			Bucket: aws.String(bucket),
			Key:    aws.String(key),
		},
	)
	if err != nil {
		return nil, imgproxyerr.New(imgproxyerr.WARNING, err)
	}

	ret := new(bytes.Buffer)
	if _, err := io.Copy(ret, file); err != nil {
		return nil, imgproxyerr.New(imgproxyerr.WARNING, err)
	}
	return ret, imgproxyerr.New(imgproxyerr.ERROR, err)
}

func init() {
	content.RegisterContentType("s3", GetImageBinary)
}


text:
/*jslint node: true */
/*jslint unparam: true */
/*global describe:true*/
/*global it:true*/
/*global xdescribe:true*/
/*global xit:true*/

var coinbase = require('..');
var Client   = coinbase.Client;
var assert   = require("assert");
var na     = require('./nockClient');

describe('Client', function() {

  describe('client constructor', function() {
    it('should return client', function() {
      var client = new Client({'apiKey': 'mykey', 'apiSecret': 'mysecret', 'baseApiUri': na.TEST_BASE_URI});
      assert(client);
      assert.equal(client.apiKey, 'mykey');
      assert.equal(client.apiSecret, 'mysecret');
    });
    it('should require constructor new call', function(){
      var cl1 = Client({'apiKey': 'mykey', 'apiSecret': 'mysecret', 'baseApiUri': na.TEST_BASE_URI});
      assert(cl1 instanceof Client);
    });
    it('should require constructor args', function(){
      try {
        Client();
      } catch(err) {
        assert(true);
        return;
      }
      assert(false);
    });

    it('should work support oauth', function() {
      var cl1 = Client({ accessToken: 'mytoken', 'baseApiUri': na.TEST_BASE_URI })
      assert.equal(cl1.accessToken, 'mytoken');
      assert(cl1 instanceof Client);
    })

    it('should support an optional refresh token', function() {
      var cl1 = Client({ accessToken: 'mytoken', refreshToken: 'refreshtoken', 'baseApiUri': na.TEST_BASE_URI })
      assert.equal(cl1.accessToken, 'mytoken');
      assert.equal(cl1.refreshToken, 'refreshtoken');
      assert(cl1 instanceof Client);
    })

    it('should throw if the we do not pass the access token or api credentials', function() {
      try {
        Client({ 'baseApiUri': na.TEST_BASE_URI })
        throw new Error('failed');
      } catch (e) {
        assert.equal(e.message, 'you must either provide an "accessToken" or the "apiKey" & "apiSecret" parameters')
      }
    })

    it('should throw if both the api key + secret and the access token is used', function() {
      try {
        Client({ 'accessToken': 'mytoken', 'apiKey': 'mykey', 'apiSecret': 'mysecret' })
        throw new Error('failed');
      } catch (e) {
        assert.equal(e.message, 'you must either provide an "accessToken" or the "apiKey" & "apiSecret" parameters')
      }
    })
  });

  describe('client methods', function() {

    var client = new Client({'apiKey': 'mykey', 'apiSecret': 'mysecret', 'baseApiUri': na.TEST_BASE_URI});
    it('should get accounts', function() {
      client.getAccounts(function(err, accounts) {
        assert.equal(err, null, err);
        assert(accounts, "no accounts");
        assert.equal(accounts.length, 2, "wrong number of accounts");
        assert.equal(accounts[0].id, na.ACCOUNTS_ID_1,
          "wrong account id: " + accounts[0].id);
        assert.equal(accounts[1].id, na.ACCOUNTS_ID_2,
          "wrong account id: " + accounts[1].id);
      });
    });

    it('should get account', function() {
      client.getAccount(na.ACCOUNTS_ID_1, function(err, account) {
        assert.equal(err, null, err);
        assert(account, 'no account');
        assert.equal(account.id, na.ACCOUNTS_ID_1, 'wrong account');
      });
    });

    it('should create account', function() {
      var args = {
        "name": na.NEW_ACCOUNT_NAME_1
      };
      client.createAccount(args, function(err, account) {
        assert.equal(err, null, err);
        assert(account, 'no account');
        assert(account.name, 'no name');
        assert.equal(account.name, na.NEW_ACCOUNT_NAME_1, 'wrong account name');
      });
    });

    it('should get contacts', function() {
      client.getContacts(2, 9, '1234', function(err, contacts) {
        assert.equal(err, null, err);
        assert(contacts, 'no contacts');
        assert(contacts[0].email, "no email");
        assert.equal(contacts[0].email,
          na.GET_CONTACTS_RESP.contacts[0].contact.email,
          'wrong contacts: ' + contacts[0].email);
      });
    });

    it('should get current user', function() {
      client.getCurrentUser(function(err, user) {
        assert.equal(err, null, err);
        assert(user, 'no user');
        assert(user.name, "no email");
        assert.equal(user.name,
          na.GET_CURRENT_USER_RESP.user.name,
          'wrong user: ' + user.name);

      });
    });

    it('should get buy price', function() {
      client.getBuyPrice({'qty': 2, 'currency': 'USD'}, function(err, obj) {
        assert.equal(err, null, err);
        assert(obj, 'no price');
        assert(obj.total.amount, "no amount");
        assert.equal(obj.total.amount,
          na.GET_BUY_PRICE_RESP.total.amount,
          'wrong amount: ' + obj.total.amount);

      });
    });

    it('should sell price', function() {
      client.getSellPrice({'qty': 3, 'currency': "USD"}, function(err, obj) {
        assert.equal(err, null, err);
        assert(obj, 'no price');
        assert(obj.subtotal.amount, "no amount");
        assert.equal(obj.subtotal.amount,
          na.GET_SELL_PRICE_RESP.subtotal.amount,
          'wrong amount: ' + obj.subtotal.amount);
      });
    });

    it('should spot price', function() {
      client.getSpotPrice(null, function(err, obj) {
        assert.equal(err, null, err);
        assert(obj, 'no price');
        assert(obj.amount, "no amount");
        assert.equal(obj.amount,
          na.GET_SPOT_RESP.amount,
          'wrong amount: ' + obj.amount);
      });

    });

    it('should get supported currencies', function() {
      client.getCurrencies(function(err, obj) {
        assert.equal(err, null, err);
        assert(obj, 'no currencies');
        assert.equal(obj.length,
          na.GET_CURRENCIES_RESP.length,
          'wrong number of currencies: ' + obj.length);
      });
    });

    it('should get exchange rates', function() {
      client.getExchangeRates(function(err, obj) {
        assert.equal(err, null, err);
        assert(obj, 'no rates');
        assert(obj.zwl_to_btc, "no rate");
        assert.equal(obj.zwl_to_btc,
          na.GET_EX_RATES_RESP.zwl_to_btc,
          'wrong rate: ' + obj.zwl_to_btc);
      });
    });

    it('should create user', function() {
      var args = {
        "user": {
          "email": "newuser@example.com",
          "password": "test123!"
        }
      };
      client.createUser(args, function(err, obj) {
        assert.equal(err, null, err);
        assert(obj, 'no obj');
        assert(obj.user, 'no user');
        assert(obj.user.email, "no email");
        assert.equal(obj.user.email,
          na.CREATE_USER_RESP.user.email,
          'wrong user: ' + obj.user.email);
      });
    });

    it('should get payment methods', function() {
      client.getPaymentMethods(function(err, pms) {
        assert.equal(err, null, err);
        assert(pms, 'no payment methods');
        assert.equal(pms.length,
          na.GET_PAYMENT_METHODS_RESP.payment_methods.length,
          'wrong number of methods: ' + pms.length);
      });
    });

    it('should get payment method', function() {
      client.getPaymentMethod(na.GET_PAYMENT_METHOD_RESP.payment_method.id,
        function(err, pm) {
        assert.equal(err, null, err);
        assert(pm, 'no payment method');
        assert.equal(pm.id, na.GET_PAYMENT_METHOD_RESP.payment_method.id,
          'wrong payment method');
      });
    });

    it('should verify a legitimate merchant callback', function() {
      var body = '{"order":{"id":null,"created_at":null,"status":"completed","event":null,"total_btc":{"cents":100000000,"currency_iso":"BTC"},"total_native":{"cents":1000,"currency_iso":"USD"},"total_payout":{"cents":1000,"currency_iso":"USD"},"custom":"123456789","receive_address":"mzVoQenSY6RTBgBUcpSBTBAvUMNgGWxgJn","button":{"type":"buy_now","name":"Test Item","description":null,"id":null},"transaction":{"id":"53bdfe4d091c0d74a7000003","hash":"4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b","confirmations":0}}}';
      var signature = "6yQRl17CNj5YSHSpF+tLjb0vVsNVEv021Tyy1bTVEQ69SWlmhwmJYuMc7jiDyeW9TLy4vRqSh4g4YEyN8eoQIM57pMoNw6Lw6Oudubqwp+E3cKtLFxW0l18db3Z/vhxn5BScAutHWwT/XrmkCNaHyCsvOOGMekwrNO7mxX9QIx21FBaEejJeviSYrF8bG6MbmFEs2VGKSybf9YrElR8BxxNe/uNfCXN3P5tO8MgR5wlL3Kr4yq8e6i4WWJgD08IVTnrSnoZR6v8JkPA+fn7I0M6cy0Xzw3BRMJAvdQB97wkobu97gFqJFKsOH2u/JR1S/UNP26vL0mzuAVuKAUwlRn0SUhWEAgcM3X0UCtWLYfCIb5QqrSHwlp7lwOkVnFt329Mrpjy+jAfYYSRqzIsw4ZsRRVauy/v3CvmjPI9sUKiJ5l1FSgkpK2lkjhFgKB3WaYZWy9ZfIAI9bDyG8vSTT7IDurlUhyTweDqVNlYUsO6jaUa4KmSpg1o9eIeHxm0XBQ2c0Lv/T39KNc/VOAi1LBfPiQYMXD1e/8VuPPBTDGgzOMD3i334ppSr36+8YtApAn3D36Hr9jqAfFrugM7uPecjCGuleWsHFyNnJErT0/amIt24Nh1GoiESEq42o7Co4wZieKZ+/yeAlIUErJzK41ACVGmTnGoDUwEBXxADOdA=";
      assert(client.verifyCallback(body, signature))
    });

    it('should reject a tampered-with merchant callback', function() {
      var body = '{"order":{"id":null,"created_at":null,"status":"completed","event":null,"total_btc":{"cents":1000000000,"currency_iso":"BTC"},"total_native":{"cents":1000,"currency_iso":"USD"},"total_payout":{"cents":1000,"currency_iso":"USD"},"custom":"123456789","receive_address":"mzVoQenSY6RTBgBUcpSBTBAvUMNgGWxgJn","button":{"type":"buy_now","name":"Test Item","description":null,"id":null},"transaction":{"id":"53bdfe4d091c0d74a7000003","hash":"4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b","confirmations":0}}}';
      var signature = "6yQRl17CNj5YSHSpF+tLjb0vVsNVEv021Tyy1bTVEQ69SWlmhwmJYuMc7jiDyeW9TLy4vRqSh4g4YEyN8eoQIM57pMoNw6Lw6Oudubqwp+E3cKtLFxW0l18db3Z/vhxn5BScAutHWwT/XrmkCNaHyCsvOOGMekwrNO7mxX9QIx21FBaEejJeviSYrF8bG6MbmFEs2VGKSybf9YrElR8BxxNe/uNfCXN3P5tO8MgR5wlL3Kr4yq8e6i4WWJgD08IVTnrSnoZR6v8JkPA+fn7I0M6cy0Xzw3BRMJAvdQB97wkobu97gFqJFKsOH2u/JR1S/UNP26vL0mzuAVuKAUwlRn0SUhWEAgcM3X0UCtWLYfCIb5QqrSHwlp7lwOkVnFt329Mrpjy+jAfYYSRqzIsw4ZsRRVauy/v3CvmjPI9sUKiJ5l1FSgkpK2lkjhFgKB3WaYZWy9ZfIAI9bDyG8vSTT7IDurlUhyTweDqVNlYUsO6jaUa4KmSpg1o9eIeHxm0XBQ2c0Lv/T39KNc/VOAi1LBfPiQYMXD1e/8VuPPBTDGgzOMD3i334ppSr36+8YtApAn3D36Hr9jqAfFrugM7uPecjCGuleWsHFyNnJErT0/amIt24Nh1GoiESEq42o7Co4wZieKZ+/yeAlIUErJzK41ACVGmTnGoDUwEBXxADOdA=";
      assert(!client.verifyCallback(body, signature))
    });
  });
});


text:
@implementation NSString (DDNAHelpers)

+ (BOOL) stringIsNilOrEmpty: (NSString*) aString
{
    return !(aString && aString.length);
}

+ (NSString *) jsonStringWithContentsOfDictionary: (NSDictionary *) aDictionary
{
    NSString * result = nil;
    NSError * error = nil;
    NSData * data = [NSJSONSerialization dataWithJSONObject:aDictionary
                                                    options:kNilOptions
                                                      error:&error];
    if (error == 0)
    {
        result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    }

    return result;
}

- (NSString *) md5
{
    if (!self) return nil;

    const char* str = [self UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (CC_LONG)strlen(str), result);

    NSMutableString *ret = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH*2];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [ret appendFormat:@"%02x", result[i]];
    }
    return ret;
}

@end


text:
const yaml = require('js-yaml');
const path = require('path');
const fs = require('fs').promises;

const {dirExists} = require('lib/util/fileutil');

const isArray = item => {
  return item instanceof Array;
};
const isString = item => {
  return typeof item === 'string';
};
const isObject = item => {
  return typeof item === 'object' && !isArray(item);
};

// Add more items here, when support for them is added:
const handledKeys = [
  'src_dirs', 'theme_names', 'packages', 'gfx_formats',
  'themes_require', 'env'];
const configParsers = (config, filePath) => {
  const handleConfigItemArray = (source, destination, descr) => {
    // handles special items in config arrays:
    const handleArrayDirective = directives => {
      // deletes items from arr:
      const deleteFromArray = itemsToDelete => {
        if (isString(itemsToDelete)) {
          itemsToDelete = [itemsToDelete];
        }
        else if (!isArray(itemsToDelete)) {
          console.warn(`invalid format of items to delete in ${descr}:`, itemsToDelete);
        }
        destination = destination.filter(item => {
          return !(itemsToDelete.includes(item));
        });
      };
      const isPackage = descr.startsWith('packages.');
      const convertFileToPackage = fileName => {
        config.files[fileName] = {
          isFound: false,
          src: ''
        };
        destination.push(fileName);
      };
      Object.entries(directives)
        .forEach(([cmd, props]) => {
          if (cmd === 'delete') {
            deleteFromArray(props);
          }
          else if (isPackage && cmd === 'file') {
            convertFileToPackage(props);
          }
          else {
            console.warn(
              `invalid directive in ${descr}: '${cmd}'; `, props);
          }
        });
      return destination;
    };
    source.forEach(item => {
      if (typeof item === 'string') {
        destination.push(item);
      }
      else if (isObject(item)) {
        destination = handleArrayDirective(item, 'theme_names');
      }
      else {
        console.warn(`invalid item in '${descr}': `, item);
      }
    });
    return destination;
  };
  const configDir = path.dirname(filePath);
  return {
    'src_dirs': srcDirs => {
      srcDirs.forEach(srcDir => {
        const srcPath = path.resolve(configDir, srcDir);
        if (dirExists(srcPath)) {
          config.srcDirs.push(srcPath);
        }
        else {
          console.warn(`invalid item in src_dirs: '${srcPath}'`);
        }
      });
    },
    'theme_names': themeNames => {
      config.themeNames = handleConfigItemArray(
        themeNames, config.themeNames, 'theme_names');
    },
    'packages': packages => {
      Object.entries(packages).forEach(([name, items]) => {
        const destination = config.packages[name] || [];
        config.packages[name] = handleConfigItemArray(
          items, destination, `packages.${name}`);
      });
    },
    'gfx_formats': gfxFormats => {
      config.gfxFormats = handleConfigItemArray(
        gfxFormats, config.gfxFormats, 'gfx_formats');
    },
    'themes_require': themesRequire => {
      Object.entries(themesRequire)
        .forEach(([themeName, requireItems]) => {
          if (!config.themesRequire[themeName]) {
            config.themesRequire[themeName] = {__order: []};
          }
          const themeRequire = config.themesRequire[themeName];
          requireItems.forEach(requireItem => {
            Object.entries(requireItem)
              .forEach(([constName, requirePath]) => {
                if (!themeRequire.__order.includes(constName)) {
                  themeRequire.__order.push(constName);
                  themeRequire[constName] = requirePath;
                }
              });
          });
        });
    },
    'env': envObj => {
      Object.entries(envObj)
        .forEach(([key, value]) => {
          config.env[key] = value;
        });
    }
  };
};

const readConfigFile = configFile => {
  return fs.readFile(configFile)
    .then(yamlSrc => {
      return yaml.load(yamlSrc);
    }, err => {
      console.error('Unable to read config, because:', err);
    })
    .then(config => {
      config._filePath = configFile;
      return config;
    });
};

const readConfig = configFiles => {
  return Promise
    .all(configFiles.map(readConfigFile))
    .then(configs => {
      const parsedConfig = {
        srcDirs: [],
        themeNames: [],
        packages: {},
        gfxFormats: [],
        themesRequire: {},
        env: {},
        files: {}
      };
      configs.forEach(config => {
        const parsers = configParsers(parsedConfig, config._filePath);
        Object.entries(config).forEach(([key, val]) => {
          if (key.startsWith(':')) {
            key = key.slice(1); // older ruby-parsed ones had symbols
          }
          if (handledKeys.includes(key)) {
            parsers[key](val);
          }
        });
      });
      return parsedConfig;
    }
  );
};

module.exports = readConfig;


text:
package org.colapietro.mail;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author Pete Colapietro
 */
public class SimplerMailMessageClient {

  public static void main(String args[]) {
    final String simpleMailConfigurationFile = "mail-bean.xml";
    final ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(simpleMailConfigurationFile);
    final SimplerMailMessage peteEmailAPI = (SimplerMailMessage) context.getBean("peteEmail");
    peteEmailAPI.sendEmail();
  }
}


text:
/**
 * @provides phui-calendar-css
 */

.phui-calendar-list {
  /* When hovering over a day, this allows the hover color to peek through
     the event name, but for event names to mostly remain readable. */

}

.application-search-view div.phui-calendar-box {
  border-left: 1px solid {$thinblueborder};
  border-right: 1px solid {$thinblueborder};
  border-bottom: 1px solid {$lightblueborder};
  border-radius: 0;
}

.phui-calendar-list a {
  color: {$greytext};
}

.phui-calendar-list .event-cancelled .phui-calendar-list-title {
  text-decoration: line-through;
}

.phui-calendar-viewer-invited a {
  color: {$green};
}

.phui-calendar-red a {
  color: {$red};
}

.phui-calendar-orange a {
  color: {$orange};
}

.phui-calendar-yellow a {
  color: {$yellow};
}

.phui-calendar-green a {
  color: {$green}
}

.phui-calendar-blue a {
  color: {$blue};
}

.phui-calendar-sky a {
  color: {$sky};
}

.phui-calendar-indigo a {
  color: {$indigo};
}

.phui-calendar-violet a {
  color: {$violet};
}

.phui-calendar-grey a {
  color: {$lightgreytext};
}

.phui-calendar-bg-viewer-invited {
  background-color: {$lightgreen};
}

.phui-calendar-bg-red {
  background-color: {$lightred};
}

.phui-calendar-bg-orange {
  background-color: {$lightorange};
}

.phui-calendar-bg-yellow {
  background-color: {$lightyellow};
}

.phui-calendar-bg-green {
  background-color: {$lightgreen};
}

.phui-calendar-bg-blue {
  background-color: {$lightblue};
}

.phui-calendar-bg-sky {
  background-color: {$lightsky};
}

.phui-calendar-bg-indigo {
  background-color: {$lightindigo};
}

.phui-calendar-bg-violet {
  background-color: {$lightviolet};
}

.phui-calendar-bg-grey {
  background-color: {$darkgreybackground};
}

.phui-calendar-list-dot {
  background-color: {$lightgreytext};
  border-color: {$lightgreytext};
}

.phui-calendar-viewer-invited .phui-calendar-list-dot {
  background-color: {$green};
  border-color: {$green};
}

.phui-calendar-red .phui-calendar-list-dot {
  background-color: {$red};
  border-color: {$red};
}

.phui-calendar-orange .phui-calendar-list-dot {
  background-color: {$orange};
  border-color: {$orange};
}

.phui-calendar-yellow .phui-calendar-list-dot {
  background-color: {$orange};
  border-color: {$orange};
}

.phui-calendar-green .phui-calendar-list-dot {
  background-color: {$green};
  border-color: {$green};
}

.phui-calendar-blue .phui-calendar-list-dot {
  background-color: {$blue};
  border-color: {$blue};
}

.phui-calendar-sky .phui-calendar-list-dot {
  background-color: {$sky};
  border-color: {$sky};
}

.phui-calendar-indigo .phui-calendar-list-dot {
  background-color: {$indigo};
  border-color: {$indigo};
}

.phui-calendar-violet .phui-calendar-list-dot {
  background-color: {$violet};
  border-color: {$violet};
}

.phui-calendar-grey .phui-calendar-list-dot {
  background-color: {$lightgreytext};
  border-color: {$lightgreytext};
}


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

namespace Lab2_Library
{
    class SciFi : Book
    {
        public SciFi(string title) : base(title)
        {
            base.Author = new Person("Isaac Asimov", 72);
        }
    }
}


text:
package org.bouncycastle.crypto.test;

import java.security.SecureRandom;

import org.bouncycastle.asn1.sec.SECNamedCurves;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
import org.bouncycastle.crypto.SecretWithEncapsulation;
import org.bouncycastle.crypto.digests.SHA1Digest;
import org.bouncycastle.crypto.generators.ECKeyPairGenerator;
import org.bouncycastle.crypto.generators.KDF2BytesGenerator;
import org.bouncycastle.crypto.kems.ECIESKEMExtractor;
import org.bouncycastle.crypto.kems.ECIESKEMGenerator;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECKeyGenerationParameters;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.util.test.SimpleTest;

/**
 * Tests for the ECIES Key Encapsulation Mechanism
 */
public class ECIESKeyEncapsulationTest
    extends SimpleTest
{
    public String getName()
    {
        return "ECIESKeyEncapsulation";
    }

    public void performTest()
        throws Exception
    {

        // Set EC domain parameters and generate key pair
        X9ECParameters            spec     = SECNamedCurves.getByName("secp224r1");
        ECDomainParameters        ecDomain = new ECDomainParameters(spec.getCurve(), spec.getG(), spec.getN());
        ECKeyPairGenerator        ecGen    = new ECKeyPairGenerator();

        ecGen.init(new ECKeyGenerationParameters(ecDomain, new SecureRandom()));

        AsymmetricCipherKeyPair    keys      = ecGen.generateKeyPair();

        // Set ECIES-KEM parameters
        ECIESKEMGenerator kemGen;
        ECIESKEMExtractor kemExt;
        KDF2BytesGenerator        kdf = new KDF2BytesGenerator(new SHA1Digest());
        SecureRandom            rnd = new SecureRandom();
        byte[]                    out = new byte[57];
        KeyParameter            key1, key2;

        // Test basic ECIES-KEM
        kemGen = new ECIESKEMGenerator(128 / 8, kdf, rnd);

        SecretWithEncapsulation secEnc = kemGen.generateEncapsulated(keys.getPublic());

        key1 = new KeyParameter(secEnc.getSecret());

        kemExt = new ECIESKEMExtractor((ECPrivateKeyParameters)keys.getPrivate(), 128 / 8, kdf);

        key2 = new KeyParameter(kemExt.extractSecret(secEnc.getEncapsulation()));

        if (!areEqual(key1.getKey(), key2.getKey()))
        {
            fail("failed basic test");
        }

        // Test ECIES-KEM using new cofactor mode
        kemGen = new ECIESKEMGenerator(128 / 8, kdf, rnd, true, false, false);

        secEnc = kemGen.generateEncapsulated(keys.getPublic());

        key1 = new KeyParameter(secEnc.getSecret());

        kemExt = new ECIESKEMExtractor((ECPrivateKeyParameters)keys.getPrivate(), 128 / 8, kdf, true, false, false);

        key2 = new KeyParameter(kemExt.extractSecret(secEnc.getEncapsulation()));

        if (!areEqual(key1.getKey(), key2.getKey()))
        {
            fail("failed cofactor test");
        }
        // Test ECIES-KEM using old cofactor mode
        kemGen = new ECIESKEMGenerator(128 / 8, kdf, rnd, false, true, false);

        secEnc = kemGen.generateEncapsulated(keys.getPublic());

        key1 = new KeyParameter(secEnc.getSecret());

        kemExt = new ECIESKEMExtractor((ECPrivateKeyParameters)keys.getPrivate(), 128 / 8, kdf, false, true, false);

        key2 = new KeyParameter(kemExt.extractSecret(secEnc.getEncapsulation()));

        if (!areEqual(key1.getKey(), key2.getKey()))
        {
            fail("failed old cofactor test");
        }

        // Test ECIES-KEM using single hash mode
        kemGen = new ECIESKEMGenerator(128 / 8, kdf, rnd, false, false, true);

        secEnc = kemGen.generateEncapsulated(keys.getPublic());

        key1 = new KeyParameter(secEnc.getSecret());

        kemExt = new ECIESKEMExtractor((ECPrivateKeyParameters)keys.getPrivate(), 128 / 8, kdf, false, false, true);

        key2 = new KeyParameter(kemExt.extractSecret(secEnc.getEncapsulation()));

        if (!areEqual(key1.getKey(), key2.getKey()))
        {
            fail("failed single hash test");
        }

        // Test ECIES-KEM using new cofactor mode and single hash mode
        kemGen = new ECIESKEMGenerator(128 / 8, kdf, rnd, true, false, true);

        secEnc = kemGen.generateEncapsulated(keys.getPublic());

        key1 = new KeyParameter(secEnc.getSecret());

        kemExt = new ECIESKEMExtractor((ECPrivateKeyParameters)keys.getPrivate(), 128 / 8, kdf, true, false, true);

        key2 = new KeyParameter(kemExt.extractSecret(secEnc.getEncapsulation()));

        if (!areEqual(key1.getKey(), key2.getKey()))
        {
            fail("failed cofactor and single hash test");
        }

        // Test ECIES-KEM using old cofactor mode and single hash mode
        kemGen = new ECIESKEMGenerator(128 / 8, kdf, rnd, false, true, true);

        secEnc = kemGen.generateEncapsulated(keys.getPublic());

        key1 = new KeyParameter(secEnc.getSecret());

        kemExt = new ECIESKEMExtractor((ECPrivateKeyParameters)keys.getPrivate(), 128 / 8, kdf, false, true, true);

        key2 = new KeyParameter(kemExt.extractSecret(secEnc.getEncapsulation()));

        if (!areEqual(key1.getKey(), key2.getKey()))
        {
            fail("failed old cofactor and single hash test");
        }
    }

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


text:
title: "Compress"
description: "Compression Remote"
---

{{< icon "fas fa-compress" >}}Compress (Experimental)
-----------------------------------------

The `Compress` remote adds compression to another remote. It is best used with remotes containing
many large compressible files.

Please read the [warnings](#warnings) before using this remote.

To use this remote, all you need to do is specify another remote and a compression mode to use:

```
Current remotes:

Name                 Type
====                 ====
remote_to_press      sometype

e) Edit existing remote
$ rclone config
n) New remote
d) Delete remote
r) Rename remote
c) Copy remote
s) Set configuration password
q) Quit config
e/n/d/r/c/s/q> n
name> compress
...
 8 / Compress a remote
   \ "compress"
...
Storage> compress
** See help for compress backend at: https://rclone.org/compress/ **

Remote to compress.
Enter a string value. Press Enter for the default ("").
remote> remote_to_press:subdir
Compression mode.
Enter a string value. Press Enter for the default ("gzip").
Choose a number from below, or type in your own value
 1 / Gzip compression balanced for speed and compression strength.
   \ "gzip"
compression_mode> gzip
Edit advanced config? (y/n)
y) Yes
n) No (default)
y/n> n
Remote config
--------------------
[compress]
type = compress
remote = remote_to_press:subdir
compression_mode = gzip
--------------------
y) Yes this is OK (default)
e) Edit this remote
d) Delete this remote
y/e/d> y
```

### Compression Modes
Currently only gzip compression is supported, it provides a decent balance between speed and strength and is well
supported by other application. Compression strength can further be configured via an advanced setting where 0 is no
compression and 9 is strongest compression.

#### Filetype
If you open a remote wrapped by press, you will see that there are many files with an extension corresponding to
the compression algorithm you chose. These files are standard files that can be opened by various archive programs,
but they have some hidden metadata that allows them to be used by rclone.
While you may download and decompress these files at will, do **not** manually delete or rename files. Files without
correct metadata files will not be recognized by rclone.

### File names

The compressed files will be named `*.###########.gz` where `*` is the base file and the `#` part is base64 encoded
size of the uncompressed file. The file names should not be changed by anything other than the rclone compression backend.

#### Experimental
This remote is currently **experimental**. Things may break and data may be lost. Anything you do with this remote is
at your own risk. Please understand the risks associated with using experimental code and don't use this remote in
critical applications.

{{< rem autogenerated options start" - DO NOT EDIT - instead edit fs.RegInfo in backend/compress/compress.go then run make backenddocs" >}}
### Standard Options

Here are the standard options specific to compress (Compress a remote).

#### --compress-remote

Remote to compress.

- Config:      remote
- Env Var:     RCLONE_COMPRESS_REMOTE
- Type:        string
- Default:     ""

#### --compress-mode

Compression mode.

- Config:      mode
- Env Var:     RCLONE_COMPRESS_MODE
- Type:        string
- Default:     "gzip"
- Examples:
    - "gzip"
        - Standard gzip compression with fastest parameters.

### Advanced Options

Here are the advanced options specific to compress (Compress a remote).

#### --compress-level

GZIP compression level (-2 to 9).

			Generally -1 (default, equivalent to 5) is recommended.
			Levels 1 to 9 increase compressiong at the cost of speed.. Going past 6
			generally offers very little return.

			Level -2 uses Huffmann encoding only. Only use if you now what you
			are doing
			Level 0 turns off compression.

- Config:      level
- Env Var:     RCLONE_COMPRESS_LEVEL
- Type:        int
- Default:     -1

{{< rem autogenerated options stop >}}


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use dosamigos\ckeditor\CKEditor;
use backend\modules\worlds\category\models\Category;
use backend\modules\worlds\rate\models\Rate;
use backend\modules\worlds\status\models\Status;
use dosamigos\selectize\SelectizeTextInput;
/* @var $this yii\web\View */
/* @var $model backend\modules\article\models\Article */
/* @var $form yii\widgets\ActiveForm */
?>

<?= Html::encode($this->title) ?>

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'headline')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'content')->widget(CKEditor::className(), [
        'options' => ['rows' => 6],
        'preset' => 'basic'
    ]) ?>

    <?= $form->field($model, 'tags')->widget(SelectizeTextInput::className(), [

                    'clientOptions' => [ 'plugins' => ['remove_button'],
                      'create' => true,
                     ],
                     ])
                     ->hint('กรอกได้มากกว่า 1 คำค้น')
                     ?>

    <?= $form->field($model, 'rate_id')->dropDownList(
     ArrayHelper::map(Rate::find()->all(),'id','rate_name'),
     ['prompt'=>'เลือก ระดับ']
    ) ?>

    <?= $form->field($model, 'category_id')->dropDownList(
     ArrayHelper::map(Category::find()->where(['world_id'=>2])->all(),'id','title'),
     ['prompt'=>'เลือกหมวดหมู่']
    ) ?>
    <?php if(!$model->isNewRecord){?>
   <?=   Html::img('uploads/coverimage/'.$model->coverImg['filename'], ['width' => '200px']);?>

   <?php }?>
     <?= $form->field($modelimg, 'cover')->fileInput() ?>

        <?= Html::submitButton($model->isNewRecord ? 'เพิ่ม' : 'บันทึก', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-success']) ?>

    <?php ActiveForm::end(); ?>