text:
require 'spec_helper'

describe BlogPostsController do

  describe "#show" do
    #TODO add some tests
  end

  describe "#new" do

    context 'LeanLaunchLab project' do
      before do
        project = create_lll_project
        @owner = project.members.first
        sign_in @owner.user
      end

      after do
        sign_out @owner.user
      end

      it 'does not assign LLL in the projects if member is Normal' do
        @owner.update_attribute(:level, 'Normal')
        get :new, :project_id => @owner.project_id
        response.should be_redirect
      end

      it 'assigns LLL in the projects' do
        get :new, :project_id => @owner.project_id
        assigns[:projects].should include @owner.project
      end

    end

    context 'project other than LeanLaunchLab' do

      before do
        @owner = Factory(:owner)
      end

      context 'authenticated user who is a member of the project' do
        before do
          sign_in @owner.user
        end

        it 'should render new' do
          get :new, :project_id => @owner.project_id
          response.should render_template("new")
        end

        it 'assigns @blog_post' do
          pending "do this once we deliver NSF"
          # TODO:  essentially, don't we need coverage for this line of code:
          # @blog_post.post_items.build (from the controller)
        end

        it 'assigns key learnings' do
          get :new, :project_id => @owner.project_id
          assigns[:learnings].should == ""
        end

        it 'assigns projects' do
          get :new, :project_id => @owner.project_id
          assigns[:projects].should_not be_nil
          assigns[:projects].first.should be_kind_of(Project)
        end

        it 'assigns project' do
          get :new, :project_id => @owner.project_id
          assigns[:project].should == @owner.project
        end

        it 'assigns no_project' do
          get :new, :project_id => @owner.project_id
          assigns[:no_project].should be_false
          get :new, :project_id => @owner.project_id, :all_projects => 'true'
          assigns[:no_project].should be_true
        end

        it "assigns 'associated_file_ids' as a session variable" do
          get :new, :project_id => @owner.project_id

          session[:associated_file_ids].should == []
        end
      end

      context 'authenticated user who has been invited to the project, but has not joined' do

        before do
          member = Factory(:member_with_confirmed_user, :project => @owner.project)
          sign_in member.user
        end

        it 'should redirect to the user page' do
          get :new, :project_id => @owner.project_id
          response.should redirect_to current_user_path
        end
      end

      context 'authenticated user who was a member of the project but was deactivated' do

        before do
          member = Factory(:member_with_confirmed_user, :project => @owner.project)
          member.deactivate
          sign_in member.user
        end

        it 'should redirect to the user page' do
          get :new, :project_id => @owner.project_id
          response.should redirect_to current_user_path
        end
      end

      context 'authenticated user who is NOT a member of the project' do

        before do
          sign_in @owner.user
        end

        it 'should redirect to the user page' do
          owner2 = Factory(:owner)
          get :new, :project_id => owner2.project_id
          response.should redirect_to current_user_path
        end
      end

      context 'un-authenticated user' do
        it 'should redirect to the login screen' do
          get :new, :project_id => @owner.project_id
          response.should redirect_to new_user_session_path
        end
      end
    end
  end

  describe "save_draft" do
    before do
      @owner = Factory(:owner)
      @parameters = {"blog_post" => {"subject" => "My test blog post", "body" => "this is a short blog post", "the_ask" => "Just FYI"},
                     "project_id" => @owner.project_id, :draft => '1'}
    end

    context 'authenticated user who is a member of the project' do

      context "level is admin" do
        before do
          sign_in @owner.user
        end

        it "saves a blog_post draft with valid params" do
          expect { post :create, @parameters }.should change { BlogPost.draft.count }.by(1)
        end

        it "saves a blog_post draft with minimal (invalid) params" do
          expect { post :create, {:draft => '1', "project_id" => @owner.project_id} }.should change { BlogPost.draft.count }.by(1)
        end

        ['body', 'the_ask', 'subject'].each do |attr|
          it "saves with just draft, project_id and #{attr}" do
            post :create, {:draft => '1', "project_id" => @owner.project_id, attr => 'TEST'}
            BlogPost.last[attr].should == 'TEST'
          end
        end

        it "keeps published_at nil" do
          post :create, {"project_id" => @owner.project_id, :draft => '1'}
          BlogPost.last.should be_present
          BlogPost.last.published_at.should be_nil
        end
      end
    end
  end

  describe "#create" do

    before do
      @owner = Factory(:owner)
      @parameters = {"blog_post" => {"subject" => "My test blog post", "body" => "this is a short blog post", "the_ask" => "Just FYI"},
                     "project_id" => @owner.project_id}
    end

    context 'authenticated user who is a member of the project' do

      context "level is admin" do
        before do
          sign_in @owner.user
        end

        it "should create a new BlogPost" do
          expect { post :create, @parameters }.should change { BlogPost.count }.by(1)
        end

        it "sets published_at" do
          post :create, @parameters
          BlogPost.last.published_at.to_i.should be_present
          BlogPost.last.published_at.to_i.should be_within(5).of(Time.now.to_i)
          BlogPost.last.date.should == BlogPost.last.published_at.in_time_zone("Pacific Time (US & Canada)").to_date
        end

        it "creates a PostItem if nested attributes passed for it" do
          canvas_item = Factory(:canvas_item, :project => @owner.project)
          canvas_item2 = Factory(:canvas_item, :project => @owner.project)
          @parameters["blog_post"][:post_items_attributes] = {"0" => {:canvas_item_id => canvas_item.id},
                                                              "1" => {:canvas_item_id => canvas_item2.id}}
          expect { post :create, @parameters }.should change { PostItem.count }.by(2)
        end

        it "creates a UserActivity record" do
          expect { post :create, @parameters }.should change(UserActivity, :count).by(1)
          blog_post = BlogPost.last
          user_activity = UserActivity.last
          user_activity.description.should == "#{@owner.user.name} created blog post in #{@owner.project.name}"
          user_activity.action.should == "Create blog post"
          user_activity.member.should == @owner
        end

        it 'should print flash message on success' do
          post :create, @parameters
          flash[:notice].should == "Blog post created successfully"
        end

        it 'should redirect to project page' do
          post :create, @parameters
          response.should redirect_to project_path(@owner.project)
        end

        it 'should create learnings from the learnings param' do
          params = @parameters.merge(:learnings => "Learning 1\r\n Learning 2")
          expect { post :create, params }.should change { Learning.count }.by(2)
        end

        it "assigns the id of the blog post into the 'assetable_id' column of the picture model (ckeditor_assets table)" do
          picture = Factory(:picture)
          session[:associated_file_ids] = [picture.id]
          post :create, @parameters
          picture.reload
          picture.assetable_id.should == BlogPost.last.id
          picture.assetable_type.should == "BlogPost"
        end
      end

      context "level is Normal" do
        before do
          member = Factory(:member_who_has_joined_project, :project => @owner.project, :level => "Normal")
          sign_in member.user
        end

        it "Normal level members should create a new BlogPost" do
          expect { post :create, @parameters }.should change { BlogPost.count }.by(1)
        end
      end

      context "level is Viewer" do
        before do
          member = Factory(:member_who_has_joined_project, :project => @owner.project, :level => 'Viewer')
          sign_in member.user
        end

        it "should NOT create a new BlogPost" do
          expect { post :create, @parameters }.should_not change { BlogPost.count }
        end
      end

      context 'authenticated user who is NOT a member of the project' do
        it 'should redirect to the user page' do
          sign_in @owner.user
          someone_elses_project = Factory(:project)
          parameters = {"blog_post" => {"subject" => "My test blog post", "body" => "this is a short blog post"}, "project_id" => someone_elses_project.id}
          post :create, parameters
          response.should redirect_to current_user_path
        end
      end

      context 'un-authenticated user' do
        it 'should redirect to the login screen' do
          post :create, @parameters
          response.should redirect_to new_user_session_path
        end
      end

    end
  end

  describe "#edit" do

    before do
      @owner = Factory(:owner)
      @blog_post = Factory(:blog_post, :member => @owner)
      @project = @owner.project
    end

    context 'authenticated user who is a member of the project' do
      before do
        sign_in @owner.user
      end

      it 'should render edit' do
        get :edit, :project_id => @project.id, :id => @blog_post.id
        response.should render_template("edit")
      end

      it 'should not render edit for a blog post that does not belong to this project' do
        owner2 = Factory(:owner)
        blog_post2 = Factory(:blog_post, :member => owner2)
        get :edit, :project_id => @project.id, :id => blog_post2.id
        response.should_not render_template("edit")
      end

      it 'assigns key learnings' do
        learning1 = Factory(:learning, :blog_post => @blog_post, :content => "People like turtles")
        learning2 = Factory(:learning, :blog_post => @blog_post, :content => "People really like turtles")
        get :edit, :project_id => @project.id, :id => @blog_post.id

        assigns[:learnings].should == "People like turtles\r\nPeople really like turtles"
      end

      it 'assigns project' do
        get :edit, :project_id => @project.id, :id => @blog_post.id
        assigns[:project].should == @project
      end

      it 'assigns projects' do
        get :edit, :project_id => @project.id, :id => @blog_post.id
        assigns[:projects].should_not be_nil
        assigns[:projects].first.should be_kind_of(Project)
      end

      it 'assigns all_projects' do
        get :edit, :project_id => @owner.project_id, :id => @blog_post.id
        assigns[:no_project].should be_false
        get :edit, :project_id => @owner.project_id, :id => @blog_post.id, :all_projects => 'true'
        assigns[:no_project].should be_true
      end

      it "assigns 'associated_file_ids' as a session variable" do
        get :new, :project_id => @owner.project_id

        session[:associated_file_ids].should == []
      end
    end

    context 'authenticated user who has been invited to the project, but has not joined' do

      before do
        member = Factory(:member_with_confirmed_user, :project => @owner.project)
        sign_in member.user
      end

      it 'should redirect to the user page' do
        get :edit, :project_id => @project.id, :id => @blog_post.id
        response.should redirect_to current_user_path
      end
    end

    context 'authenticated user who was a member of the project but was deactivated' do

      before do
        member = Factory(:member_with_confirmed_user, :project => @owner.project)
        member.deactivate
        sign_in member.user
      end

      it 'should redirect to the user page' do
        get :edit, :project_id => @project.id, :id => @blog_post.id
        response.should redirect_to current_user_path
      end
    end

    context 'authenticated user who is NOT a member of the project' do

      before do
        sign_in @owner.user
      end

      it 'should redirect to the user page' do
        owner2 = Factory(:owner)
        blog_post2 = Factory(:blog_post, :member => owner2)
        get :edit, :project_id => owner2.project.id, :id => blog_post2.id
        response.should redirect_to current_user_path
      end
    end

    context 'un-authenticated user' do
      it 'should redirect to the login screen' do
        get :edit, :project_id => @project.id, :id => @blog_post.id
        response.should redirect_to new_user_session_path
      end
    end

  end

  describe "#update" do

    before do
      @owner = Factory(:owner)
      @blog_post = Factory(:blog_post, :member => @owner)
      @parameters = {"blog_post" => {"subject" => "My updated subject", "body" => "updated body"}, "project_id" => @owner.project_id, "id" => @blog_post.id}
    end

    context 'authenticated user who is a member of the project' do

      context "level is Admin" do
        before do
          sign_in @owner.user
        end

        it "should update BlogPost" do
          put :update, @parameters
          @blog_post.reload
          @blog_post.subject.should == @parameters['blog_post']['subject']
          @blog_post.body.should == @parameters['blog_post']['body']
        end

        it "does not increase count of associated canvas items when params contain already associated items" do
          canvas_item = Factory(:canvas_item)
          @parameters["blog_post"][:post_items_attributes] = {"0" => {:canvas_item_id => canvas_item.id}}
          put :update, @parameters
          put :update, @parameters
          @blog_post.reload
          @blog_post.post_items.count.should == 1
        end

        it 'should not update a blog post that does not belong to this project' do
          owner2 = Factory(:owner)
          blog_post2 = Factory(:blog_post, :member => owner2)
          parameters = {"blog_post" => {"subject" => "My updated subject", "body" => "updated body", "project_id" => @owner.project_id}, "project_id" => @owner.project_id, "id" => blog_post2.id}
          put :update, parameters
          blog_post2.reload
          blog_post2.subject.should_not == parameters['blog_post']['subject']
          blog_post2.body.should_not == parameters['blog_post']['body']
        end

        it "assigns the id of the blog post into the 'assetable_id' column of the picture model (ckeditor_assets table)" do
          picture = Factory(:picture)
          session[:associated_file_ids] = [picture.id]
          put :update, @parameters
          picture.reload
          picture.assetable_id.should == BlogPost.last.id
          picture.assetable_type.should == "BlogPost"
        end

        describe "updating drafts" do
          before { @blog_post.update_attribute(:published_at, nil) }

          ['subject', 'body'].each do |key|
            it "updates with required param #{key} missing if draft" do
              @parameters['blog_post'][key] = nil
              @parameters['draft'] = 1
              put :update, @parameters
              @blog_post.reload
              @blog_post[key].should be_nil
            end
          end
        end

        describe "publishing" do
          before do
            #make a member to receive mail
            Factory(:member_who_has_joined_project, :project => @owner.project, :level => 'Admin')
          end

          it "sends an email when publishing a draft" do
            @blog_post.update_attribute(:published_at, nil)
            message = double
            message.should_receive(:deliver)
            BlogPostMailer.should_receive(:mail_contents_of_blog_post).and_return(message)
            put :update, @parameters
          end

          it "does not send email when updating an already published blog post" do
            BlogPostMailer.should_not_receive(:mail_contents_of_blog_post)
            put :update, @parameters
          end
        end
      end

      context "permission level Normal" do
        before do
          member = Factory(:member_who_has_joined_project, :project => @owner.project, :level => "Normal")
          sign_in member.user
        end

        it "level of Normal should update a BlogPost" do
          put :update, @parameters
          @blog_post.reload
          @blog_post.subject.should == @parameters['blog_post']['subject']
          @blog_post.body.should == @parameters['blog_post']['body']
        end
      end

      context "permission level Viewer" do
        before do
          member = Factory(:member_who_has_joined_project, :project => @owner.project, :level => 'Viewer')
          sign_in member.user
        end

        it "should NOT update a BlogPost" do
          put :update, @parameters
          @blog_post.reload
          @blog_post.subject.should_not == @parameters['blog_post']['subject']
          @blog_post.body.should_not == @parameters['blog_post']['body']
        end
      end
      context 'authenticated user who is NOT a member of the project' do
        it 'should redirect to the user page' do
          sign_in @owner.user
          owner2 = Factory(:owner)
          blog_post2 = Factory(:blog_post, :member => owner2)
          parameters = {"blog_post" => {"subject" => "My test blog post", "body" => "this is a short blog post"}, "project_id" => owner2.project.id, "id" => blog_post2.id}

          put :update, parameters
          response.should redirect_to current_user_path
        end
      end

      context 'un-authenticated user' do
        it 'should redirect to the login screen' do
          put :update, @parameters
          response.should redirect_to new_user_session_path
        end
      end

    end
  end

  describe "#delete" do
    before do
      @user = Factory(:confirmed_user)
    end

    context 'authenticated user' do

      before do
        sign_in @user
      end

      context 'user is member of project' do

        def setup_member_and_project level
          owner = Factory(:owner)
          member = Factory(:member_who_has_joined_project, :project => owner.project, :user => @user, :level => level)
          @project = member.project
          @member = member
        end

        describe 'permission level restriction' do
          %w(Admin Normal Viewer).each do |level|
            context "level is #{level}" do
              before do
                setup_member_and_project(level)
                @blog_post = Factory(:blog_post, :member => @member)
                @params = {:project_id => @project.id, :id => @blog_post.id}
              end

              if level == "Viewer"
                it 'should NOT delete the blog post' do
                  expect { delete :destroy, @params }.should_not change(BlogPost, :count)
                end

                it 'should redirect to the user page' do
                  delete :destroy, @params
                  response.should redirect_to current_user_path
                end
              else
                it 'should delete the blog post' do
                  expect { delete :destroy, @params }.should change(BlogPost, :count).by(-1)
                end

                it 'should redirect to the project page' do
                  delete :destroy, @params
                  response.should redirect_to project_path(@project)
                end
                it 'should set a flash message' do
                  delete :destroy, @params
                  flash[:notice].should =~ /deleted successfully/
                end
                it 'should not delete a blog post that does not belong to this project' do
                  blog_post2 = Factory(:blog_post)
                  delete :destroy, {:project_id => @project.id, :id => blog_post2.id}
                  expect { delete :destroy, @params }.should_not change(BlogPost, :count)
                  response.should redirect_to current_user_path
                end
              end
            end
          end
        end
      end

      context 'user is NOT member of project' do
        it 'should not delete' do
          owner2 = Factory(:owner)
          blog_post2 = Factory(:blog_post, :member => owner2)
          params = {:project_id => blog_post2.project.id, :id => blog_post2.id}
          expect { delete :destroy, params }.should_not change(BlogPost, :count)
          response.should redirect_to current_user_path
        end
      end
    end

    context 'un-authenticated user' do
      it 'should redirect to the login screen' do
        owner2 = Factory(:owner)
        blog_post2 = Factory(:blog_post, :member => owner2)
        params = {:project_id => blog_post2.project.id, :id => blog_post2.id}
        delete :destroy, params
        response.should redirect_to new_user_session_path
      end
    end
  end
end


text:
"""The multi-process worker process."""

from __future__ import unicode_literals

from dfvfs.lib import errors as dfvfs_errors
from dfvfs.resolver import context
from dfvfs.resolver import resolver

from plaso.engine import plaso_queue
from plaso.engine import worker
from plaso.lib import definitions
from plaso.lib import errors
from plaso.multi_processing import base_process
from plaso.multi_processing import logger
from plaso.parsers import mediator as parsers_mediator

class WorkerProcess(base_process.MultiProcessBaseProcess):
  """Class that defines a multi-processing worker process."""

  def __init__(
      self, task_queue, storage_writer, collection_filters_helper,
      knowledge_base, session_identifier, processing_configuration, **kwargs):
    """Initializes a worker process.

    Non-specified keyword arguments (kwargs) are directly passed to
    multiprocessing.Process.

    Args:
      task_queue (PlasoQueue): task queue.
      storage_writer (StorageWriter): storage writer for a session store.
      collection_filters_helper (CollectionFiltersHelper): collection filters
          helper.
      knowledge_base (KnowledgeBase): knowledge base which contains
          information from the source data needed for parsing.
      session_identifier (str): identifier of the session.
      processing_configuration (ProcessingConfiguration): processing
          configuration.
      kwargs: keyword arguments to pass to multiprocessing.Process.
    """
    super(WorkerProcess, self).__init__(processing_configuration, **kwargs)
    self._abort = False
    self._collection_filters_helper = collection_filters_helper
    self._buffer_size = 0
    self._current_display_name = ''
    self._extraction_worker = None
    self._knowledge_base = knowledge_base
    self._number_of_consumed_events = 0
    self._number_of_consumed_sources = 0
    self._parser_mediator = None
    self._session_identifier = session_identifier
    self._status = definitions.STATUS_INDICATOR_INITIALIZED
    self._storage_writer = storage_writer
    self._task = None
    self._task_queue = task_queue

  def _GetStatus(self):
    """Retrieves status information.

    Returns:
      dict[str, object]: status attributes, indexed by name.
    """
    if self._parser_mediator:
      number_of_produced_events = (
          self._parser_mediator.number_of_produced_events)
      number_of_produced_sources = (
          self._parser_mediator.number_of_produced_event_sources)
      number_of_produced_warnings = (
          self._parser_mediator.number_of_produced_warnings)
    else:
      number_of_produced_events = None
      number_of_produced_sources = None
      number_of_produced_warnings = None

    if self._extraction_worker and self._parser_mediator:
      last_activity_timestamp = max(
          self._extraction_worker.last_activity_timestamp,
          self._parser_mediator.last_activity_timestamp)
      processing_status = self._extraction_worker.processing_status
    else:
      last_activity_timestamp = 0.0
      processing_status = self._status

    task_identifier = getattr(self._task, 'identifier', '')

    if self._process_information:
      used_memory = self._process_information.GetUsedMemory() or 0
    else:
      used_memory = 0

    if self._memory_profiler:
      self._memory_profiler.Sample('main', used_memory)

    # XML RPC does not support integer values > 2 GiB so we format them
    # as a string.
    used_memory = '{0:d}'.format(used_memory)

    status = {
        'display_name': self._current_display_name,
        'identifier': self._name,
        'last_activity_timestamp': last_activity_timestamp,
        'number_of_consumed_event_tags': None,
        'number_of_consumed_events': self._number_of_consumed_events,
        'number_of_consumed_sources': self._number_of_consumed_sources,
        'number_of_consumed_warnings': None,
        'number_of_produced_event_tags': None,
        'number_of_produced_events': number_of_produced_events,
        'number_of_produced_sources': number_of_produced_sources,
        'number_of_produced_warnings': number_of_produced_warnings,
        'processing_status': processing_status,
        'task_identifier': task_identifier,
        'used_memory': used_memory}

    return status

  def _Main(self):
    """The main loop."""
    # We need a resolver context per process to prevent multi processing
    # issues with file objects stored in images.
    resolver_context = context.Context()

    for credential_configuration in self._processing_configuration.credentials:
      resolver.Resolver.key_chain.SetCredential(
          credential_configuration.path_spec,
          credential_configuration.credential_type,
          credential_configuration.credential_data)

    self._parser_mediator = parsers_mediator.ParserMediator(
        None, self._knowledge_base,
        collection_filters_helper=self._collection_filters_helper,
        preferred_year=self._processing_configuration.preferred_year,
        resolver_context=resolver_context,
        temporary_directory=self._processing_configuration.temporary_directory)

    # We need to initialize the parser and hasher objects after the process
    # has forked otherwise on Windows the "fork" will fail with
    # a PickleError for Python modules that cannot be pickled.
    self._extraction_worker = worker.EventExtractionWorker(
        parser_filter_expression=(
            self._processing_configuration.parser_filter_expression))

    self._extraction_worker.SetExtractionConfiguration(
        self._processing_configuration.extraction)

    self._parser_mediator.StartProfiling(
        self._processing_configuration.profiling, self._name,
        self._process_information)
    self._StartProfiling(self._processing_configuration.profiling)

    if self._analyzers_profiler:
      self._extraction_worker.SetAnalyzersProfiler(self._analyzers_profiler)

    if self._processing_profiler:
      self._extraction_worker.SetProcessingProfiler(self._processing_profiler)

    if self._serializers_profiler:
      self._storage_writer.SetSerializersProfiler(self._serializers_profiler)

    if self._storage_profiler:
      self._storage_writer.SetStorageProfiler(self._storage_profiler)

    logger.debug('Worker: {0!s} (PID: {1:d}) started.'.format(
        self._name, self._pid))

    self._status = definitions.STATUS_INDICATOR_RUNNING

    try:
      logger.debug('{0!s} (PID: {1:d}) started monitoring task queue.'.format(
          self._name, self._pid))

      while not self._abort:
        try:
          task = self._task_queue.PopItem()
        except (errors.QueueClose, errors.QueueEmpty) as exception:
          logger.debug('ConsumeItems exiting with exception: {0!s}.'.format(
              type(exception)))
          break

        if isinstance(task, plaso_queue.QueueAbort):
          logger.debug('ConsumeItems exiting, dequeued QueueAbort object.')
          break

        self._ProcessTask(task)

      logger.debug('{0!s} (PID: {1:d}) stopped monitoring task queue.'.format(
          self._name, self._pid))

    # All exceptions need to be caught here to prevent the process
    # from being killed by an uncaught exception.
    except Exception as exception:  # pylint: disable=broad-except
      logger.warning(
          'Unhandled exception in process: {0!s} (PID: {1:d}).'.format(
              self._name, self._pid))
      logger.exception(exception)

      self._abort = True

    if self._analyzers_profiler:
      self._extraction_worker.SetAnalyzersProfiler(None)

    if self._processing_profiler:
      self._extraction_worker.SetProcessingProfiler(None)

    if self._serializers_profiler:
      self._storage_writer.SetSerializersProfiler(None)

    if self._storage_profiler:
      self._storage_writer.SetStorageProfiler(None)

    self._StopProfiling()
    self._parser_mediator.StopProfiling()

    self._extraction_worker = None
    self._parser_mediator = None
    self._storage_writer = None

    if self._abort:
      self._status = definitions.STATUS_INDICATOR_ABORTED
    else:
      self._status = definitions.STATUS_INDICATOR_COMPLETED

    logger.debug('Worker: {0!s} (PID: {1:d}) stopped.'.format(
        self._name, self._pid))

    try:
      self._task_queue.Close(abort=self._abort)
    except errors.QueueAlreadyClosed:
      logger.error('Queue for {0:s} was already closed.'.format(self.name))

  def _ProcessPathSpec(self, extraction_worker, parser_mediator, path_spec):
    """Processes a path specification.

    Args:
      extraction_worker (worker.ExtractionWorker): extraction worker.
      parser_mediator (ParserMediator): parser mediator.
      path_spec (dfvfs.PathSpec): path specification.
    """
    self._current_display_name = parser_mediator.GetDisplayNameForPathSpec(
        path_spec)

    excluded_find_specs = None
    if self._collection_filters_helper:
      excluded_find_specs = (
          self._collection_filters_helper.excluded_file_system_find_specs)

    try:
      extraction_worker.ProcessPathSpec(
          parser_mediator, path_spec, excluded_find_specs=excluded_find_specs)

    except dfvfs_errors.CacheFullError:
      # TODO: signal engine of failure.
      self._abort = True
      logger.error((
          'ABORT: detected cache full error while processing path spec: '
          '{0:s}').format(self._current_display_name))

    except Exception as exception:  # pylint: disable=broad-except
      parser_mediator.ProduceExtractionWarning((
          'unable to process path specification with error: '
          '{0!s}').format(exception), path_spec=path_spec)

      if self._processing_configuration.debug_output:
        logger.warning((
            'Unhandled exception while processing path specification: '
            '{0:s}.').format(self._current_display_name))
        logger.exception(exception)

  def _ProcessTask(self, task):
    """Processes a task.

    Args:
      task (Task): task.
    """
    logger.debug('Started processing task: {0:s}.'.format(task.identifier))

    if self._tasks_profiler:
      self._tasks_profiler.Sample(task, 'processing_started')

    self._task = task

    task_storage_writer = self._storage_writer.CreateTaskStorage(
        task, self._processing_configuration.task_storage_format)

    if self._serializers_profiler:
      task_storage_writer.SetSerializersProfiler(self._serializers_profiler)

    task_storage_writer.Open()

    self._parser_mediator.SetStorageWriter(task_storage_writer)

    task_storage_writer.WriteTaskStart()

    try:
      # TODO: add support for more task types.
      self._ProcessPathSpec(
          self._extraction_worker, self._parser_mediator, task.path_spec)
      self._number_of_consumed_sources += 1

    finally:
      task_storage_writer.WriteTaskCompletion(aborted=self._abort)

      self._parser_mediator.SetStorageWriter(None)

      task_storage_writer.Close()

    try:
      self._storage_writer.FinalizeTaskStorage(task)
    except IOError:
      pass

    self._task = None

    if self._tasks_profiler:
      self._tasks_profiler.Sample(task, 'processing_completed')

    logger.debug('Completed processing task: {0:s}.'.format(task.identifier))

  def SignalAbort(self):
    """Signals the process to abort."""
    self._abort = True
    if self._extraction_worker:
      self._extraction_worker.SignalAbort()
    if self._parser_mediator:
      self._parser_mediator.SignalAbort()

redpajama_set_name: RedPajamaGithub


text:
package com.ukiy.module.updator.core;

import android.content.Context;
import android.content.Intent;

import com.ukiy.module.updator.core.callback.DownloadCallback;
import com.ukiy.module.updator.core.callback.SimpleDownloadCallback;
import com.ukiy.module.updator.core.callback.SimpleUpdateCallback;
import com.ukiy.module.updator.core.callback.UpdateCallback;

/**
 * Created by ukiy on 15/12/24.
 * 用于检查版本更新情况
 */
public class Updator {

    static String url;
    static String cur_version;
    private static boolean isInit = false;

    private Updator() {
    }

    public static void init(String cur_version, String url) {
        Updator.url = url;
        Updator.cur_version = cur_version;
        isInit = true;
    }

    public static String getCur_version() {
        return Updator.cur_version;
    }

    //向service发送检查更新的任务
    public static void getUpdateInfo(Context context, UpdateCallback updateCallback) {
        if (!isInit) {
            throw new RuntimeException("Updator is not yet init!");
        }
        Intent intent = new Intent(context, UpdateService.class);
        intent.putExtra(UpdateService.TYPE, UpdateService.GET_UPDATE_INFO);
        intent.putExtra(UpdateService.UPDATE_CALLBACK, updateCallback);
        context.startService(intent);
    }

    //向service发送下载并安装更新包的任务
    public static void downloadUpdateInfo(Context context, DownloadCallback downloadCallback) {
        if (!isInit) {
            throw new RuntimeException("Updator is not yet init!");
        }
        Intent intent = new Intent(context, UpdateService.class);
        intent.putExtra(UpdateService.TYPE, UpdateService.DOWNLOAD_UPDATE_FILE);
        intent.putExtra(UpdateService.DOWNLOAD_CALLBACK, downloadCallback);
        context.startService(intent);
    }

    public static void start(Context context) {
        if (!isInit) {
            throw new RuntimeException("Updator is not yet init!");
        }
        getUpdateInfo(context, new SimpleUpdateCallback(new SimpleDownloadCallback(), false));
    }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>O-Index</title>
<meta name="date" content="2014-08-14">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D E F G H I K L M N O P R S T V W X

O

OnVisited(EdgePath) - Method in interface de.general.graph.IEdgePathIterationDelegate

orderChildElements(Element, String[]) - Static method in class de.general.xml.XMLUtils

Bring the child elements in the specified XML element in the correct order by first removing
 them all and then adding them in the correct order.

ORIGINAL_SPACES - Static variable in class de.general.simpletokenizing.Tokenizer

A B C D E F G H I K L M N O P R S T V W X

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
"""managed-instance-groups list-instances command.

It's an alias for the instance-groups list-instances command.
"""
from googlecloudsdk.api_lib.compute import instance_groups_utils

class ListInstances(instance_groups_utils.InstanceGroupListInstances):
  pass


text:
var _imgInterval,
    _getTitle = function (item) {
      if (item.data && item.data.title !== undefined)
        return item.data.title;

      var src = mfp.st.image.titleSrc;

      if (src) {
        if ($.isFunction(src)) {
          return src.call(mfp, item);
        } else if (item.el) {
          return item.el.attr(src) || '';
        }
      }
      return '';
    };

  $.magnificPopup.registerModule('image', {

    options: {
      markup: '
' +
            '

' +
            '
' +
              '

' +
              '
' +
                '
' +
                  '

' +
                  '

' +
                '
' +
              '
' +
            '
' +
          '
',
      cursor: 'mfp-zoom-out-cur',
      titleSrc: 'data-title',
      verticalFit: true,
      tError: 'The image could not be loaded.'
    },

    proto: {
      initImage: function () {
        var imgSt = mfp.st.image,
          ns = '.image';

        mfp.types.push('image');

        _mfpOn(OPEN_EVENT + ns, function () {
          if (mfp.currItem.type === 'image' && imgSt.cursor) {
            $(document.body).addClass(imgSt.cursor);
          }
        });

        _mfpOn(CLOSE_EVENT + ns, function () {
          if (imgSt.cursor) {
            $(document.body).removeClass(imgSt.cursor);
          }
          _window.off('resize' + EVENT_NS);
        });

        _mfpOn('Resize' + ns, mfp.resizeImage);
        if (mfp.isLowIE) {
          _mfpOn('AfterChange', mfp.resizeImage);
        }
      },
      resizeImage: function () {
        var item = mfp.currItem;
        if (!item || !item.img) return;

        if (mfp.st.image.verticalFit) {
          var decr = 0;
          // fix box-sizing in ie7/8
          if (mfp.isLowIE) {
            decr = parseInt(item.img.css('padding-top'), 10) + parseInt(item.img.css('padding-bottom'), 10);
          }
          item.img.css('max-height', mfp.wH - decr);
        }
      },
      _onImageHasSize: function (item) {
        if (item.img) {

          item.hasSize = true;

          if (_imgInterval) {
            clearInterval(_imgInterval);
          }

          item.isCheckingImgSize = false;

          _mfpTrigger('ImageHasSize', item);

          if (item.imgHidden) {
            if (mfp.content)
              mfp.content.removeClass('mfp-loading');

            item.imgHidden = false;
          }

        }
      },

      /**
       * Function that loops until the image has size to display elements that rely on it asap
       */
      findImageSize: function (item) {

        var counter = 0,
          img = item.img[0],
          mfpSetInterval = function (delay) {

            if (_imgInterval) {
              clearInterval(_imgInterval);
            }
            // decelerating interval that checks for size of an image
            _imgInterval = setInterval(function () {
              if (img.naturalWidth > 0) {
                mfp._onImageHasSize(item);
                return;
              }

              if (counter > 200) {
                clearInterval(_imgInterval);
              }

              counter++;
              if (counter === 3) {
                mfpSetInterval(10);
              } else if (counter === 40) {
                mfpSetInterval(50);
              } else if (counter === 100) {
                mfpSetInterval(500);
              }
            }, delay);
          };

        mfpSetInterval(1);
      },

      getImage: function (item, template) {

        var guard = 0,

          // image load complete handler
          onLoadComplete = function () {
            if (item) {
              if (item.img[0].complete) {
                item.img.off('.mfploader');

                if (item === mfp.currItem) {
                  mfp._onImageHasSize(item);

                  mfp.updateStatus('ready');
                }

                item.hasSize = true;
                item.loaded = true;

                _mfpTrigger('ImageLoadComplete');

              }
              else {
                // if image complete check fails 200 times (20 sec), we assume that there was an error.
                guard++;
                if (guard < 200) {
                  setTimeout(onLoadComplete, 100);
                } else {
                  onLoadError();
                }
              }
            }
          },

          // image error handler
          onLoadError = function () {
            if (item) {
              item.img.off('.mfploader');
              if (item === mfp.currItem) {
                mfp._onImageHasSize(item);
                mfp.updateStatus('error', imgSt.tError.replace('%url%', item.src));
              }

              item.hasSize = true;
              item.loaded = true;
              item.loadError = true;
            }
          },
          imgSt = mfp.st.image;

        var el = template.find('.mfp-img');
        if (el.length) {
          var img = document.createElement('img');
          img.className = 'mfp-img';
          if (item.el && item.el.find('img').length) {
            img.alt = item.el.find('img').attr('alt');
          }
          item.img = $(img).on('load.mfploader', onLoadComplete).on('error.mfploader', onLoadError);
          img.src = item.src;

          // without clone() "error" event is not firing when IMG is replaced by new IMG
          // TODO: find a way to avoid such cloning
          if (el.is('img')) {
            item.img = item.img.clone();
          }

          img = item.img[0];
          if (img.naturalWidth > 0) {
            item.hasSize = true;
          } else if (!img.width) {
            item.hasSize = false;
          }
        }

        mfp._parseMarkup(template, {
          title: _getTitle(item),
          img_replaceWith: item.img
        }, item);

        mfp.resizeImage();

        if (item.hasSize) {
          if (_imgInterval) clearInterval(_imgInterval);

          if (item.loadError) {
            template.addClass('mfp-loading');
            mfp.updateStatus('error', imgSt.tError.replace('%url%', item.src));
          } else {
            template.removeClass('mfp-loading');
            mfp.updateStatus('ready');
          }
          return template;
        }

        mfp.updateStatus('loading');
        item.loading = true;

        if (!item.hasSize) {
          item.imgHidden = true;
          template.addClass('mfp-loading');
          mfp.findImageSize(item);
        }

        return template;
      }
    }
  });


text:
if (!process.versions.openssl) {
  console.error('Skipping because node compiled without OpenSSL.');
  process.exit(0);
}

var common = require('../common');
var assert = require('assert');
var fs = require('fs');
var tls = require('tls');
var path = require('path');

var cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem'));
var key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem'));

var conn = tls.connect({cert: cert, key: key, port: common.PORT}, function() {
  assert.ok(false); // callback should never be executed
});
conn.on('error', function() {
});
assert.doesNotThrow(function() {
  conn.destroy();
});


text:
<html>
<head><title></title></head>
<!-- <body onload="javascript: playGame();"> -->
<canvas width="504" height="504" id="board" onclick="javascript: clickHandler(event);"></canvas>
<script src=games.js></script>
<LINK href="style.css" rel="stylesheet" type="text/css">
</script>
</body>
</html>


text:
is_interactive_shell || return

## Amazon AWS CLI
complete -C aws_completer aws


text:
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2019, OpenNebula Project, OpenNebula Systems                */
/*                                                                            */
/* 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.                                             */
/* -------------------------------------------------------------------------- */

define(function(require) {
  /*
    DEPENDENCIES
   */

//  require('foundation.tab');
  var BaseFormPanel = require("utils/form-panels/form-panel");
  var Sunstone = require("sunstone");
  var Locale = require("utils/locale");
  var Tips = require("utils/tips");
  var CustomTagsTable = require("utils/custom-tags-table");
  var ArTab = require("tabs/vnets-tab/utils/ar-tab");
  var SecurityGroupsTable = require("tabs/secgroups-tab/datatable");
  var ClustersTable = require("tabs/clusters-tab/datatable");
  var TemplateUtils = require("utils/template-utils");
  var WizardFields = require("utils/wizard-fields");
  var ResourceSelect = require("utils/resource-select");

  /*
    TEMPLATES
   */

  var TemplateWizardHTML = require("hbs!tabs/vnets-tab/form-panels/create/wizard");
  var TemplateAdvancedHTML = require("hbs!tabs/vnets-tab/form-panels/create/advanced");

  /*
    CONSTANTS
   */

  var FORM_PANEL_ID = require("./create/formPanelId");
  var TAB_ID = require("../tabId");

  /*
    CONSTRUCTOR
   */

  function FormPanel() {
    this.formPanelId = FORM_PANEL_ID;
    this.tabId = TAB_ID;
    this.actions = {
      "create": {
        "title": Locale.tr("Create Virtual Network Template"),
        "buttonText": Locale.tr("Create"),
        "resetButton": true
      },
      "update": {
        "title": Locale.tr("Update Virtual Network Template"),
        "buttonText": Locale.tr("Update"),
        "resetButton": false
      }
    };

    BaseFormPanel.call(this);
  }

  FormPanel.FORM_PANEL_ID = FORM_PANEL_ID;
  FormPanel.prototype = Object.create(BaseFormPanel.prototype);
  FormPanel.prototype.constructor = FormPanel;
  FormPanel.prototype.htmlWizard = _htmlWizard;
  FormPanel.prototype.htmlAdvanced = _htmlAdvanced;
  FormPanel.prototype.submitWizard = _submitWizard;
  FormPanel.prototype.submitAdvanced = _submitAdvanced;
  FormPanel.prototype.onShow = _onShow;
  FormPanel.prototype.fill = _fill;
  FormPanel.prototype.setup = _setup;
  FormPanel.prototype.addARTab = _add_ar_tab;

  return FormPanel;

  /*
    FUNCTION DEFINITIONS
   */

  function _htmlWizard() {
    var opts = {
      info: false,
      select: true,
      selectOptions: {"multiple_choice": true}
    };

    this.securityGroupsTable = new SecurityGroupsTable("vnet_tmpl_create_sg", opts);
    this.clustersTable = new ClustersTable("vnet_tmpl_create_cluster", opts);

    return TemplateWizardHTML({
      "formPanelId": this.formPanelId,
      "customTagsHTML": CustomTagsTable.html(),
      "securityGroupsTableHTML": this.securityGroupsTable.dataTableHTML,
      "clustersTableHTML": this.clustersTable.dataTableHTML,
      "createGeneralTab": "vntemplateCreateGeneralTab",
      "createBridgeTab": "vntemplateCreateBridgeTab",
      "createARTab": "vntemplateCreateARTab",
      "createSecurityTab": "vntemplateCreateSecurityTab",
      "createQoSTab": "vntemplateCreateQoSTab",
      "createContextTab": "vntemplateCreateContextTab"
    });
  }

  function _htmlAdvanced() {
    return TemplateAdvancedHTML({formPanelId: this.formPanelId});
  }

  function _setup(context) {
    this.arTabObjects = {};
    var that = this;

    var number_of_ar = 0;

    $("#vnet_wizard_ar_btn", context).bind("click", function() {
      that.addARTab(number_of_ar, context);
      number_of_ar++;
      var mode = $("#network_mode", context).val();
      if (mode == "vcenter"){
        $(".sec_groups_datatable", context).hide();
      }
      return false;
    });

    $("#vntemplateCreateARTab #vntemplateCreateARTabUpdate", context).hide();

    $("#network_mode", context).change(function() {
      $("div.mode_param", context).hide();
      $("div.mode_param [wizard_field]", context).prop("wizard_field_disabled", true);
      $("input#vn_mad", context).removeAttr("required");
      $("input#vn_mad", context).removeAttr("value");
      $("#vcenter_switch_name", context).removeAttr("required");
      $("#vcenter_cluster_id", context).removeAttr("required");
      $("#phydev", context).removeAttr("required");
      $(".sec_groups_datatable", context).show();
      $("#vntemplateCreateSecurityTab-label").show();
      $("#automatic_vlan_id option[value='NO']", context).show();
      $("input[wizard_field=\"VLAN_ID\"]", context).removeAttr("required");

      switch ($(this).val()) {
      case "bridge":
        $("div.mode_param.bridge", context).show();
        $("div.mode_param.bridge [wizard_field]", context).prop("wizard_field_disabled", false);

        $("input#bridge", context).removeAttr("required");
        break;
      case "fw":
        $("div.mode_param.fw", context).show();
        $("div.mode_param.fw [wizard_field]", context).prop("wizard_field_disabled", false);

        $("input#bridge", context).removeAttr("required");
        break;
      case "802.1Q":
        $("div.mode_param.8021Q", context).show();
        $("div.mode_param.8021Q [wizard_field]", context).prop("wizard_field_disabled", false);

        $("input#bridge", context).removeAttr("required");
        $("#phydev", context).attr("required", "");
        $("#automatic_vlan_id option[value='NO']", context).hide();
        break;
      case "vxlan":
        $("div.mode_param.vxlan", context).show();
        $("div.mode_param.vxlan [wizard_field]", context).prop("wizard_field_disabled", false);

        $("input#bridge", context).removeAttr("required");
        $("#automatic_vlan_id option[value='NO']", context).hide();
        $("#phydev", context).attr("required", "");
        break;
      case "ebtables":
        $("div.mode_param.ebtables", context).show();
        $("div.mode_param.ebtables [wizard_field]", context).prop("wizard_field_disabled", false);

        $("input#bridge", context).removeAttr("required");
        break;
      case "ovswitch":
        $("div.mode_param.ovswitch", context).show();
        $("#vntemplateCreateSecurityTab-label").hide();
        $("div.mode_param.ovswitch [wizard_field]", context).prop("wizard_field_disabled", false);

        $("input#bridge", context).removeAttr("required");
        break;
      case "ovswitch_vxlan":
        $("div.mode_param.ovswitch_vxlan", context).show();
        $("#vntemplateCreateSecurityTab-label").hide();
        $("div.mode_param.ovswitch_vxlan [wizard_field]", context).prop("wizard_field_disabled", false);

        $("input#bridge", context).removeAttr("required");
        $("#phydev", context).attr("required", "");
        break;
      case "vcenter":
        $("div.mode_param.vcenter", context).show();
        $(".sec_groups_datatable", context).hide();
        $("div.mode_param.vcenter [wizard_field]", context).prop("wizard_field_disabled", false);
        $("input#bridge", context).attr("value", $("#name", context).val());
        $("#vcenter_switch_name", context).attr("required", "");
        $("#vntemplateCreateSecurityTab-label").hide();
        ResourceSelect.insert({
          context: $("#vcenter_cluster_id", context),
          resourceName: "Host",
          emptyValue: true,
          nameValues: false,
          filterKey: "VM_MAD",
          filterValue: "vcenter",
          required: true,
          callback: function(element){
            element.attr("wizard_field", "VCENTER_ONE_HOST_ID");
          }
        });

        $("input#vn_mad", context).attr("required", "");
        $("input#vn_mad", context).attr("value", "vcenter");

        $("#div_vn_mad", context).hide();
        break;
      case "custom":
        $("div.mode_param.custom", context).show();
        $("div.mode_param.custom [wizard_field]", context).prop("wizard_field_disabled", false);

        $("input#bridge", context).removeAttr("required");
        $("input#vn_mad", context).attr("required", "");
        break;
      }

      $("div.network_mode_description").hide();
      $("div.network_mode_description[value=\"" + $(this).val() + "\"]").show();

      if ($("input[wizard_field=\"VLAN_ID\"]", context).is(":visible")){
        $("input[wizard_field=\"VLAN_ID\"]", context).attr("required", "");
      } else {
        $("input[wizard_field=\"VLAN_ID\"]", context).removeAttr("required");
      }

      if ($("input[wizard_field=\"OUTER_VLAN_ID\"]", context).is(":visible")){
        $("input[wizard_field=\"OUTER_VLAN_ID\"]", context).attr("required", "");
      } else {
        $("input[wizard_field=\"OUTER_VLAN_ID\"]", context).removeAttr("required");
      }
    });

    $("select[wizard_field=AUTOMATIC_VLAN_ID]", context).change(function(){
      if($(this).val() != "") {
        $("input[wizard_field=\"VLAN_ID\"]", context).hide().prop("wizard_field_disabled", true).removeAttr("required");
      } else {
        $("input[wizard_field=\"VLAN_ID\"]", context).show().prop("wizard_field_disabled", false).attr("required", "");
      }
    });

    $("select[wizard_field=AUTOMATIC_OUTER_VLAN_ID]", context).change(function(){
      if($(this).val() != "") {
        $("input[wizard_field=\"OUTER_VLAN_ID\"]", context).hide().prop("wizard_field_disabled", true).removeAttr("required");
      } else {
        $("input[wizard_field=\"OUTER_VLAN_ID\"]", context).show().prop("wizard_field_disabled", false).attr("required", "");
      }
    });

    //Initialize shown options
    $("#network_mode", context).trigger("change");
    $("select[wizard_field=AUTOMATIC_VLAN_ID]", context).trigger("change");
    $("select[wizard_field=AUTOMATIC_OUTER_VLAN_ID]", context).trigger("change");

    this.securityGroupsTable.initialize();
    this.clustersTable.initialize();

    CustomTagsTable.setup($("#vntemplateCreateContextTab", context));

    Foundation.reflow(context, "tabs");

    // Add first AR
    $("#vnet_wizard_ar_btn", context).trigger("click");

    Tips.setup();

    if (config["mode"] === "kvm"){
      $("#network_mode option[value=\"vcenter\"]", context).hide();
    } else if (config["mode"] === "vcenter"){
      $("#network_mode option[value=\"bridge\"]", context).hide();
      $("#network_mode option[value=\"fw\"]", context).hide();
      $("#network_mode option[value=\"ebtables\"]", context).hide();
      $("#network_mode option[value=\"802.1Q\"]", context).hide();
      $("#network_mode option[value=\"vxlan\"]", context).hide();
      $("#network_mode option[value=\"ovswitch\"]", context).hide();
      $("#network_mode option[value=\"ovswitch_vxlan\"]", context).hide();
    }

    $("#vntemplateCreateARTab ul#vnet_wizard_ar_tabs i.remove-tab", context).trigger("click");

    return false;
  }

  function _add_ar_tab(ar_id, context) {
    var that = this;
    var str_ar_tab_id  = "ar" + ar_id;

    var ar_tab = new ArTab();
    this.arTabObjects[ar_id] = ar_tab;

    var html_tab_content =
      "
" +
        ar_tab.html(str_ar_tab_id) +
      "
";

    // Append the new div containing the tab and add the tab to the list
    var a = $("
" +
        "" +
        Locale.tr("AR") + "
"
      ).appendTo($("ul#vnet_wizard_ar_tabs", context));

    $(html_tab_content).appendTo($("#vnet_wizard_ar_tabs_content", context));

    Foundation.reInit($("ul#vnet_wizard_ar_tabs", context));
    $("a", a).trigger("click");

    var ar_section = $("#" + str_ar_tab_id + "Tab", context);
    ar_tab.setup(ar_section, str_ar_tab_id);
    ar_tab.onShow();

    // close icon: removing the tab on click
    a.on("click", "i.remove-tab", function() {
      var target = $(this).parent().attr("href");
      var li = $(this).closest("li");
      var ul = $(this).closest("ul");
      var content = $(target);

      var ar_id = content.attr("ar_id");

      li.remove();
      content.remove();

      if (li.hasClass("is-active")) {
        $("a", ul.children("li").last()).click();
      }

      delete that.arTabObjects[ar_id];

      return false;
    });
  }

  function _submitWizard(context) {
    var that = this;

    //Fetch values
    var network_json = {};

    $.extend(network_json, WizardFields.retrieve($("#vntemplateCreateGeneralTab", context)));
    $.extend(network_json, WizardFields.retrieve($("#vntemplateCreateBridgeTab", context)));
    $.extend(network_json, WizardFields.retrieve($("#vntemplateCreateQoSTab", context)));
    $.extend(network_json, WizardFields.retrieve($("#vntemplateCreateContextTab", context)));

    var secgroups = this.securityGroupsTable.retrieveResourceTableSelect();
    if (secgroups != undefined && secgroups.length != 0) {
      network_json["SECURITY_GROUPS"] = secgroups.join(",");
    }

    var clusters = this.clustersTable.retrieveResourceTableSelect();
    if (clusters != undefined && clusters.length != 0) {
      network_json["CLUSTERS"] = clusters.join(",");
    }

    $.extend(network_json, CustomTagsTable.retrieve($("#vntemplateCreateContextTab", context)));

    $(".ar_tab", context).each(function() {
      var ar_id = $(this).attr("ar_id");
      var hash = that.arTabObjects[ar_id].retrieve();

      if (!$.isEmptyObject(hash)) {
        if (!network_json["AR"])
            network_json["AR"] = [];

        network_json["AR"].push(hash);
      }
    });

    if (this.action == "create") {
      network_json = {
        "vntemplate" : network_json,
        //"clusters": clusters
      };
      Sunstone.runAction("VNTemplate.create", network_json);
      return false;
    } else if (this.action == "update") {
      Sunstone.runAction("VNTemplate.update", this.resourceId, TemplateUtils.templateToString(network_json));
      return false;
    }
  }

  function _submitAdvanced(context) {
    if (this.action == "create") {
      var template = $("textarea#template", context).val();
      var vntemplate_json = {vntemplate: {vntemplate_raw: template}};
      Sunstone.runAction("VNTemplate.create", vntemplate_json);
      return false;

    } else if (this.action == "update") {
      var template_raw = $("textarea#template", context).val();
      var vntemplate_json = {vntemplate: {vntemplate_raw: template}};
      Sunstone.runAction("VNTemplate.update", this.resourceId, vntemplate_json);
      return false;
    }
  }

  function _onShow(context) {
    var that = this;

    this.securityGroupsTable.refreshResourceTableSelect();
    this.clustersTable.refreshResourceTableSelect();

    $(".ar_tab", context).each(function() {
      var ar_id = $(this).attr("ar_id");
      if (that.arTabObjects[ar_id] != undefined) {
        that.arTabObjects[ar_id].onShow();
      }
    });

    if (this.action === "create"){
      $("div#vnet_cluster_table_div", context).show();
      // var cluster_id = $("div#vnet_cluster_id .resource_list_select", context).val();
      // if (!cluster_id) cluster_id = "0";

      // ResourceSelect.insert({
      //   context: $('#vnet_cluster_id', context),
      //   resourceName: 'Cluster',
      //   initValue: cluster_id
      // });
    } else {
      $("div#vnet_cluster_table_div", context).hide();
    }
  }

  function _fill(context, element) {
    if (this.action != "update") {return;}
    this.setHeader(element);
    this.resourceId = element.ID;

    $("#default_sg_warning", context).hide();
    // Populates the Avanced mode Tab
    $("#template", context).val(TemplateUtils.templateToString(element.TEMPLATE));

    WizardFields.fillInput($("[wizard_field=\"NAME\"]", context), element.NAME);
    $("[wizard_field=\"NAME\"]", context).prop("disabled", true).prop("wizard_field_disabled", true);

    // Show all network mode inputs, and make them not required. This will change
    // if a different network model is selected
    $("input#bridge", context).removeAttr("required");
    $("div.mode_param", context).show();
    $("div.mode_param [wizard_field]", context).prop("wizard_field_disabled", true).removeAttr("required");

    WizardFields.fillInput($("input#vn_mad", context), element.TEMPLATE["VN_MAD"]);

    if (element.VLAN_ID_AUTOMATIC == 1){
      $("select[wizard_field=AUTOMATIC_VLAN_ID]", context).val("YES").
                                attr("disabled", "disabled").trigger("change");
    } else {
      $("select[wizard_field=AUTOMATIC_VLAN_ID]", context).val("").
                                attr("disabled", "disabled").trigger("change");
    }

    if (element.OUTER_VLAN_ID_AUTOMATIC== 1){
      $("select[wizard_field=AUTOMATIC_OUTER_VLAN_ID]", context).val("YES").
                                attr("disabled", "disabled").trigger("change");
    } else {
      $("select[wizard_field=AUTOMATIC_OUTER_VLAN_ID]", context).val("").
                                attr("disabled", "disabled").trigger("change");
    }

    WizardFields.fill($("#vntemplateCreateGeneralTab", context), element.TEMPLATE);
    WizardFields.fill($("#vntemplateCreateBridgeTab", context), element.TEMPLATE);
    WizardFields.fill($("#vntemplateCreateQoSTab", context), element.TEMPLATE);
    WizardFields.fill($("#vntemplateCreateContextTab", context), element.TEMPLATE);

    if ($("#network_mode", context).val() == undefined){
      $("#network_mode", context).val("custom").change();
    }

    if (element.TEMPLATE["SECURITY_GROUPS"] != undefined &&
        element.TEMPLATE["SECURITY_GROUPS"].length != 0) {

      var secgroups = element.TEMPLATE["SECURITY_GROUPS"].split(",");

      this.securityGroupsTable.selectResourceTableSelect({ids : secgroups});
    } else {
      this.securityGroupsTable.refreshResourceTableSelect();
    }

    if (element.TEMPLATE["CLUSTERS"] != undefined &&
        element.TEMPLATE["CLUSTERS"].length != 0) {

      var clusters = element.TEMPLATE["CLUSTERS"].split(",");

      this.clustersTable.selectResourceTableSelect({ids : clusters});
    } else {
      this.clustersTable.refreshResourceTableSelect();
    }

    // Delete so these attributes don't end in the custom tags table also
    delete element.TEMPLATE["SECURITY_GROUPS"];

    var fields = $("[wizard_field]", context);

    fields.each(function() {
      var field = $(this);
      var field_name = field.attr("wizard_field");

      delete element.TEMPLATE[field_name];
    });

    CustomTagsTable.fill($("#vntemplateCreateContextTab", context), element.TEMPLATE);

    // Remove the first AR added in initialize_
    $("#vntemplateCreateARTab ul#vnet_wizard_ar_tabs i.remove-tab", context).trigger("click");
    $("#vntemplateCreateARTab #vntemplateCreateARTabUpdate", context).show();
    $("#vntemplateCreateARTab #vntemplateCreateARTabCreate", context).hide();
  }
});


text:
package com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions;

import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.logic.AnyJobRestriction;
import hudson.model.Descriptor;

/**
 * Descriptor class for {@link JobRestriction}s.
 * @author Oleg Nenashev
 */
public abstract class JobRestrictionDescriptor extends Descriptor<JobRestriction> {
    public JobRestrictionDescriptor getDefaultSettingsProvider() {
        return (JobRestrictionDescriptor)JobRestriction.all().find(AnyJobRestriction.class);
    }
}


text:
/*
 *	Device handling code
 *	Linux ethernet bridge
 *
 *	Authors:
 *	Lennert Buytenhek		<buytenh@gnu.org>
 *
 *	This program is free software; you can redistribute it and/or
 *	modify it under the terms of the GNU General Public License
 *	as published by the Free Software Foundation; either version
 *	2 of the License, or (at your option) any later version.
 */

#include <linux/kernel.h>
#include <linux/netdevice.h>
#include <linux/netpoll.h>
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include <linux/list.h>
#include <linux/netfilter_bridge.h>

#include <asm/uaccess.h>
#include "br_private.h"

/* net device transmit always called with BH disabled */
netdev_tx_t br_dev_xmit(struct sk_buff *skb, struct net_device *dev)
{
	struct net_bridge *br = netdev_priv(dev);
	const unsigned char *dest = skb->data;
	struct net_bridge_fdb_entry *dst;
	struct net_bridge_mdb_entry *mdst;
	struct br_cpu_netstats *brstats = this_cpu_ptr(br->stats);

#ifdef CONFIG_BRIDGE_NETFILTER
	if (skb->nf_bridge && (skb->nf_bridge->mask & BRNF_BRIDGED_DNAT)) {
		br_nf_pre_routing_finish_bridge_slow(skb);
		return NETDEV_TX_OK;
	}
#endif

	BR_INPUT_SKB_CB(skb)->brdev = dev;

	skb_reset_mac_header(skb);
	skb_pull(skb, ETH_HLEN);

	u64_stats_update_begin(&brstats->syncp);
	brstats->tx_packets++;
	/* Exclude ETH_HLEN from byte stats for consistency with Rx chain */
	brstats->tx_bytes += skb->len;
	u64_stats_update_end(&brstats->syncp);

	rcu_read_lock();
	if (is_broadcast_ether_addr(dest))
		br_flood_deliver(br, skb);
	else if (is_multicast_ether_addr(dest)) {
		if (unlikely(netpoll_tx_running(dev))) {
			br_flood_deliver(br, skb);
			goto out;
		}
		if (br_multicast_rcv(br, NULL, skb)) {
			kfree_skb(skb);
			goto out;
		}

		mdst = br_mdb_get(br, skb);
		if (mdst || BR_INPUT_SKB_CB_MROUTERS_ONLY(skb))
			br_multicast_deliver(mdst, skb);
		else
			br_flood_deliver(br, skb);
	} else if ((dst = __br_fdb_get(br, dest)) != NULL)
		br_deliver(dst->dst, skb);
	else
		br_flood_deliver(br, skb);

out:
	rcu_read_unlock();
	return NETDEV_TX_OK;
}

static int br_dev_init(struct net_device *dev)
{
	struct net_bridge *br = netdev_priv(dev);

	br->stats = alloc_percpu(struct br_cpu_netstats);
	if (!br->stats)
		return -ENOMEM;

	return 0;
}

static int br_dev_open(struct net_device *dev)
{
	struct net_bridge *br = netdev_priv(dev);

	netdev_update_features(dev);
	netif_start_queue(dev);
	br_stp_enable_bridge(br);
	br_multicast_open(br);

	return 0;
}

static void br_dev_set_multicast_list(struct net_device *dev)
{
}

static int br_dev_stop(struct net_device *dev)
{
	struct net_bridge *br = netdev_priv(dev);

	br_stp_disable_bridge(br);
	br_multicast_stop(br);

	netif_stop_queue(dev);

	return 0;
}

static struct rtnl_link_stats64 *br_get_stats64(struct net_device *dev,
						struct rtnl_link_stats64 *stats)
{
	struct net_bridge *br = netdev_priv(dev);
	struct br_cpu_netstats tmp, sum = { 0 };
	unsigned int cpu;

	for_each_possible_cpu(cpu) {
		unsigned int start;
		const struct br_cpu_netstats *bstats
			= per_cpu_ptr(br->stats, cpu);
		do {
			start = u64_stats_fetch_begin(&bstats->syncp);
			memcpy(&tmp, bstats, sizeof(tmp));
		} while (u64_stats_fetch_retry(&bstats->syncp, start));
		sum.tx_bytes   += tmp.tx_bytes;
		sum.tx_packets += tmp.tx_packets;
		sum.rx_bytes   += tmp.rx_bytes;
		sum.rx_packets += tmp.rx_packets;
	}

	stats->tx_bytes   = sum.tx_bytes;
	stats->tx_packets = sum.tx_packets;
	stats->rx_bytes   = sum.rx_bytes;
	stats->rx_packets = sum.rx_packets;

	return stats;
}

static int br_change_mtu(struct net_device *dev, int new_mtu)
{
	struct net_bridge *br = netdev_priv(dev);
	if (new_mtu < 68 || new_mtu > br_min_mtu(br))
		return -EINVAL;

	dev->mtu = new_mtu;

#ifdef CONFIG_BRIDGE_NETFILTER
	/* remember the MTU in the rtable for PMTU */
	dst_metric_set(&br->fake_rtable.dst, RTAX_MTU, new_mtu);
#endif

	return 0;
}

/* Allow setting mac address to any valid ethernet address. */
static int br_set_mac_address(struct net_device *dev, void *p)
{
	struct net_bridge *br = netdev_priv(dev);
	struct sockaddr *addr = p;

	if (!is_valid_ether_addr(addr->sa_data))
		return -EADDRNOTAVAIL;

	spin_lock_bh(&br->lock);
	if (compare_ether_addr(dev->dev_addr, addr->sa_data)) {
		dev->addr_assign_type &= ~NET_ADDR_RANDOM;
		memcpy(dev->dev_addr, addr->sa_data, ETH_ALEN);
		br_fdb_change_mac_address(br, addr->sa_data);
		br_stp_change_bridge_id(br, addr->sa_data);
	}
	br->flags |= BR_SET_MAC_ADDR;
	spin_unlock_bh(&br->lock);

	return 0;
}

static void br_getinfo(struct net_device *dev, struct ethtool_drvinfo *info)
{
	strcpy(info->driver, "bridge");
	strcpy(info->version, BR_VERSION);
	strcpy(info->fw_version, "N/A");
	strcpy(info->bus_info, "N/A");
}

static netdev_features_t br_fix_features(struct net_device *dev,
	netdev_features_t features)
{
	struct net_bridge *br = netdev_priv(dev);

	return br_features_recompute(br, features);
}

#ifdef CONFIG_NET_POLL_CONTROLLER
static void br_poll_controller(struct net_device *br_dev)
{
}

static void br_netpoll_cleanup(struct net_device *dev)
{
	struct net_bridge *br = netdev_priv(dev);
	struct net_bridge_port *p, *n;

	list_for_each_entry_safe(p, n, &br->port_list, list) {
		br_netpoll_disable(p);
	}
}

static int br_netpoll_setup(struct net_device *dev, struct netpoll_info *ni)
{
	struct net_bridge *br = netdev_priv(dev);
	struct net_bridge_port *p, *n;
	int err = 0;

	list_for_each_entry_safe(p, n, &br->port_list, list) {
		if (!p->dev)
			continue;

		err = br_netpoll_enable(p);
		if (err)
			goto fail;
	}

out:
	return err;

fail:
	br_netpoll_cleanup(dev);
	goto out;
}

int br_netpoll_enable(struct net_bridge_port *p)
{
	struct netpoll *np;
	int err = 0;

	np = kzalloc(sizeof(*p->np), GFP_KERNEL);
	err = -ENOMEM;
	if (!np)
		goto out;

	np->dev = p->dev;
	strlcpy(np->dev_name, p->dev->name, IFNAMSIZ);

	err = __netpoll_setup(np);
	if (err) {
		kfree(np);
		goto out;
	}

	p->np = np;

out:
	return err;
}

void br_netpoll_disable(struct net_bridge_port *p)
{
	struct netpoll *np = p->np;

	if (!np)
		return;

	p->np = NULL;

	/* Wait for transmitting packets to finish before freeing. */
	synchronize_rcu_bh();

	__netpoll_cleanup(np);
	kfree(np);
}

#endif

static int br_add_slave(struct net_device *dev, struct net_device *slave_dev)

{
	struct net_bridge *br = netdev_priv(dev);

	return br_add_if(br, slave_dev);
}

static int br_del_slave(struct net_device *dev, struct net_device *slave_dev)
{
	struct net_bridge *br = netdev_priv(dev);

	return br_del_if(br, slave_dev);
}

static const struct ethtool_ops br_ethtool_ops = {
	.get_drvinfo    = br_getinfo,
	.get_link	= ethtool_op_get_link,
};

static const struct net_device_ops br_netdev_ops = {
	.ndo_open		 = br_dev_open,
	.ndo_stop		 = br_dev_stop,
	.ndo_init		 = br_dev_init,
	.ndo_start_xmit		 = br_dev_xmit,
	.ndo_get_stats64	 = br_get_stats64,
	.ndo_set_mac_address	 = br_set_mac_address,
	.ndo_set_rx_mode	 = br_dev_set_multicast_list,
	.ndo_change_mtu		 = br_change_mtu,
	.ndo_do_ioctl		 = br_dev_ioctl,
#ifdef CONFIG_NET_POLL_CONTROLLER
	.ndo_netpoll_setup	 = br_netpoll_setup,
	.ndo_netpoll_cleanup	 = br_netpoll_cleanup,
	.ndo_poll_controller	 = br_poll_controller,
#endif
	.ndo_add_slave		 = br_add_slave,
	.ndo_del_slave		 = br_del_slave,
	.ndo_fix_features        = br_fix_features,
};

static void br_dev_free(struct net_device *dev)
{
	struct net_bridge *br = netdev_priv(dev);

	free_percpu(br->stats);
	free_netdev(dev);
}

static struct device_type br_type = {
	.name	= "bridge",
};

void br_dev_setup(struct net_device *dev)
{
	struct net_bridge *br = netdev_priv(dev);

	eth_hw_addr_random(dev);
	ether_setup(dev);

	dev->netdev_ops = &br_netdev_ops;
	dev->destructor = br_dev_free;
	SET_ETHTOOL_OPS(dev, &br_ethtool_ops);
	SET_NETDEV_DEVTYPE(dev, &br_type);
	dev->tx_queue_len = 0;
	dev->priv_flags = IFF_EBRIDGE;

	dev->features = NETIF_F_SG | NETIF_F_FRAGLIST | NETIF_F_HIGHDMA |
			NETIF_F_GSO_MASK | NETIF_F_HW_CSUM | NETIF_F_LLTX |
			NETIF_F_NETNS_LOCAL | NETIF_F_HW_VLAN_TX;
	dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST | NETIF_F_HIGHDMA |
			   NETIF_F_GSO_MASK | NETIF_F_HW_CSUM |
			   NETIF_F_HW_VLAN_TX;

	br->dev = dev;
	spin_lock_init(&br->lock);
	INIT_LIST_HEAD(&br->port_list);
	spin_lock_init(&br->hash_lock);

	br->bridge_id.prio[0] = 0x80;
	br->bridge_id.prio[1] = 0x00;

	memcpy(br->group_addr, br_group_address, ETH_ALEN);

	br->stp_enabled = BR_NO_STP;
	br->group_fwd_mask = BR_GROUPFWD_DEFAULT;

	br->designated_root = br->bridge_id;
	br->bridge_max_age = br->max_age = 20 * HZ;
	br->bridge_hello_time = br->hello_time = 2 * HZ;
	br->bridge_forward_delay = br->forward_delay = 15 * HZ;
	br->ageing_time = 300 * HZ;

	br_netfilter_rtable_init(br);
	br_stp_timer_init(br);
	br_multicast_init(br);
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Dasyscyphus hamatus var. bulbopilosus Feltgen, 1903

### Remarks
null


text:
cask 'classeur' do
  version :latest
  sha256 :no_check

  url 'http://download.classeur.io/download/osx'
  name 'Classeur'
  homepage 'http://classeur.io/'

  app 'Classeur.app'
end


text:
LEVEL = ..

include $(LEVEL)/Makefile.config

PARALLEL_DIRS := IR AsmParser Bitcode Analysis Transforms CodeGen Target      \
                 ExecutionEngine Linker LTO MC Object Option DebugInfo        \
                 IRReader LineEditor ProfileData Passes LibDriver

include $(LEVEL)/Makefile.common


text:
<?php

namespace Btn\PmBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

use Btn\BaseBundle\Controller\RestController as BaseRestController;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;

/**
 * Restful leads controller
 *
 * @Route("/rest/lead")
 */
class LeadController extends BaseRestController
{
    //define controller resources, maybe we can move them to the config?
    protected $resource   = 'Btn\\PmBundle\\Entity\\Lead';
    protected $createForm = 'Btn\\PmBundle\\Form\\LeadType';
    protected $editForm   = 'Btn\\PmBundle\\Form\\LeadType';

    //define custom callback
    protected $customCallbacks = array(
        'setCurrentUser',
    );

    /**
     * Register preexecute filter - checking auth before each rest call
     *
     * @return void
     **/
    public function preExecute($event, $resolver)
    {
        if (!$this->isAuthenticated()) {
            $request = $event->getRequest();

            $request->attributes->set('_controller', 'BtnPmBundle:Api:exception');
            $request->attributes->set('_route', 'actionException');
            $request->attributes->set('type', 'not_authenticated');

            $event->setController($resolver->getController($request));
        }
    }

    /**
     * Custom callback - set current user when lead is saved (each time via rest api)
     *
     * @return void
     **/
    protected function setCurrentUser(&$controller, $entity)
    {
        $entity->setUser($controller->getUser());
    }
}


text:
package com.morpheus.wallpaper.vertex.shape;

import java.util.ArrayList;
import android.graphics.Canvas;
import android.graphics.Paint;

public class Container {
	private ArrayList<Number> mNumber = new ArrayList<Number>(4);

	public Number getNumber(int i) {
		if (i < mNumber.size())
			return mNumber.get(i);
		else
			return null;
	}

	public int getNumberCount() {
		return mNumber.size();
	}

	public void addNumber(Number num) {
		mNumber.add(num);
	}

	public void replaceNumberAt(Number num, int index) {
		if (index < mNumber.size()) {
//			delete mNumber[index];
			mNumber.set(index, num);
		}
	}

	public boolean draw(Canvas canvas, Paint paint) {

		boolean bEnd = true;

		for (Number number : mNumber) {
			if (!number.draw(canvas, paint))
				bEnd = false;		// Even One Ball doesnot finish drawing,
		}

		return bEnd;
	}
}


text:
@interface BBTemplaterTagXpath : BBTemplaterTag

@end


text:
class CreatePermalinks < ActiveRecord::Migration
  def self.up
    # TODO: These are f'ed
    # transaction do
    #   User.paginated_each do |user|
    #     User.update_all ['permalink = ?', PermalinkFu.escape(user.login)], ['id = ?', user.id]
    #   end
    #   Forum.paginated_each do |forum|
    #     Forum.update_all ['permalink = ?', PermalinkFu.escape(forum.name)], ['id = ?', forum.id]
    #   end
    #   Topic.paginated_each do |topic|
    #     Topic.update_all ['permalink = ?', PermalinkFu.escape(topic.title)], ['id = ?', topic.id]
    #   end
    # end
  end

  def self.down
  end
end


text:
package org.apache.deltaspike.test.scheduler.custom;

import junit.framework.Assert;
import org.apache.deltaspike.core.spi.config.ConfigSource;
import org.apache.deltaspike.scheduler.spi.Scheduler;
import org.apache.deltaspike.test.util.ArchiveUtils;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.quartz.Job;

import javax.inject.Inject;

@RunWith(Arquillian.class)
public class ScopeNotStartedTest
{
    //TODO even though this test exists, the tests in this module don't execute for quartz.
    @Deployment
    public static WebArchive deploy()
    {
        String simpleName = ScopeNotStartedTest.class.getSimpleName();
        String archiveName = simpleName.substring(0, 1).toLowerCase() + simpleName.substring(1);

        JavaArchive testJar = ShrinkWrap.create(JavaArchive.class, "scopeNotStartedTest.jar")
                .addPackage(CustomSchedulerWarFileTest.class.getPackage().getName())
                .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
                .addAsResource(new StringAsset(MockedScheduler.class.getName()),
                        "META-INF/services/" + Scheduler.class.getName())
                .addAsResource(new StringAsset(CustomDeactivatedConfigSource.class.getName()),
                        "META-INF/services/" + ConfigSource.class.getName());

        return ShrinkWrap.create(WebArchive.class, archiveName + ".war")
                .addAsLibraries(ArchiveUtils.getDeltaSpikeCoreAndSchedulerArchive())
                .addAsLibraries(Maven.resolver().loadPomFromFile("pom.xml").resolve(
                        "org.quartz-scheduler:quartz")
                        .withTransitivity()
                        .asFile())
                .addAsLibraries(testJar)
                .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
    }

    @Inject
    private Scheduler scheduler;

    @Inject
    private TestJobManager testJobManager;

    @Test
    public void testRegisterBadJob()
    {
        Assert.assertTrue(testJobManager.isStarted());

        this.scheduler.registerNewJob(ManualJob.class);
        Assert.assertEquals(2, testJobManager.getRegisteredJobs().size());
        Assert.assertEquals(2, testJobManager.getRunningJobs().size());

    }
}


text:
require "test_helper"

module Tropoli
  class PingResponseTest < IntegrationTest
    test :"responding to a PING message" do
      connection.tap do |c|
        assert_sent_from c, "PONG gort.nj.us.doolanshire.net" do
          c.receive_line ":gort.nj.us.doolanshire.net PING gort.nj.us.doolanshire.net\r\n"
        end
        assert_sent_from c, "PONG gort.nj.us.doolanshire.net blat.ma.es.doolanshire.net" do
          c.receive_line ":server PING gort.nj.us.doolanshire.net blat.ma.es.doolanshire.net\r\n"
        end
      end
    end

    test :"responding to a CTCP PING request" do
      connection.tap do |c|
        assert_sent_from c, "NOTICE Raws :\x01PONG signature\x01\r\n" do
          c.receive_line ":Raws!ross@test PRIVMSG Tropoli :\x01PING signature\x01\r\n"
        end
      end
    end
  end
end


text:
namespace boost {
namespace interprocess {
namespace ipcdetail {

class spin_condition
{
   spin_condition(const spin_condition &);
   spin_condition &operator=(const spin_condition &);

   public:
   spin_condition()
   {
      //Note that this class is initialized to zero.
      //So zeroed memory can be interpreted as an initialized
      //condition variable
      m_command      = SLEEP;
      m_num_waiters  = 0;
   }

   ~spin_condition()
   {
      //Notify all waiting threads
      //to allow POSIX semantics on condition destruction
      this->notify_all();
   }

   void notify_one()
   {  this->notify(NOTIFY_ONE);  }

   void notify_all()
   {  this->notify(NOTIFY_ALL);  }

   template <typename L>
   void wait(L& lock)
   {
      if (!lock)
         throw lock_exception();
      this->do_timed_wait_impl<false>(0, *lock.mutex());
   }

   template <typename L, typename Pr>
   void wait(L& lock, Pr pred)
   {
      if (!lock)
         throw lock_exception();

      while (!pred())
         this->do_timed_wait_impl<false>(0, *lock.mutex());
   }

   template <typename L, typename TimePoint>
   bool timed_wait(L& lock, const TimePoint &abs_time)
   {
      if (!lock)
         throw lock_exception();
      //Handle infinity absolute time here to avoid complications in do_timed_wait
      if(is_pos_infinity(abs_time)){
         this->wait(lock);
         return true;
      }
      return this->do_timed_wait_impl<true>(abs_time, *lock.mutex());
   }

   template <typename L, typename TimePoint, typename Pr>
   bool timed_wait(L& lock, const TimePoint &abs_time, Pr pred)
   {
      if (!lock)
         throw lock_exception();
      //Handle infinity absolute time here to avoid complications in do_timed_wait
      if(is_pos_infinity(abs_time)){
         this->wait(lock, pred);
         return true;
      }
      while (!pred()){
         if (!this->do_timed_wait_impl<true>(abs_time, *lock.mutex()))
            return pred();
      }
      return true;
   }

   template <typename L, class TimePoint>
   cv_status wait_until(L& lock, const TimePoint &abs_time)
   {  return this->timed_wait(lock, abs_time) ? cv_status::no_timeout : cv_status::timeout; }

   template <typename L, class TimePoint, typename Pr>
   bool wait_until(L& lock, const TimePoint &abs_time, Pr pred)
   {  return this->timed_wait(lock, abs_time, pred); }

   template <typename L, class Duration>
   cv_status wait_for(L& lock, const Duration &dur)
   {  return this->wait_until(lock, duration_to_ustime(dur)); }

   template <typename L, class Duration, typename Pr>
   bool wait_for(L& lock, const Duration &dur, Pr pred)
   {  return this->wait_until(lock, duration_to_ustime(dur), pred); }

   private:

   template<bool TimeoutEnabled, class InterprocessMutex, class TimePoint>
   bool do_timed_wait_impl(const TimePoint &abs_time, InterprocessMutex &mut)
   {
      typedef boost::interprocess::scoped_lock<spin_mutex> InternalLock;
      //The enter mutex guarantees that while executing a notification,
      //no other thread can execute the do_timed_wait method.
      {
         //---------------------------------------------------------------
         InternalLock lock;
         get_lock(bool_<TimeoutEnabled>(), m_enter_mut, lock, abs_time);

         if(!lock)
            return false;
         //---------------------------------------------------------------
         //We increment the waiting thread count protected so that it will be
         //always constant when another thread enters the notification logic.
         //The increment marks this thread as "waiting on spin_condition"
         atomic_inc32(const_cast<boost::uint32_t*>(&m_num_waiters));

         //We unlock the external mutex atomically with the increment
         mut.unlock();
      }

      //By default, we suppose that no timeout has happened
      bool timed_out  = false, unlock_enter_mut= false;

      //Loop until a notification indicates that the thread should
      //exit or timeout occurs
      while(1){
         //The thread sleeps/spins until a spin_condition commands a notification
         //Notification occurred, we will lock the checking mutex so that
         spin_wait swait;
         while(atomic_read32(&m_command) == SLEEP){
            swait.yield();

            //Check for timeout
            if(TimeoutEnabled){
               TimePoint now = get_now<TimePoint>(bool_<TimeoutEnabled>());

               if(now >= abs_time){
                  //If we can lock the mutex it means that no notification
                  //is being executed in this spin_condition variable
                  timed_out = m_enter_mut.try_lock();

                  //If locking fails, indicates that another thread is executing
                  //notification, so we play the notification game
                  if(!timed_out){
                     //There is an ongoing notification, we will try again later
                     continue;
                  }
                  //No notification in execution, since enter mutex is locked.
                  //We will execute time-out logic, so we will decrement count,
                  //release the enter mutex and return false.
                  break;
               }
            }
         }

         //If a timeout occurred, the mutex will not execute checking logic
         if(TimeoutEnabled && timed_out){
            //Decrement wait count
            atomic_dec32(const_cast<boost::uint32_t*>(&m_num_waiters));
            unlock_enter_mut = true;
            break;
         }
         else{
            boost::uint32_t result = atomic_cas32
                           (const_cast<boost::uint32_t*>(&m_command), SLEEP, NOTIFY_ONE);
            if(result == SLEEP){
               //Other thread has been notified and since it was a NOTIFY one
               //command, this thread must sleep again
               continue;
            }
            else if(result == NOTIFY_ONE){
               //If it was a NOTIFY_ONE command, only this thread should
               //exit. This thread has atomically marked command as sleep before
               //so no other thread will exit.
               //Decrement wait count.
               unlock_enter_mut = true;
               atomic_dec32(const_cast<boost::uint32_t*>(&m_num_waiters));
               break;
            }
            else{
               //If it is a NOTIFY_ALL command, all threads should return
               //from do_timed_wait function. Decrement wait count.
               unlock_enter_mut = 1 == atomic_dec32(const_cast<boost::uint32_t*>(&m_num_waiters));
               //Check if this is the last thread of notify_all waiters
               //Only the last thread will release the mutex
               if(unlock_enter_mut){
                  atomic_cas32(const_cast<boost::uint32_t*>(&m_command), SLEEP, NOTIFY_ALL);
               }
               break;
            }
         }
      }

      //Unlock the enter mutex if it is a single notification, if this is
      //the last notified thread in a notify_all or a timeout has occurred
      if(unlock_enter_mut){
         m_enter_mut.unlock();
      }

      //Lock external again before returning from the method
      mut.lock();
      return !timed_out;
   }

   template <class TimePoint>
   static TimePoint get_now(bool_<true>)
   {  return microsec_clock<TimePoint>::universal_time();  }

   template <class TimePoint>
   static TimePoint get_now(bool_<false>)
   {  return TimePoint();  }

   template <class Mutex, class Lock, class TimePoint>
   static void  get_lock(bool_<true>, Mutex &m, Lock &lck, const TimePoint &abs_time)
   {
      Lock dummy(m, abs_time);
      lck = boost::move(dummy);
   }

   template <class Mutex, class Lock, class TimePoint>
   static void get_lock(bool_<false>, Mutex &m, Lock &lck, const TimePoint &)
   {
      Lock dummy(m);
      lck = boost::move(dummy);
   }

   void notify(boost::uint32_t command)
   {
      //This mutex guarantees that no other thread can enter to the
      //do_timed_wait method logic, so that thread count will be
      //constant until the function writes a NOTIFY_ALL command.
      //It also guarantees that no other notification can be signaled
      //on this spin_condition before this one ends
      m_enter_mut.lock();

      //Return if there are no waiters
      if(!atomic_read32(&m_num_waiters)) {
         m_enter_mut.unlock();
         return;
      }

      //Notify that all threads should execute wait logic
      spin_wait swait;
      while(SLEEP != atomic_cas32(const_cast<boost::uint32_t*>(&m_command), command, SLEEP)){
         swait.yield();
      }
      //The enter mutex will rest locked until the last waiting thread unlocks it
   }

   enum { SLEEP = 0, NOTIFY_ONE, NOTIFY_ALL };
   spin_mutex  m_enter_mut;
   volatile boost::uint32_t    m_command;
   volatile boost::uint32_t    m_num_waiters;
};

}  //namespace ipcdetail
}  //namespace interprocess
}  //namespace boost

#include <boost/interprocess/detail/config_end.hpp>

#endif   //BOOST_INTERPROCESS_DETAIL_SPIN_CONDITION_HPP


text:
require 'celluloid/current'
require 'conquer/core_ext/numeric'
require 'conquer/helpers'

module Conquer
  class EventSegment
    class Worker
      include Celluloid
      include Celluloid::Notifications

      def initialize(topic, block, *subscribed_topics)
        @topic = topic
        @block = wrapped_proc(block)
        subscribed_topics.each { |t| subscribe(t, :handle_event) }
      end

      def handle_event(event, *args)
        publish(@topic, @block.call(event, *args).to_s.chomp)
      end

      private

      def wrapped_proc(block)
        proc { |*args| Helpers.instance_exec(*args, &block) }
      end
    end

    def initialize(topic, interval, block, *subscribed_topics)
      @topic = topic
      @interval = interval
      @block = block
      @subscribed_topics = subscribed_topics
    end

    def start_worker
      Worker.supervise(args: [@topic, @interval, @block, *@subscribed_topics])
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="black">#000000</color>
    <color name="white">#FFFFFF</color>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
    <color name="limit_buy_border_bg">#ffd4bc77</color>
    <color name="search_toolbar_bg">#ff484B50</color>
    <color name="toast_color">#ff2E76B9</color>
    <color name="login_button">#ff775025</color>
    <color name="text_doing">#DA5601</color>
    <color name="tab_unfocuse">#868686</color>
    <color name="tab_focuse">#FF6E0F</color>
    <color name="item_selected">#FF862A</color>
    <color name="item_normal">#FFF3E5</color>
</resources>


text:
//
//  BOXAbstractSession_Private.h
//  BoxContentSDK
//
//  Created by Andrew Chun on 6/3/15.
//  Copyright (c) 2015 Box. All rights reserved.
//

#import "BOXAbstractSession.h"
#import "BOXKeychainItemWrapper.h"

@class BOXRequest;

#define keychainUserIDKey @"user_id"
#define keychainUserNameKey @"user_name"
#define keychainAccessTokenKey @"access_token"
#define keychainAccessTokenExpirationKey @"access_token_expiration"
#define keychainUserLoginKey @"user_login"

@interface BOXAbstractSession ()

@property (nonatomic, readwrite, strong) id<UniqueSDKUser> user;

+ (NSString *)keychainIdentifierPrefix;
+ (NSString *)keychainAccessGroup;

+ (NSString *)keychainIdentifierForUserWithID:(NSString *)userID;
+ (NSString *)userIDFromKeychainIdentifier:(NSString *)identifier;

+ (BOXKeychainItemWrapper *)keychainItemWrapperForUserWithID:(NSString *)userID;

/**
 *  This method should mirror BOXContentClient's prepareRequest: for when the session needs to create a request.
 *
 *  @param request request to prepare.
 */
- (void)prepareRequest:(BOXRequest *)request;

@end


text:
namespace NVelocity.Context
{
    ///   interface to bring all necessary internal and user contexts together.
    /// this is what the AST expects to deal with.  If anything new comes
    /// along, Add it here.
    ///
    /// I will rename soon :)
    ///
    ///
    /// <author>  Geir Magnusson Jr.
    /// </author>
    /// <version>  $Id: InternalContextAdapter.java 463298 2006-10-12 16:10:32Z henning $
    /// </version>

    public interface IInternalContextAdapter : IInternalHousekeepingContext, IContext, IInternalWrapperContext, IInternalEventContext
    {
    }
}


text:
package main.routes;

import org.junit.*;

import main.domain.Booleanic;
import main.domain.Percentage;
import main.domain.Text;
import main.domain.category.Category;
import main.persistence.inmemory.InMemoryFactory;

public class ReadCategoryRouteTest extends RouteTest {
    @Override
	public void responseCodeForNoRequestBody() throws Exception {
    	assertRouteResponse("GET", "/categories/not_exists",404);
	}

	@Test
    public void integration() throws Exception {
        Category category = new Category();
        category.setId("55ec9e9ad8699a069f77a024");
        category.setName(new Text("Name 1"));
        category.setDescription(new Text("Description 1"));
        category.setDiscount(new Percentage("12"));
        category.setNeedCodeAtInscription(new Booleanic("true"));

        InMemoryFactory.getInstance().getCategoryRepository().save(category);

        assertRouteResponse("GET", "/categories/55ec9e9ad8699a069f77a024",
                "{" +
                "\"id\":\"55ec9e9ad8699a069f77a024\"," +
                "\"name\":\"Name 1\"," +
                "\"description\":\"Description 1\"," +
                "\"discount\":12," +
                "\"needCodeAtInscription\":true" +
                "}");
    }
}