text:
import proto
from proto.marshal.marshal import BaseMarshal
import pytest

def test_strict_to_proto():
    m = BaseMarshal()

    with pytest.raises(TypeError):
        m.to_proto(dict, None, strict=True)

redpajama_set_name: RedPajamaGithub


text:
namespace xFunc.Maths.Analyzers.Formatters;

/// <summary>
/// The common interface for expression formatters.
/// </summary>
/// <seealso cref="IAnalyzer{TResult}" />
public interface IFormatter : IAnalyzer<string>
{
}


text:
var RemoteSourcesCommandHandler = function(){
	this.includeInAudit = true;
}

RemoteSourcesCommandHandler.prototype.run = function(command, cParts, conn, screen, callback){

	conn.exec("conn", "SELECT REMOTE_SOURCE_NAME, ADAPTER_NAME, LOCATION, AGENT_NAME FROM PUBLIC.REMOTE_SOURCES", function(err, data) {
	    callback([err == null ? 0 : 1, err == null ? data : err, err == null ? "default" : "sql-error"]);
	})
}

module.exports = RemoteSourcesCommandHandler;


text:
#!/usr/bin/env ruby

# Verifies if paths are in the correct name directory

require 'edn'
require 'json'

def validate_paths(paths, extract_name_fn)
  paths.group_by {|path| path[%r{^[^/]+}] }.each do |actual, paths|
    # Only check latest version since previous versions may have had another name
    # e.g. color_picker -> Color Picker
    latest_version_path = paths.sort.last
    expected = extract_name_fn.call(File.read(latest_version_path))
    if expected != actual
      puts "Plugin '#{expected}' is at an invalid path: #{latest_version_path}"
    end
  end
end

validate_paths Dir.glob('**/*.edn'), lambda {|e| EDN.read(e)[:name] }
validate_paths Dir.glob('**/*.json'), lambda {|e| JSON.parse(e)['name'] }


text:
void Switch_Init(void);

void PassButtons(void);

void ClearB(void);

void ClearKeys(void);


text:
class JenkinsDashboardController < ApplicationController
  def build_summary
  end

  def build_dashboard
  end

  def index
  	# render json: Project.all
  	render json: Build.all
  	# render json: Project.all[3].builds
  	# render json: Project.all[9].builds
  end
end


text:
namespace ash {

using ViewShadowTest = views::ViewsTestBase;

TEST_F(ViewShadowTest, UseShadow) {
  views::View root;
  root.SetPaintToLayer();

  views::View* v1 = root.AddChildView(std::make_unique<views::View>());
  v1->SetPaintToLayer();
  views::View* v2 = root.AddChildView(std::make_unique<views::View>());
  v2->SetPaintToLayer();
  views::View* v3 = root.AddChildView(std::make_unique<views::View>());
  v3->SetPaintToLayer();

  auto shadow = std::make_unique<ViewShadow>(v2, 1);

  ASSERT_EQ(4u, root.layer()->children().size());
  EXPECT_EQ(v1->layer(), root.layer()->children()[0]);
  EXPECT_EQ(shadow->shadow()->layer(), root.layer()->children()[1]);
  EXPECT_EQ(v2->layer(), root.layer()->children()[2]);
  EXPECT_EQ(v3->layer(), root.layer()->children()[3]);

  shadow.reset();
  EXPECT_EQ(3u, root.layer()->children().size());
  EXPECT_EQ(v1->layer(), root.layer()->children()[0]);
  EXPECT_EQ(v2->layer(), root.layer()->children()[1]);
  EXPECT_EQ(v3->layer(), root.layer()->children()[2]);
}

TEST_F(ViewShadowTest, ShadowBoundsFollowView) {
  views::View view;
  view.SetBoundsRect(gfx::Rect(10, 20, 30, 40));

  ViewShadow shadow(&view, 1);

  EXPECT_EQ(gfx::Rect(10, 20, 30, 40), shadow.shadow()->content_bounds());

  view.SetBoundsRect(gfx::Rect(100, 110, 120, 130));
  EXPECT_EQ(gfx::Rect(100, 110, 120, 130), shadow.shadow()->content_bounds());
}

TEST_F(ViewShadowTest, ShadowBoundsFollowIndirectViewBoundsChange) {
  views::View root;
  root.SetPaintToLayer();
  root.SetBoundsRect(gfx::Rect(100, 100, 200, 200));

  views::View* parent = root.AddChildView(std::make_unique<views::View>());
  parent->SetBoundsRect(gfx::Rect(10, 20, 70, 80));
  views::View* view = parent->AddChildView(std::make_unique<views::View>());
  view->SetBoundsRect(gfx::Rect(5, 10, 20, 30));

  ViewShadow shadow(view, 1);
  EXPECT_EQ(gfx::Rect(15, 30, 20, 30), shadow.shadow()->content_bounds());

  parent->SetBoundsRect(gfx::Rect(5, 15, 60, 70));
  EXPECT_EQ(gfx::Rect(10, 25, 20, 30), shadow.shadow()->content_bounds());
}

TEST_F(ViewShadowTest, ShadowCornerRadius) {
  views::View view;
  view.SetBoundsRect(gfx::Rect(10, 20, 30, 40));

  ViewShadow shadow(&view, 1);
  shadow.SetRoundedCornerRadius(5);

  EXPECT_EQ(gfx::RoundedCornersF(5), view.layer()->rounded_corner_radii());
  EXPECT_EQ(gfx::ShadowDetails::Get(1, 5).values,
            shadow.shadow()->details_for_testing()->values);

  shadow.SetRoundedCornerRadius(2);
  EXPECT_EQ(gfx::RoundedCornersF(2), view.layer()->rounded_corner_radii());
  EXPECT_EQ(gfx::ShadowDetails::Get(1, 2).values,
            shadow.shadow()->details_for_testing()->values);
}

TEST_F(ViewShadowTest, ViewDestruction) {
  views::View root;
  root.SetPaintToLayer();
  root.SetBoundsRect(gfx::Rect(10, 20, 30, 40));

  views::View* v1 = root.AddChildView(std::make_unique<views::View>());
  ViewShadow shadow(v1, 1);
  EXPECT_EQ(2u, root.layer()->children().size());

  delete v1;
  EXPECT_TRUE(root.layer()->children().empty());
}

TEST_F(ViewShadowTest, ShadowKeepsLayerType) {
  views::View view;
  view.SetPaintToLayer(ui::LAYER_SOLID_COLOR);
  view.SetBoundsRect(gfx::Rect(10, 20, 30, 40));
  ViewShadow shadow(&view, 1);
  EXPECT_TRUE(view.layer());
  EXPECT_EQ(ui::LAYER_SOLID_COLOR, view.layer()->type());
}

}  // namespace ash


text:
<?php
if (!defined('ABSPATH')) {
	exit;
}

global $woocommerce;
?>

	<?php $woocommerce->show_messages(); ?>
	<form action="<?php echo esc_url( get_permalink(woocommerce_get_page_id('change_password')) ); ?>" method="post">

			<input type="password" class="input-text" name="password_1" id="password_1" placeholder="<?php _e( 'New password', 'lovestory' ); ?>" />

			<input type="password" class="input-text" name="password_2" id="password_2" placeholder="<?php _e( 'Re-enter new password', 'lovestory' ); ?>" />

<input type="submit" class="button" name="change_password" value="<?php _e( 'Save', 'lovestory' ); ?>" />

		<?php $woocommerce->nonce_field('change_password')?>
		<input type="hidden" name="action" value="change_password" />
	</form>


text:
package org.apache.samza.task;

import java.util.concurrent.ExecutorService;
import org.apache.samza.config.Config;
import org.apache.samza.system.IncomingMessageEnvelope;

/**
 * AsyncStreamTaskAdapter allows a StreamTask to be executed in parallel.The class
 * uses the build-in thread pool to invoke StreamTask.process and triggers
 * the callbacks once it's done. If the thread pool is null, it follows the legacy
 * synchronous model to execute the tasks on the run loop thread.
 */
public class AsyncStreamTaskAdapter implements AsyncStreamTask, InitableTask, WindowableTask, ClosableTask {
  private final StreamTask wrappedTask;
  private final ExecutorService executor;

  public AsyncStreamTaskAdapter(StreamTask task, ExecutorService executor) {
    this.wrappedTask = task;
    this.executor = executor;
  }

  @Override
  public void init(Config config, TaskContext context) throws Exception {
    if (wrappedTask instanceof InitableTask) {
      ((InitableTask) wrappedTask).init(config, context);
    }
  }

  @Override
  public void processAsync(final IncomingMessageEnvelope envelope,
      final MessageCollector collector,
      final TaskCoordinator coordinator,
      final TaskCallback callback) {
    if (executor != null) {
      executor.submit(new Runnable() {
        @Override
        public void run() {
          process(envelope, collector, coordinator, callback);
        }
      });
    } else {
      // legacy mode: running all tasks in the runloop thread
      process(envelope, collector, coordinator, callback);
    }
  }

  private void process(IncomingMessageEnvelope envelope,
      MessageCollector collector,
      TaskCoordinator coordinator,
      TaskCallback callback) {
    try {
      wrappedTask.process(envelope, collector, coordinator);
      callback.complete();
    } catch (Throwable t) {
      callback.failure(t);
    }
  }

  @Override
  public void window(MessageCollector collector, TaskCoordinator coordinator) throws Exception {
    if (wrappedTask instanceof WindowableTask) {
      ((WindowableTask) wrappedTask).window(collector, coordinator);
    }
  }

  @Override
  public void close() throws Exception {
    if (wrappedTask instanceof ClosableTask) {
      ((ClosableTask) wrappedTask).close();
    }
  }
}


text:
def mock_bundle_outdated_some
  str = %(
Fetching gem metadata from https://rubygems.org/........
Fetching version metadata from https://rubygems.org/..
Resolving dependencies...

Outdated gems included in the bundle:
  * aws-sdk (newest 2.1.32, installed 1.66.0, requested = 1.66.0) in group "default"
  * byebug (newest 6.0.2, installed 5.0.0, requested ~> 5.0.0) in group "development"
  * shoulda (newest 3.0.1, installed 2.8.0, requested ~> 2.8) in group "test"
  * minitest (newest 5.8.2, installed 5.8.1)
  * multi_json (newest 1.11.2, installed 1.9.3)
)
  allow(Gemometer::System).to receive(:bundle_outdated).and_return(str)
end

def mock_bundle_outdated_none
  str = %(
Fetching gem metadata from https://rubygems.org/............
Fetching version metadata from https://rubygems.org/..
Resolving dependencies...

Bundle up to date!
)
  allow(Gemometer::System).to receive(:bundle_outdated).and_return(str)
end


text:
package org.docksidestage.hangar.dbflute.dtomapper;

import java.util.Map;
import org.dbflute.Entity;
import org.docksidestage.hangar.dbflute.dtomapper.bs.BsWhiteBaseOne07MiracoDtoMapper;

/**
 * The DTO mapper of WHITE_BASE_ONE07_MIRACO.
 * <p>
 * You can implement your original methods here.
 * This class remains when re-generating.
 * </p>
 * @author DBFlute(AutoGenerator)
 */
public class WhiteBaseOne07MiracoDtoMapper extends BsWhiteBaseOne07MiracoDtoMapper {

    /** The serial version UID for object serialization. (Default) */
    private static final long serialVersionUID = 1L;

    public WhiteBaseOne07MiracoDtoMapper() {
    }

    public WhiteBaseOne07MiracoDtoMapper(Map<Entity, Object> relationDtoMap, Map<Object, Entity> relationEntityMap) {
        super(relationDtoMap, relationEntityMap);
    }
}


text:
require File.expand_path('../../../spec_helper', __FILE__)

describe Dataservice::ProcessExternalActivityDataJob do
  let(:template)     { double({open_responses: [], multiple_choices: [], image_questions: [], iframes: []}) }
  let(:runnable)     { double(template: template) }
  let(:offering)     { double(runnable: runnable, id: 23) }
  let(:report_learner) { double('last_run=' => true, update_fields: true)}
  let(:learner)      { double(offering: offering, report_learner: report_learner) }
  let(:good_content) do
    [
      {
        type: "open_response",
        question_id: 1
      },
      {
        type: "multiple_choice",
        question_id: 2
      },
      {
        type: "image_question",
        question_id: 3
      },
      {
        type: "external_link",
        question_type: "iframe interactive",
        question_id: 4
      },
      {
        type: "interactive",
        question_id: 5
      }
    ].to_json
  end

  let(:bad_content) do
    [
      {
        type: "fruitloops",
        question_id: 4
      },{
        type: "multiple_choice",
        question_id: 2
      },
    ].to_json
  end

  let(:json_content) { good_content }

  subject { Dataservice::ProcessExternalActivityDataJob.new(23,json_content)}
  before(:each) do
    allow(Portal::Learner).to receive_messages(:find => learner)
    allow(learner).to receive_messages(:update_report_model_cache => true)
    allow(subject).to receive(:internal_process_open_response)
    allow(subject).to receive(:internal_process_multiple_choice)
    allow(subject).to receive(:internal_process_image_question)
    allow(subject).to receive(:internal_process_external_link)
    allow(subject).to receive(:internal_process_interactive)
  end

  describe "#perform" do
    describe "with weird content" do
      let(:json_content) { bad_content }

      it "should record a name exception when performing" do
        expect(subject.content).to eq(bad_content)
        expect(Rails.logger).to receive :info
        expect(subject).to receive :internal_process_multiple_choice
        subject.perform
      end
    end

    describe "with good content" do
      it "should not record any exceptions when performing" do
        expect(subject.content).to eq(good_content)
        expect(Rails.logger).not_to receive :info
        expect(subject).to receive :internal_process_open_response
        expect(subject).to receive :internal_process_multiple_choice
        expect(subject).to receive :internal_process_image_question
        expect(subject).to receive :internal_process_external_link
        expect(subject).to receive :internal_process_interactive
        subject.perform
      end
    end
  end

  # TODO: auto-generated
  describe '#perform' do
    it 'perform' do
      _learner_id = 1
      _content = '[]'
      process_external_activity_data_job = described_class.new(_learner_id, _content)
      result = process_external_activity_data_job.perform

      expect(result).not_to be_nil
    end
  end

  # TODO: auto-generated
  describe '#internal_process_open_response' do
    it 'internal_process_open_response' do
      _learner_id = 1
      _content = '1'
      process_external_activity_data_job = described_class.new(_learner_id, _content)
      data = {}
      embeddable = FactoryBot.create(:open_response)
      result = process_external_activity_data_job.internal_process_open_response(data, embeddable)

      expect(result).not_to be_nil
    end
  end

  # TODO: auto-generated
  describe '#internal_process_multiple_choice' do
    it 'internal_process_multiple_choice' do
      _learner_id = 1
      _content = '1'
      process_external_activity_data_job = described_class.new(_learner_id, _content)
      data = { 'answer_ids' => [] }
      embeddable = FactoryBot.create(:open_response)

      result = process_external_activity_data_job.internal_process_multiple_choice(data, embeddable)

      expect(result).to be_nil
    end
  end

  # TODO: auto-generated
  describe '#internal_process_image_question' do
    it 'internal_process_image_question' do
      _learner_id = 1
      _content = '1'
      process_external_activity_data_job = described_class.new(_learner_id, _content)
      data = {}
      embeddable = FactoryBot.create(:open_response)
      result = process_external_activity_data_job.internal_process_image_question(data, embeddable)

      expect(result).not_to be_nil
    end
  end

  describe '#internal_process_external_link' do
    it 'internal_process_external_link' do
      _learner_id = 1
      _content = '1'
      process_external_activity_data_job = described_class.new(_learner_id, _content)
      data = {}
      embeddable = FactoryBot.create(:open_response)
      result = process_external_activity_data_job.internal_process_external_link(data, embeddable)

      expect(result).not_to be_nil
    end
  end

  describe '#internal_process_interactive' do
    it 'internal_process_interactive' do
      _learner_id = 1
      _content = '1'
      process_external_activity_data_job = described_class.new(_learner_id, _content)
      data = {}
      embeddable = FactoryBot.create(:open_response)
      result = process_external_activity_data_job.internal_process_interactive(data, embeddable)

      expect(result).not_to be_nil
    end
  end

  # TODO: auto-generated
  describe '#id' do
    it 'id' do
      _learner_id = double('_learner_id')
      _content = double('_content')
      process_external_activity_data_job = described_class.new(_learner_id, _content)
      result = process_external_activity_data_job.id

      expect(result).to be_nil
    end
  end

end


text:
CREATE TABLE toastable_heap(a text, b varchar, c int) distributed by (b);
CREATE TABLE toastable_ao(a text, b varchar, c int) with(appendonly=true, compresslevel=1) distributed by (b);

-- Helper function to generate a random string with given length. (Due to the
-- implementation, the length is rounded down to nearest multiple of 32.
-- That's good enough for our purposes.)
CREATE FUNCTION randomtext(len int) returns text as $$
  select string_agg(md5(random()::text),'') from generate_series(1, $1 / 32)
$$ language sql;

-- INSERT
-- uses the toast call to store the large tuples
INSERT INTO toastable_heap VALUES(repeat('a',100000), repeat('b',100001), 1);
INSERT INTO toastable_heap VALUES(repeat('A',100000), repeat('B',100001), 2);
INSERT INTO toastable_ao VALUES(repeat('a',100000), repeat('b',100001), 1);
INSERT INTO toastable_ao VALUES(repeat('A',100000), repeat('B',100001), 2);

-- uncompressable values
INSERT INTO toastable_heap VALUES(randomtext(10000000), randomtext(10000032), 3);
INSERT INTO toastable_ao VALUES(randomtext(10000000), randomtext(10000032), 3);

-- Check that tuples were toasted and are detoasted correctly. we use
-- char_length() because it guarantees a detoast without showing tho whole result
SELECT char_length(a), char_length(b), c FROM toastable_heap ORDER BY c;
SELECT char_length(a), char_length(b), c FROM toastable_ao ORDER BY c;

-- UPDATE
-- (heap rel only) and toast the large tuple
UPDATE toastable_heap SET a=repeat('A',100000) WHERE c=1;
UPDATE toastable_heap SET a=randomtext(100032) WHERE c=3;
SELECT char_length(a), char_length(b) FROM toastable_heap ORDER BY c;

-- ALTER
-- this will cause a full table rewrite. we make sure the tosted values and references
-- stay intact after all the oid switching business going on.
ALTER TABLE toastable_heap ADD COLUMN d int DEFAULT 10;
ALTER TABLE toastable_ao ADD COLUMN d int DEFAULT 10;

SELECT char_length(a), char_length(b), c, d FROM toastable_heap ORDER BY c;
SELECT char_length(a), char_length(b), c, d FROM toastable_ao ORDER BY c;

-- TRUNCATE
-- remove reference to toast table and create a new one with different values
TRUNCATE toastable_heap;
TRUNCATE toastable_ao;

INSERT INTO toastable_heap VALUES(repeat('a',100002), repeat('b',100003), 2, 20);
INSERT INTO toastable_ao VALUES(repeat('a',100002), repeat('b',100003), 2, 20);

SELECT char_length(a), char_length(b), c, d FROM toastable_heap;
SELECT char_length(a), char_length(b), c, d FROM toastable_ao;

-- TODO: figure out a way to verify that toasted data is removed after the truncate.

DROP TABLE toastable_heap;
DROP TABLE toastable_ao;

-- TODO: figure out a way to verify that the toast tables are dropped


text:
* [ ] Have you read [How to write the perfect pull request](https://github.com/blog/1943-how-to-write-the-perfect-pull-request)?
* [ ] Have you read through the [contributor guidelines](https://www.playframework.com/contributing)?
* [ ] Have you signed the [Lightbend CLA](https://www.lightbend.com/contribute/cla)?
* [ ] Have you referenced any issues you're fixing using [commit message keywords](https://help.github.com/articles/closing-issues-using-keywords/)?
* [ ] Have you added copyright headers to new files?
* [ ] Have you checked that both Scala and Java APIs are updated?
* [ ] Have you updated the documentation for both Scala and Java sections?
* [ ] Have you added tests for any changed functionality?

# Helpful things

## Fixes

Fixes #xxxx

## Purpose

What does this PR do?

## Background Context

Why did you take this approach?

## References

Are there any relevant issues / PRs / mailing lists discussions?


text:
$:.unshift File.join(File.dirname(__FILE__),'..','lib')

require 'test/unit'
require 'jmx'

class MyAttributeDynamicBean < RubyDynamicMBean
  rw_attribute :name1, :string, "My sample attribute"
  r_attribute :number1, :int, "My sample integer based attribute that is read only"
  w_attribute :number2, :int, "My sample integer based attribute that is write only"

  def intialize(type, text)
    super(type,text)
  end
  def set_number1(val)
    @number1 = val
  end

  def fetch_number2
    @number2
  end
end

class JMXAttributeTest < Test::Unit::TestCase

  def setup
    @madb = MyAttributeDynamicBean.new("test.MyTestBean","Mwahahahahahah")
  end

  #make sure we didn't break anything from a ruby perspective
  def test_can_create_bean_and_access_accessor_type_methods
    @madb.set_number1 4
    assert_nil(@madb.name1)
    @madb.name1 = "Name"
    assert_equal("Name", @madb.name1)
    assert_equal(4, @madb.number1)
    @madb.number2 = 4
    assert_equal(4, @madb.fetch_number2)
    assert_raise(NoMethodError) { @madb.number2 }
  end

  def test_get_attributes_via_dynamicmbeaninterface
    @madb.set_number1 4
    @madb.name1 = "Name"

    assert_equal(@madb.name1, @madb.getAttribute("name1").get_value.to_s)
    assert_equal(@madb.number1, @madb.getAttribute("number1").get_value)
    atts = ["name1", "number1"]
    retrieved = @madb.getAttributes(atts)
    assert_equal(2, retrieved.length)
    #TODO: assertion comparing the types in teh array to java types
  end

  def test_set_attributes_via_dynamicbeaninterface
    @madb.name1 = "blue"
    red = java.lang.String.new("red")
    attribute = javax.management.Attribute.new("name1", red)
    @madb.setAttribute(attribute)

    assert_equal("String", @madb.name1.class.to_s )
    assert_equal("red", @madb.name1)
  end

  def test_set_multiple_attributes_via_dynamicbeaninterface
    @madb.name1 = "blue"
    three = java.lang.Integer.new(3)
    red = java.lang.String.new("red")
    attribute1 = javax.management.Attribute.new("name1", red)
    attribute2 = javax.management.Attribute.new("number2", three)

    @madb.setAttributes([attribute1, attribute2])
    assert_equal("red", @madb.name1)
    assert_equal(3, @madb.fetch_number2)
  end

end


text:
package io.underscore.validation
package update

import scala.language.experimental.macros
import scala.language.higherKinds

trait UpdateValidator[A] extends ((A, A) => Seq[ValidationResult]) {
  def ~(that: UpdateValidator[A]): UpdateValidator[A] =
    this and that

  def and(that: UpdateValidator[A]): UpdateValidator[A] =
    UpdateValidator[A] { (updated, original) =>
      this(updated, original) ++ that(updated, original)
    }

  def contramap[B](func: B => A): UpdateValidator[B] =
    UpdateValidator[B] { (updated, original) =>
      this(func(updated), func(original))
    }

  def prefix[B: ValidationPathPrefix](prefixes: B *): UpdateValidator[A] =
    UpdateValidator[A] { (updated, original) =>
      this(updated, original).prefix(prefixes : _*)
    }

  def field[B](field: String, accessor: A => B)(implicit validator: UpdateValidator[B]): UpdateValidator[A] =
    this and (validator contramap accessor prefix field)

  def field[B](accessor: A => B)(implicit validator: UpdateValidator[B]): UpdateValidator[A] =
    macro ValidationMacros.fieldUpdate[A, B]

  def seqField[B](field: String, accessor: A => Seq[B])(implicit validator: UpdateValidator[B]): UpdateValidator[A] =
    this and UpdateValidator[A] { (updated, original) =>
      (accessor(updated) zip accessor(original)) flatMap validator.tupled prefix field
    }

  def seqField[B](accessor: A => Seq[B])(implicit validator: UpdateValidator[B]): UpdateValidator[A] =
    macro ValidationMacros.seqFieldUpdate[A, B]
}

object UpdateValidator {
  def apply[A](func: (A, A) => Seq[ValidationResult]) = new UpdateValidator[A] {
    def apply(updated: A, original: A) = func(updated, original)
  }
}


text:
package com.raquo.domtypes.fixtures.nodes

trait Text extends Node {

  @inline def text: String
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>Ignite Tools: UAInboxPushHandler Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css"/>

Ignite Tools

Main Page

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

Static Public Member Functions |
Properties

UAInboxPushHandler Class Reference

Inheritance diagram for UAInboxPushHandler:

  <map id="UAInboxPushHandler_map" name="UAInboxPushHandler_map">
<area href="protocol_u_a_inbox_message_list_observer-p.html" alt="<UAInboxMessageListObserver>" shape="rect" coords="0,0,197,24"/>
</map>

List of all members.

Static Public Member Functions

(void) 	+ handleNotification:forInbox:

(void) 	+ handleLaunchOptions:

(void) 	+ showMessageAfterMessageListLoaded

Properties

NSString * 	viewingMessageID

BOOL 	hasLaunchMessage

The documentation for this class was generated from the following file:

Shared/Airship/Library/InboxLib/UAInboxPushHandler.h

 All Classes Functions Variables Properties

<address class="footer">Generated on Tue Aug 30 2011 10:11:54 for Ignite Tools by

 1.7.4 </address>


text:
namespace chromeos {

MockNetworkDeviceHandler::MockNetworkDeviceHandler() = default;

MockNetworkDeviceHandler::~MockNetworkDeviceHandler() = default;

}  // namespace chromeos


text:
[![Build Status](https://github.com/abdullahselek/Lighty/workflows/Lighty%20CI/badge.svg)](https://github.com/abdullahselek/Lighty/actions)
![CocoaPods Compatible](https://img.shields.io/cocoapods/v/Lighty.svg)
[![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)
[![Swift Package Manager Compatible](https://img.shields.io/badge/Swift%20Package%20Manager-compatible-brightgreen.svg)](https://github.com/apple/swift-package-manager)
[![Coverage Status](https://coveralls.io/repos/github/abdullahselek/Lighty/badge.svg?branch=master)](https://coveralls.io/github/abdullahselek/Lighty?branch=master)
[![Platform](https://img.shields.io/cocoapods/p/Lighty.svg?style=flat)](https://cocoapods.org/pods/Lighty)
[![License](https://img.shields.io/badge/License-MIT-blue.svg)](https://github.com/abdullahselek/Lighty/blob/master/LICENSE)

# Lighty
Easy to use and lightweight logger for iOS, macOS, tvOS, watchOS and Linux in Swift.

## Screenshots

![default_theme](https://github.com/abdullahselek/Lighty/blob/master/Screenshots/default_theme.png)
![dark_theme](https://github.com/abdullahselek/Lighty/blob/master/Screenshots/dark_theme.png)

## Requirements

| Lighty Version | Minimum iOS Target | Minimum OS X Target | Minimum watchOS Target | Minimum tvOS Target | Swift Version |
|:--------------------:|:---------------------------:|:---------------------------:|:--------------------:|:---------------------------:|:---------------------------:|
| 1.1.7 | iOS 10 | OS X 10.11 | watchOS 3.0 | tvOS 10.0 | Swift 5 |
| 1.1.6 | iOS 9 | OS X 10.9 | watchOS 2.0 | tvOS 9.0 | Swift 4.1 |
| 1.1.5 | iOS 9 | OS X 10.9 | watchOS 2.0 | tvOS 9.0 | Swift 4.0 |
| 1.1.4 | iOS 9 | OS X 10.9 | watchOS 2.0 | tvOS 9.0 | Swift 3.x |

## CocoaPods

CocoaPods is a dependency manager for Cocoa projects. You can install it with the following command:
```
$ gem install cocoapods
```

To integrate Lighty into your Xcode project using CocoaPods, specify it in your Podfile:
```
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '10.0'
use_frameworks!

target '<Your Target Name>' do
	pod 'Lighty', '~>1.1.7'
end
```

Then, run the following command:
```
$ pod install
```

## Carthage

Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks.

You can install Carthage with Homebrew using the following command:

```
brew update
brew install carthage
```

To integrate Lighty into your Xcode project using Carthage, specify it in your Cartfile:

```
github "abdullahselek/Lighty" ~> 1.1.7
```

Run carthage update to build the framework and drag the built Lighty.framework into your Xcode project.

## Swift Package Manager

Modify your Package.swift file to include the following dependency:

```
.package(url: "https://github.com/abdullahselek/Lighty.git", from: "1.1.7")
```

Run  `swift package resolve`

## Example Usage
```
import Lighty
````

```
let logger = LightyLogger.sharedInstance

logger.log(type: .verbose, message: "Verbose")
logger.log(type: .debug, message: "Debug")
logger.log(type: .info, message: "Info")
logger.log(type: .warn, message: "Warn")

LightyLogger.sharedInstance.log(type: .error, message: "Error for test :)")
```

or globally add an instance to `AppDelegate`

```
import Lighty

let logger = LightyLogger.sharedInstance

class AppDelegate: UIResponder, UIApplicationDelegate {
    ...
}
```

and you can reach `logger` instance from module classes.

You can set your own date formatter and separator
```
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .long
dateFormatter.timeStyle = .long
logger.dateFormatter = dateFormatter
```

```
logger.separator = " + "
```

Enable/Disable formatted date logs
```
logger.enableDate = false
```

Enable/Disable logging
```
logger.enable = false
```

Logs for just debug mode
```
logger.dlog(type: .warn, message: "Log for just debug mode")
```


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Constants.cs" company="WildGums">
//   Copyright (c) 2008 - 2014 WildGums. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace LogViewer
{
    using System.Windows.Input;
    using Orc.Squirrel;
    using InputGesture = Catel.Windows.Input.InputGesture;

    public static class Analytics
    {
        public const string AccountId = "UA-54671533-10";

        public static class Application
        {
            public const string Name = "Application";

            public const string StartupTime = "Startup time";
        }
    }

    public static class Settings
    {
        public static class Application
        {
            public static class General
            {
                public const string EnableAnalytics = "General.EnableAnalytics";
                public const bool EnableAnalyticsDefaultValue = true;

                public const string ThemeBaseColor = "General.ThemeBaseColor";
                public const string ThemeBaseColorDefaultValue = "Light";
            }

            public static class AutomaticUpdates
            {
                public const bool CheckForUpdatesDefaultValue = false;

                public static readonly UpdateChannel[] AvailableChannels =
                {
                    new UpdateChannel("Stable", "https://downloads.wildgums.com/logviewer/stable"),
                    new UpdateChannel("Beta", "https://downloads.wildgums.com/logviewer/beta"),
                    new UpdateChannel("Alpha", "https://downloads.wildgums.com/logviewer/alpha")
                };

                public static readonly UpdateChannel DefaultChannel = AvailableChannels[0];
            }
        }

        public static class Workspace
        {
            public static class General
            {
                public const string EnableTooltips = "General.EnableToolips";
                public const bool EnableTooltipsDefaultValue = false;
            }

            public static class Filter
            {
                public const string ShowDebug = "ShowDebug";
                public const bool ShowDebugDefaultValue = true;
                public const string ShowError = "ShowError";
                public const bool ShowErrorDefaultValue = true;
                public const string ShowInfo = "ShowInfo";
                public const bool ShowInfoDefaultValue = true;
                public const string ShowWarning = "ShowWarning";
                public const bool ShowWarningDefaultValue = true;
                public const string IsUseDateRange = "IsUseDateRange";
                public const bool IsUseDateRangeDefaultValue = false;
                public const string StartDate = "StartDate";
                public const string EndDate = "EndDate";
            }
        }
    }

    public static class Commands
    {
        public static class File
        {
            public const string Exit = "File.Exit";
            public static readonly InputGesture ExitInputGesture = new InputGesture(Key.F4, ModifierKeys.Alt);
        }

        public static class Filter
        {
            public const string ResetSearchTemplate = "Filter.ResetSearchTemplate";
            public static readonly InputGesture ResetSearchTemplateInputGesture = null;

            public const string ExportResult = "Filter.ExportResult";
            public static readonly InputGesture ExportResultInputGesture = null;

            public const string CopyResultToClipboard = "Filter.CopyResultToClipboard";
            public static readonly InputGesture CopyResultToClipboardInputGesture = null;
        }

        public static class Settings
        {
            public const string General = "Settings.General";
            public static readonly InputGesture GeneralInputGesture = new InputGesture(Key.S, ModifierKeys.Alt | ModifierKeys.Control);
        }

        public static class Help
        {
            public const string About = "Help.About";
            public static readonly InputGesture AboutInputGesture = new InputGesture(Key.F1);
        }
    }

    public static class Workspaces
    {
        public const string DefaultWorkspaceName = "Default";
    }
}


text:
using NServiceBus;

public class OrderLifecycleSagaData : ContainSagaData
{
    public virtual string OrderId { get; set; }
}


text:
package baylandtag.ax_unit_test;

import javafx.beans.property.BooleanProperty;
import javafx.beans.property.StringProperty;

public interface Database {

	void connect();

	void disconnect();

	boolean isConnected();

	void setConnected(boolean value);

	BooleanProperty connectedProperty();

	String getUrl();

	void setUrl(String value);

	StringProperty urlProperty();

	String getUser();

	void setUser(String value);

	StringProperty userProperty();

	String getPassword();

	void setPassword(String value);

	StringProperty passwordProperty();

}


text:
class CreateMessages < ActiveRecord::Migration
  def change
    create_table :messages do |t|
      t.string :email
      t.string :tel
      t.text :message_description
      t.boolean :sms_notify
      t.boolean :weekly_newsletter

      t.timestamps null: false
    end
  end
end


text:
package com.jeffpeng.jmod.util;

import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Locale;

import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.ModContainer;
import cpw.mods.fml.common.registry.GameData;

/* Based on mcp.mobius.waila.utils.ModIdentification by ProfMobius released under the Apache License 2.0
 *
 */

public class ModId {

    public static HashMap<String, String> modSource_Name = new HashMap<String, String>();
    public static HashMap<String, String> modSource_ID = new HashMap<String, String>();

    public static void init() {
        for (ModContainer mod : Loader.instance().getModList()) {
            modSource_Name.put(mod.getSource().getName(), mod.getName());
            modSource_ID.put(mod.getSource().getName(), mod.getModId());
        }

        //TODO : Update this to match new version (1.7.2)
        modSource_Name.put("1.6.2.jar", "Minecraft");
        modSource_Name.put("1.6.3.jar", "Minecraft");
        modSource_Name.put("1.6.4.jar", "Minecraft");
        modSource_Name.put("1.7.2.jar", "Minecraft");
        modSource_Name.put("1.8.0.jar", "Minecraft");
        modSource_Name.put("Forge", "Minecraft");
        modSource_ID.put("1.6.2.jar", "Minecraft");
        modSource_ID.put("1.6.3.jar", "Minecraft");
        modSource_ID.put("1.6.4.jar", "Minecraft");
        modSource_ID.put("1.7.2.jar", "Minecraft");
        modSource_ID.put("1.8.0.jar", "Minecraft");
        modSource_ID.put("1.8.8.jar", "Minecraft");
        modSource_ID.put("Forge", "Minecraft");

    }

    public static String nameFromObject(Object obj) {
        String objPath = obj.getClass().getProtectionDomain().getCodeSource().getLocation().toString();

        try {
            objPath = URLDecoder.decode(objPath, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String modName = "<Unknown>";
        for (String s : modSource_Name.keySet())
            if (objPath.contains(s)) {
                modName = modSource_Name.get(s);
                break;
            }

        if (modName.equals("Minecraft Coder Pack"))
            modName = "Minecraft";

        return modName;
    }

    public static String nameFromStack(ItemStack stack) {
        try {
        	GameData.getItemRegistry().getNameForObject(stack.getItem());
            ResourceLocation resource = new ResourceLocation(GameData.getItemRegistry().getNameForObject(stack.getItem()));
            ModContainer mod = ModId.findModContainer(resource.getResourceDomain());
            String modName = mod == null ? "Minecraft" : mod.getName();
            return modName;
        } catch (NullPointerException e) {
            return "";
        }
    }

    public static ModContainer findModContainer(String modID) {
        for (ModContainer mc : Loader.instance().getModList())
            if (modID.toLowerCase(Locale.US).equals(mc.getModId().toLowerCase(Locale.US)))
                return mc;
        return null;
    }
}


text:
@implementation ZipAsset

- (id)init:(NSString *)path medatada:(NSMutableDictionary *)metadata
{
    if (self == [super init]) {
        self.path       = path;
        self.metadata   = metadata;
    }
    return self;
}

- (NSComparisonResult)compare:(ZipAsset *)other {
    return [self.path compare:other.path];
}

- (id)toJSONObject
{
    NSMutableDictionary *obj = [[NSMutableDictionary alloc] init];
    [obj setValue:self.path     forKey:@"path"];
    [obj setValue:self.metadata forKey:@"metadata"];
    return obj;
}

- (NSString *)toString
{
    NSMutableString *result = [NSMutableString stringWithString:@"{"];

    [result appendString: @"\"path\": \""];
    [result appendString: [ZipAsset escape:self.path]];
    [result appendString: @"\","];

    [result appendString: @"\"metadata\": {"];
    if (self.metadata != nil) {
        NSEnumerator *keys = [self.metadata keyEnumerator];
        BOOL first = TRUE;
        for (NSString *k in keys) {
            NSString *v = [ZipAsset escape:[self.metadata objectForKey:k]];
            if (first) {
                first = FALSE;
            } else {
                [result appendString:@","];
            }
            [result appendString:[NSString stringWithFormat:@"\"%@\": \"%@\"", [ZipAsset escape:k], [ZipAsset escape:v]]];
        }
    }
    [result appendString: @"}"];

    [result appendString: @"}"];
    return result;
}

+ (NSString *)escape:(NSString *)unescaped
{
    if (unescaped == nil) {
        return @"";
    }
    return [unescaped stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
}

@end


text:
Quarkus is built using GitHub Actions, with a mix of hosted and self-hosted runners.

## Setting up a new self-hosted runner on Mac M1

### Non-root user

GitHub Actions should not run with administrator privileges, so will need to be run in a dedicated account.
Make an account for the actions runner. The steps below assume the account has the name `githubactions`.
It's usually easiest to do account creation in the GUI, via a VNC connection. Users are managed in
the **Users and Groups** section of the Settings app.

*Grant administrator privileges to the account* (we will remove them later).

### System utilities

As administrator, install homebrew.
```shell
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
```

Install build and container utilities:

```bash
brew install mvn
brew install gradle
brew install podman
```

### Podman setup

Podman needs some [extra configuration](https://quarkus.io/guides/podman) to work with test containers and dev services.

Now log in to the account you created to run the actions.
As the `githubactions` user (but with administrator privileges)

```bash
PODMAN_VERSION=`podman -v | sed 's/[a-zA-Z ]*//'`
sudo /opt/homebrew/Cellar/podman/$PODMAN_VERSION/bin/podman-mac-helper install
```
The podman helper install seems to be per-user, but it needs to be done with administrator privileges.

Again as the `githubactions` user, edit ~/.testcontainers.properties and add the following line: `ryuk.container.privileged=true`

```bash
echo "ryuk.container.privileged=true" >> ~/.testcontainers.properties
```

```bash
podman machine set --rootful
podman machine start
```

Finally, on ARM, an [extra step](https://edofic.com/posts/2021-09-12-podman-m1-amd64) is required to make AMD64 images work:

```bash
podman machine ssh
sudo -i
rpm-ostree install qemu-user-static
systemctl reboot
```

Now remove administrator privileges from the `githubactions` user.
As with the user creation, it's usually easiest to do this in the GUI.

### Rosetta

A fresh install of macOS will not have Rosetta installed, so Intel binaries cannot run. Fix this by running:

```bash
softwareupdate --install-rosetta --agree-to-license
```
### Stand up the actions runner

#### Download the runner scripts

GitHub provides an installation package of customised runner scripts for each repository.
Follow [the instructions](https://docs.github.com/en/actions/hosting-your-own-runners/adding-self-hosted-runners)
to install the scripts for the repository to be built.

Choose the default group, a descriptive name, and the default work folder. Add a label `macos-arm64-latest`.
If you forget the label, it will need to be added [through the UI](https://docs.github.com/en/actions/hosting-your-own-runners/using-labels-with-self-hosted-runners).

#### Cleanup and setup logic

Self-hosted runners do not run on ephemeral hardware, and so workflow runs may need to clean up.
We also need to start a podman machine before the job if one is not already running.

To create cleanup and setup scripts and hooks, run:

```bash
echo "rm -rf /Users/githubactions/actions-runner/_work" > /Users/githubactions/runner-cleanup.sh
echo "podman machine info | grep Running || podman machine start" >> /Users/githubactions/podman-start.sh
chmod a+x /Users/githubactions/runner-cleanup.sh
echo ACTIONS_RUNNER_HOOK_JOB_COMPLETED=/Users/githubactions/runner-cleanup.sh >> .env
echo ACTIONS_RUNNER_HOOK_JOB_STARTED=/Users/githubactions/podman-start.sh >> .env
```

In the same script, we also ensure that the podman machine is running before jobs execute.

#### Start the runner

To test the runner, run

`run.sh`

Once you're happy the runner is processing builds correctly, it's time to create it as a daemon.

### Start the service on reboot

Note that GitHub have scripts for this, but theirs run as LaunchAgents, not LaunchDaemons.
LaunchAgents run when a user logs in, and LaunchDaemons run on boot, so the daemon option seems preferable.

As administrator, `sudo vi /Library/LaunchDaemons/actions.runner.quarkusio-quarkus.macstadium-m1.plist`.

Then add the following:

```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>actions.runner.quarkusio-quarkus.macstadium-m1</string>

    <key>RunAtLoad</key>
    <true/>

    <key>KeepAlive</key>
    <true/>

    <key>UserName</key>
    <string>githubactions</string>

    <key>ProgramArguments</key>
    <array>
     <string>/Users/githubactions/actions-runner/runsvc.sh</string>
    </array>

    <key>WorkingDirectory</key>
    <string>/Users/githubactions/actions-runner</string>

    <key>StandardOutPath</key>
    <string>/tmp/github.runner.plist.stdout</string>
    <key>StandardErrorPath</key>
    <string>/tmp/github.runner.plist.stderr</string>

    <key>EnvironmentVariables</key>
    <dict>
      <key>ACTIONS_RUNNER_SVC</key>
      <string>1</string>
    </dict>
    <key>ProcessType</key>
    <string>Interactive</string>
    <key>SessionCreate</key>
    <true/>
  </dict>
</plist>
```

Finally, run

```shell
sudo launchctl load -w /Library/LaunchDaemons/actions.runner.quarkusio-quarkus.macstadium-m1.plist
```

You can check the logs in `/tmp/github.runner.plist.stdout` to confirm everything is working.


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />

    <title>SING</title>
    <link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="style.css" />
    <link rel="stylesheet" href="node_modules/bootstrap-slider/css/bootstrap-slider.css" />

SING (Sing Is Not GNU)

Simulation

PCB

Settings

Help

Clock: 0

Quantum: 0000

New

                        <select multiple id="new-select" class="form-control"></select>

Ready

                        <select multiple id="ready-select" class="form-control"></select>

Running (4 cores)

                        <select multiple id="running-select" class="form-control"></select>

Waiting

                        <select multiple id="waiting-select" class="form-control"></select>

Using I/O

                        <select id="io-select" class="form-control"></select>

Terminated

                        <select multiple id="terminated-select" class="form-control"></select>

New process probability (%)

                      <input id="new-process-probability-slider" type="text" data-slider-max="100" style="width: 100%"/>

Algorithm

                      <input type="radio" id="rr-radio" name="algorithm-radio" />Round Robin
                      <input type="radio" id="fcfs-radio" name="algorithm-radio" />First Come First Serve

Quantum (cycles)

                      <input id="quantum-slider" type="text" data-slider-max="50" style="width: 100%"/>

Delay (seconds)

                      <input id="delay-slider" type="text" data-slider-max="10" style="width: 100%"/>

CPU Cores

                      <input id="cores-slider" type="text" data-slider-min="1" data-slider-max="4" style="width: 100%"/>

List limits

                      <input type="checkbox" id="list-limits-checkbox" />Enable list limits.

New

                      <input id="new-limit-slider" type="text" data-slider-max="50" style="width: 100%"/>

Ready

                      <input id="ready-limit-slider" type="text" data-slider-max="50" style="width: 100%"/>

Waiting

                      <input id="waiting-limit-slider" type="text" data-slider-max="50" style="width: 100%"/>

CPU cycles per process range

                      <input id="cpu-slider" type="text" class="span2" value="" data-slider-min="3" data-slider-max="100" data-slider-value="[5,15]" style="width: 100%"/>

I/O cycles per process range

                      <input id="io-slider" type="text" class="span2" value="" data-slider-min="0" data-slider-max="100" data-slider-value="[3,9]" style="width: 100%"/>

Penguin mode

                      <input type="checkbox" id="penguin-mode-checkbox" />Enable penguin mode.

                    Process ID
                    Status
                    Creation cycle
                    CPU needed
                    CPU used
                    I/O start
                    I/O time needed
                    I/O time used
                    Finished cycle
                    Waited time
                    Time in system

Help

Settings

New process probability: It is the probability of the creation of a new process each cycle.

Algorithm: The scheduling algorithm to be used.

Quantum: The quantum of each process while using Round Robin algorithm.

Delay: The time, in seconds, between each cycle. While on penguin mode, this is the time the penguin takes to move each process.

CPU cores: The number of cores of the CPU, this is, the number of processes it can handle at the same time.

List limits: When this option is checked, the lists will have a limit of processes they can hold. If they have more than the specified limit, the exceding processes will be terminated with error.

CPU cycles per process range: The number of cycles on the CPU each process need, which will be randomly generated between the specified range.

IO Cycles per process range: The number of cycles on the IO device each process need, which will be randomly generated between the specified range.

Penguin mode: When checked, a penguin will move the processes.

PCB

This table holds the information of each process, ordered by creation time.

Simulation

On this time, the simulation can be observed in real time. To play, pause, or stop the simulation, click on the buttons in the top-right corner.

Extra features

There is a penguin mode!

The settings can be changed even if the simulation is not paused.

The CPU can have many cores (between 1 and 4).

Lists can have, or not, a limit.

The CPU cycles and IO cycles are specified by a range.

About

Created with  by Javier Rizzo, for the Operating Systems class.


text:
package org.apache.camel.model.loadbalancer;

import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;

import org.apache.camel.model.LoadBalancerDefinition;
import org.apache.camel.spi.Metadata;

/**
 * Failover load balancer
 *
 * The failover load balancer is capable of trying the next processor in case an Exchange failed with an exception during processing.
 * You can constrain the failover to activate only when one exception of a list you specify occurs.
 * If you do not specify a list any exception will cause fail over to occur.
 * This balancer uses the same strategy for matching exceptions as the Exception Clause does for the onException.
 */
@Metadata(label = "eip,routing,loadbalance")
@XmlRootElement(name = "failover")
@XmlAccessorType(XmlAccessType.FIELD)
public class FailoverLoadBalancerDefinition extends LoadBalancerDefinition {
    @XmlTransient
    private List<Class<?>> exceptionTypes = new ArrayList<>();
    @XmlElement(name = "exception")
    private List<String> exceptions = new ArrayList<>();
    @XmlAttribute
    private Boolean roundRobin;
    @XmlAttribute
    private Boolean sticky;
    @XmlAttribute @Metadata(defaultValue = "-1")
    private Integer maximumFailoverAttempts;

    public FailoverLoadBalancerDefinition() {
    }

    public List<String> getExceptions() {
        return exceptions;
    }

    /**
     * A list of class names for specific exceptions to monitor.
     * If no exceptions is configured then all exceptions is monitored
     */
    public void setExceptions(List<String> exceptions) {
        this.exceptions = exceptions;
    }

    public List<Class<?>> getExceptionTypes() {
        return exceptionTypes;
    }

    /**
     * A list of specific exceptions to monitor.
     * If no exceptions is configured then all exceptions is monitored
     */
    public void setExceptionTypes(List<Class<?>> exceptionTypes) {
        this.exceptionTypes = exceptionTypes;
    }

    public Boolean getRoundRobin() {
        return roundRobin;
    }

    /**
     * Whether or not the failover load balancer should operate in round robin mode or not.
     * If not, then it will always start from the first endpoint when a new message is to be processed.
     * In other words it restart from the top for every message.
     * If round robin is enabled, then it keeps state and will continue with the next endpoint in a round robin fashion.
     *

     * You can also enable sticky mode together with round robin, if so then it will pick the last known good endpoint
     * to use when starting the load balancing (instead of using the next when starting).
     */
    public void setRoundRobin(Boolean roundRobin) {
        this.roundRobin = roundRobin;
    }

    public Boolean getSticky() {
        return sticky;
    }

    /**
     * Whether or not the failover load balancer should operate in sticky mode or not.
     * If not, then it will always start from the first endpoint when a new message is to be processed.
     * In other words it restart from the top for every message.
     * If sticky is enabled, then it keeps state and will continue with the last known good endpoint.
     *

     * You can also enable sticky mode together with round robin, if so then it will pick the last known good endpoint
     * to use when starting the load balancing (instead of using the next when starting).
     */
    public void setSticky(Boolean sticky) {
        this.sticky = sticky;
    }

    public Integer getMaximumFailoverAttempts() {
        return maximumFailoverAttempts;
    }

    /**
     * A value to indicate after X failover attempts we should exhaust (give up).
     * Use -1 to indicate never give up and continuously try to failover. Use 0 to never failover.
     * And use e.g. 3 to failover at most 3 times before giving up.
     * his option can be used whether or not roundRobin is enabled or not.
     */
    public void setMaximumFailoverAttempts(Integer maximumFailoverAttempts) {
        this.maximumFailoverAttempts = maximumFailoverAttempts;
    }

    @Override
    public String toString() {
        return "FailoverLoadBalancer";
    }
}


text:
package com.github.phenomics.ontolib.base;

/**
 * Base class for handled exceptions thrown by OntoLib.
 *
 * @author Manuel Holtgrewe
 */
public class OntoLibException extends Exception {

  private static final long serialVersionUID = 1L;

  /**
   * Constructor.
   *
   * @param message Message of exception.
   * @param cause Causing {@link Throwable}.
   */
  public OntoLibException(String message, Throwable cause) {
    super(message, cause);
  }

  /**
   * Constructor.
   *
   * @param message Message of exception.
   */
  public OntoLibException(String message) {
    super(message);
  }

}


text:
/* Header */
.handsontable td.htMergeHeader {
  background-color: #f6f8f8;
  text-align: center;
  font-weight: bold;
  color: #58666e;
  vertical-align: middle !important;
}

/*  htEditRow */
.handsontable td.htEditRow{
  text-align: center;
  vertical-align: middle !important;
}
.handsontable td.htEditRow .btn {
  border-radius: 20px;
  padding: 1px 0 0;
  cursor: pointer;
  margin: 0 auto;
  width: 20px;
  height: 19px;
}
.handsontable td.htEditRow .btn:hover {
  background-color: #777;
  color: #FFF;
}


text:
{-# LANGUAGE CPP #-}
module GHCJS.DOM.WebKitDataCue (
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
  module GHCJS.DOM.JSFFI.Generated.WebKitDataCue
#else
#endif
  ) where
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
import GHCJS.DOM.JSFFI.Generated.WebKitDataCue
#else
#endif


text:
package org.i5y.pipe

import java.io.IOException
import java.io.InputStream

import scala.concurrent.Await
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.DurationInt
import scala.util.Failure

import org.scalatest.FunSuite
import org.scalatest.matchers.ShouldMatchers

class PipeTest extends FunSuite with ShouldMatchers {

  def inputStreamLength(inputStream: InputStream) =
    Iterator.continually(inputStream.read()).takeWhile(_ != -1).size

  def delayedInputStreamLength(inputStream: InputStream) = {
    val result = inputStreamLength(inputStream)
    Thread.sleep(3000)
    result
  }

  def throwOnFifth(inputStream: InputStream) = {
    Iterator.continually(inputStream.read()).take(4)
    throw new IOException
  }

  test("Success") {
    val w = new Pipe(inputStreamLength)
    (1 to 10).foreach { x => w.write("Hello World!!".getBytes()) }
    Await.result(w.complete, 5.seconds) should be(130)
  }

  test("Success Delayed") {
    val w = new Pipe(delayedInputStreamLength)
    (1 to 10).foreach { x => w.write("Hello World!!".getBytes()) }
    Await.result(w.complete, 5.seconds) should be(130)
  }

  test("IOException") {
    val w = new Pipe(throwOnFifth)
    (1 to 10).foreach { x => w.write("Hello World!!".getBytes()) }
    val completionFuture = w.complete()
    Await.ready(completionFuture, 5.seconds)
    completionFuture.value.get match {
      case Failure(x: IOException) =>
      case _ => fail("Was expecting an IOException")
    }
  }
}


text:
package fr.pizzeria.exception;

public class CreditException extends Exception {

	public CreditException() {
		super("Credit Exception");
	}

	public CreditException(String message) {
		super(message);
		// TODO Auto-generated constructor stub
	}

	public CreditException(Throwable cause) {
		super(cause);
		// TODO Auto-generated constructor stub
	}

	public CreditException(String message, Throwable cause) {
		super(message, cause);
		// TODO Auto-generated constructor stub
	}

	public CreditException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
		super(message, cause, enableSuppression, writableStackTrace);
		// TODO Auto-generated constructor stub
	}

}


text:
[![Build Status](https://scrutinizer-ci.com/g/MehrAlsNix/zf-couchbase2/badges/build.png?b=develop)](https://scrutinizer-ci.com/g/MehrAlsNix/zf-couchbase2/build-status/develop) [![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/MehrAlsNix/zf-couchbase2/badges/quality-score.png?b=develop)](https://scrutinizer-ci.com/g/MehrAlsNix/zf-couchbase2/?branch=develop) [![Code Coverage](https://scrutinizer-ci.com/g/MehrAlsNix/zf-couchbase2/badges/coverage.png?b=develop)](https://scrutinizer-ci.com/g/MehrAlsNix/zf-couchbase2/?branch=develop)

## The Couchbase Adapter

The `MehrAlsNix\ZF\Cache\Storage\Adapter\Couchbase` adapter stores cache items
over the couchbase protocol. It's using the required PHP extension [couchbase](https://github.com/couchbase/php-couchbase)
which is based on [Libcouchbase](https://github.com/couchbase/libcouchbase).

This adapter implements the following interfaces:

- `Zend\Cache\Storage\StorageInterface`
- `Zend\Cache\Storage\FlushableInterface`


text:
/*
 ONOS GUI -- Widget -- Tooltip Service
 */

(function () {
    'use strict';

    // injected references
    var $log, $timeout, fs;

    // constants
    var hoverHeight = 35,
        hoverDelay = 500,
        exitDelay = 100;

    // internal state
    var tooltip, currElemId;

    // === Helper functions ---------------------------------------------

    function init() {
        tooltip = d3.select('#tooltip');
        tooltip.html('');
    }

    function tipStyle(mouseX, mouseY) {
        var winWidth = fs.windowSize().width,
            winHeight = fs.windowSize().height,
            style = {
                display: 'inline-block'
            };

        if (mouseX <= (winWidth / 2)) {
            style.left = mouseX + 'px';
        } else {
            style.right = (winWidth - mouseX) + 'px';
        }

        if (mouseY <= (winHeight / 2)) {
            style.top = (mouseY + (hoverHeight - 10)) + 'px';
        } else {
            style.top = (mouseY - hoverHeight) + 'px';
        }

        return style;
    }

    // === API functions ------------------------------------------------

    function showTooltip(el, msg) {
        if (!el || !msg) {
            return;
        }
        var elem = d3.select(el),
            mouseX = d3.event.pageX,
            mouseY = d3.event.pageY,
            style = tipStyle(mouseX, mouseY);
        currElemId = elem.attr('id');

        tooltip.transition()
            .delay(hoverDelay)
            .each('start', function () {
                d3.select(this).style('display', 'none');
            })
            .each('end', function () {
                d3.select(this).style(style)
                    .text(msg);
            });
    }

    function cancelTooltip(el) {
        if (!el) {
            return;
        }
        var elem = d3.select(el);

        if (elem.attr('id') === currElemId) {
            tooltip.transition()
                .delay(exitDelay)
                .style({
                    display: 'none'
                })
                .text('');
        }
    }

    angular.module('onosWidget')
        .factory('TooltipService', ['$log', '$timeout', 'FnService',

        function (_$log_, _$timeout_, _fs_) {
            $log = _$log_;
            $timeout = _$timeout_;
            fs = _fs_;

            init();

            return {
                showTooltip: showTooltip,
                cancelTooltip: cancelTooltip
            };
        }]);
}());


text:
const chai = require('chai')
const chaiAsPromised = require('chai-as-promised')
const sinon = require('sinon')
const sinonChai = require('sinon-chai')

chai.use(sinonChai)
chai.use(chaiAsPromised)

const { assert } = chai
const { stub } = sinon

const handler = require('./handler').createHandler

describe('./tests/integration/target/handler.js', () => {
  describe('#handler', () => {
    const eventHandlerAsync = impl =>
      (event, context) =>
        new Promise((resolve, reject) =>
          handler({}).eventHandler(impl)(
            event,
            context,
            (err, result) => (err ? reject(err) : resolve(result))
          )
        )

    it('should callback with an error when impl throws', () => {
      const err = new Error()
      return assert.isRejected(eventHandlerAsync(() => { throw err })(), err)
    })

    it('should callback with an error when impl rejects', () => {
      const err = { statusCode: 500 }
      return assert.isRejected(eventHandlerAsync(() => Promise.reject(err))(), err)
    })

    it('should pass the event to the implementation', () => {
      const impl = stub()
      const event = {}
      return eventHandlerAsync(impl)(event)
        .then(() => assert.isOk(impl.calledOnce))
        .then(() => assert.isOk(impl.calledWithExactly(event)))
    })

    it('should return the result to lambda', () => {
      const expected = { statusCode: 200, body: '{}' }
      const impl = stub().returns({})
      return eventHandlerAsync(impl)()
        .then(result => assert.deepEqual(result, expected))
    })
  })

  describe('#handlerResponse', () => {
    it('should create a success message', () =>
      assert.deepStrictEqual(
        handler({}).handlerSuccess({ foo: 'bar' }),
        { statusCode: 200, body: '{"foo":"bar"}' }
      )
    )
  })

  describe('#handlerError', () => {
    it('should create and log a failure message', () =>
      assert.deepStrictEqual(
        handler({}).handlerError(new Error('this is an error')),
        { statusCode: 500 }
      )
    )
  })

  const testId = '/this/is/a/test'
  const err = new Error('reasons')

  describe('#test', () => {
    it('should return handler response on success', () =>
      handler({
        recordRequest: id => assert(id, testId, 'correct test id is recorded'),
      }).test({ pathParameters: { id: testId } }, {}, () => {})
    )

    it('should return handler error on fail', () =>
      handler({
        recordRequest: () => { throw err },
      }).test({ pathParameters: { id: testId } }, {}, actual => assert.equal(actual, 'Error: reasons'))
    )
  })

  describe('#list', () => {
    it('gets the results for the correct test id', () =>
      handler({
        getRequests: id => assert(id, testId, 'correct test id is requested'),
      }).list({ pathParameters: { id: testId } }, {}, () => {})
    )

    it('uses default start time', () =>
      handler({
        getRequests: (id, start) => assert(start, 0, 'correct default start time is provided'),
      }).list({ pathParameters: { id: testId } }, {}, () => {})
    )

    it('uses default start time', () =>
      handler({
        getRequests: (id, start, end) => assert(end, Number.MAX_SAFE_INTEGER, 'correct default end time is provided'),
      }).list({ pathParameters: { id: testId } }, {}, () => {})
    )

    it('uses start time from parameters, if provided', () =>
      handler({
        getRequests: (id, start) => assert(start, 1000, 'start time parameter is honored'),
      }).list({
        pathParameters: { id: testId },
        queryStringParameters: { start: 1000 },
      }, {}, () => {})
    )

    it('uses end time from parameters, if provided', () =>
      handler({
        getRequests: (id, start, end) => assert(end, 2000, 'end time parameter is honored'),
      }).list({
        pathParameters: { id: testId },
        queryStringParameters: { end: 2000 },
      }, {}, () => {})
    )

    it('uses both start and end time from parameters, if provided', () =>
      handler({
        getRequests: (id, start, end) => {
          assert(start, 1000, 'start time parameter is honored')
          assert(end, 2000, 'end time parameter is honored')
        },
      }).list({
        pathParameters: { id: testId },
        queryStringParameters: {
          start: 1000,
          end: 2000,
        },
      }, {}, () => {})
    )
  })
})


text:
package com.zr.dao.impl;

import java.sql.Connection;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.json.JsonObject;

import com.mysql.jdbc.PreparedStatement;
import com.zr.connection.DBConnection;
import com.zr.dao.TeacherDao;
import com.zr.model.Staff;

import com.mysql.jdbc.PreparedStatement;
import com.zr.connection.DBConnection;
import com.zr.dao.TeacherDao;
import com.zr.model.Paper;

import com.zr.model.Reply;

import com.zr.model.Student;
import com.zr.service.TeacherService;

import net.sf.json.JSONObject;

public class TeacherDaoImpl implements TeacherDao {

	@Override
	public JSONObject selectAllScores(int eid, int page, int pageSize) {
		JSONObject json = new JSONObject();
		List<Student> list = new ArrayList<Student>();
		StringBuffer sql = new StringBuffer();
		Connection con = DBConnection.getConnection();

		sql.append("select s.s_num,s.s_id,s.s_name,s.score ");
		sql.append("from student s ");
		sql.append("join sub b ");
		sql.append("on b.sub_id = s.sub_id ");
		sql.append("where b.e_id = ? limit ?,?");
		try {
			PreparedStatement pst = (PreparedStatement) con.prepareStatement(sql.toString());
			pst.setInt(1, eid);
			pst.setInt(2, (page-1)*pageSize);
			pst.setInt(3, pageSize);
			ResultSet rst = pst.executeQuery();
			while (rst.next()) {
				Student stu = new Student();
				stu.setSid(rst.getInt("s_id"));
				stu.setSname(rst.getString("s_name"));
				stu.setNum(rst.getInt("s_num"));
				stu.setScore(rst.getInt("score"));
				list.add(stu);
				json.put("rows", list);

			}

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return json;
	}

	@Override
	public void insertStudentScore(int sid, int score) {
		JSONObject json = new JSONObject();

		StringBuffer sql = new StringBuffer();
		Connection con = DBConnection.getConnection();

		sql.append("update student set score = ? ");
		sql.append("where s_id = ?");

		try {
			PreparedStatement pst = (PreparedStatement) con.prepareStatement(sql.toString());
			pst.setInt(1, score);
			pst.setInt(2, sid);
			pst.executeUpdate();

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public List<Staff> selectTeacher() {
		// TODO Auto-generated method stub
		StringBuffer sql = new StringBuffer();
		sql.append("select a.e_id,a.e_name,a.e_col,b.c_name,a.e_num,a.e_psw ");
		sql.append("from staff a,college b,staff_role c ");
		sql.append("where a.e_col = b.c_id and a.e_id = c.e_id and c.r_id = 3");
		List<Staff> list = new ArrayList<Staff>();
		Connection con = DBConnection.getConnection();
		try {
			PreparedStatement pst = (PreparedStatement) con.prepareStatement(sql.toString());
			ResultSet res = pst.executeQuery();
			while (res.next()) {
				Staff sta = new Staff();
				sta.setEcol(res.getInt("e_col"));
				sta.setEcolname(res.getString("c_name"));
				sta.setEname(res.getString("e_name"));
				sta.setEid(res.getInt("e_id"));
				sta.setEmnum(res.getInt("e_num"));
				sta.setEpsw(res.getString("e_psw"));
				list.add(sta);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public int selectTeacherCount() {
		// TODO Auto-generated method stub
		StringBuffer sql = new StringBuffer();
		sql.append("select count(a.e_id)as t_count ");
		sql.append("from staff a,college b,staff_role c ");
		sql.append("where a.e_col = b.c_id and a.e_id = c.e_id and c.r_id = 3");
		Connection con = DBConnection.getConnection();
		try {
			PreparedStatement pst = (PreparedStatement) con.prepareStatement(sql.toString());
			ResultSet res = pst.executeQuery();
			if (res.next()) {
				int count = res.getInt("t_count");
				return count;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 0;
	}

	@Override
	public int deleteTeacher(int eid) {
		// TODO Auto-generated method stub
		StringBuffer sql = new StringBuffer();
		sql.append("delete from staff ");
		sql.append("where e_id=? ");
		Connection con = DBConnection.getConnection();
		try {
			PreparedStatement pst = (PreparedStatement) con.prepareStatement(sql.toString());
			pst.setInt(1, eid);
			int i = pst.executeUpdate();
			return i;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 0;
	}

	@Override
	public int deleteTeacherRole(int eid) {
		// TODO Auto-generated method stub
		StringBuffer sql = new StringBuffer();
		sql.append("delete from staff_role ");
		sql.append("where e_id=? ");
		Connection con = DBConnection.getConnection();
		try {
			PreparedStatement pst = (PreparedStatement) con.prepareStatement(sql.toString());
			pst.setInt(1, eid);
			int i = pst.executeUpdate();
			return i;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 0;
	}

	@Override
	public int updateTeacher(int eid, String ename, int colid, int emnum) {
		// TODO Auto-generated method stub
		StringBuffer sql = new StringBuffer();
		int i = 0;
		sql.append("update staff ");
		sql.append("set e_name=?,e_col=?,e_num=? ");
		sql.append("where e_id=? ");
		Connection con = DBConnection.getConnection();
		try {
			PreparedStatement pst = (PreparedStatement) con.prepareStatement(sql.toString());
			pst.setString(1, ename);
			pst.setInt(2, colid);
			pst.setInt(3, emnum);
			pst.setInt(4, eid);
			i = pst.executeUpdate();
			return i;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return i;

	}

	@Override
	public JSONObject checkReplyMisson() {

		JSONObject json = new JSONObject();
		List<Reply> list = new ArrayList<Reply>();
		StringBuffer sql = new StringBuffer();
		Connection con = DBConnection.getConnection();
		sql.append("select r.reply_site,b.sub_name,r.reply_start ");
		sql.append("from reply r ");
		sql.append("join sub b ");
		sql.append("on b.sub_id = r.sub_id ");

		try {
			PreparedStatement pst = (PreparedStatement) con.prepareStatement(sql.toString());

			ResultSet rst = pst.executeQuery();
			while (rst.next()) {
				Reply re = new Reply();
				re.setReplysite(rst.getString("reply_site"));
				re.setSubname(rst.getString("sub_name"));
				re.setReplystart(rst.getString("reply_start"));

				list.add(re);
				json.put("rows", list);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return json;
	}

	@Override
	public int insertTeacher(String ename, int colid, int emnum, String epsw) {
		// TODO Auto-generated method stub
		int i = 0;
		StringBuffer sql = new StringBuffer();
		sql.append("insert into staff (e_name,e_col,e_num,e_psw) ");
		sql.append("value (?,?,?,?) ");
		Connection con = DBConnection.getConnection();
		try {
			PreparedStatement pst = (PreparedStatement) con.prepareStatement(sql.toString());
			pst.setString(1, ename);
			pst.setInt(2, colid);
			pst.setInt(3, emnum);
			pst.setString(4, epsw);
			i = pst.executeUpdate();
			return i;

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return i;
	}

	@Override
	public String getSnumBySid(int id) {
		StringBuffer sql = new StringBuffer();
		Connection con = DBConnection.getConnection();
		String s = "";
		int num;
		sql.append("select s_num from student ");
		sql.append("where s_id = ?");

		try {
			PreparedStatement pst = (PreparedStatement) con.prepareStatement(sql.toString());
			pst.setInt(1, id);
			ResultSet st = pst.executeQuery();
			while (st.next()) {
				num = (st.getInt("s_num"));
				s = "" + num;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();

		}
		return s;
	}

	@Override
	public int selectTeacherEidByEnum(int e_num) {
		// TODO Auto-generated method stub
		StringBuffer sql = new StringBuffer();
		sql.append("select e_id from staff where e_num=? ");
		Connection con = DBConnection.getConnection();
		try {
			PreparedStatement pst = (PreparedStatement) con.prepareStatement(sql.toString());
			pst.setInt(1, e_num);
			ResultSet res = pst.executeQuery();
			if (res.next()) {
				int eid = res.getInt("e_id");
				return eid;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 0;
	}

	@Override
	public int getstudentcount(int eid) {

		// TODO Auto-generated method stub
		StringBuffer sql = new StringBuffer();
		int count;
		sql.append("select count(s_id) from student ");
		sql.append("inner join sub b ");
		sql.append("where b.e_id = ? ");
		Connection con = DBConnection.getConnection();
		try {
			PreparedStatement pst = (PreparedStatement) con.prepareStatement(sql.toString());
			pst.setInt(1, eid);
			ResultSet res = pst.executeQuery();
			if (res.next()) {
				count = res.getInt("count(s_id)");
				return count;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 0;

	}

	@Override
	public int[] selectSidsByEid(int eid) {
		StringBuffer sql = new StringBuffer();
		Connection con = DBConnection.getConnection();
		int[] sids = new int[] {};
		String s = "";
		int sid;
		sql.append("select s.s_id from student s ");
		sql.append("inner join sub b ");
		sql.append("where b.e_id = ?");

		try {
			PreparedStatement pst = (PreparedStatement) con.prepareStatement(sql.toString());
			pst.setInt(1, eid);
			ResultSet st = pst.executeQuery();
			while (st.next()) {
				sid = (st.getInt("s_id"));
				for (int i = 0; i < sids.length; i++) {
					sids[i] = sid;
				}

			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();

		}
		return sids;
	}

	@Override
	public void getStudentPapers() {
		StringBuffer sql = new StringBuffer();
		Connection con = DBConnection.getConnection();

		sql.append("insert into paper(lw_name, s_id) ");
		sql.append("select wx_name,s_id from literature l ");

		sql.append("where l.wxlx_id = 7 ");

		try {
			PreparedStatement pst = (PreparedStatement) con.prepareStatement(sql.toString());

			pst.executeUpdate();

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();

		}

	}

	@Override
	public List<JSONObject> getAllPapersOfStudent(int eid, int page, int pageSize) {
		StringBuffer sql = new StringBuffer();
		Connection con = DBConnection.getConnection();
		List<JSONObject> list = new ArrayList<JSONObject>();
		sql.append("select p.lw_id, p.lw_name,p.s_id,s.s_num,s.s_name,p.lw_state,p.lw_operate,p.lw_backload from paper p ");
		sql.append("join student s ");
		sql.append("on s.s_id = p.s_id ");
		sql.append("join sub b ");
		sql.append("on b.sub_id= s.sub_id ");
		sql.append("where b.e_id = ? limit ?,?" );

		try {
			PreparedStatement pst = (PreparedStatement) con.prepareStatement(sql.toString());
			pst.setInt(1, eid);
			pst.setInt(2, (page-1)*pageSize);
			pst.setInt(3,pageSize);
			ResultSet st = pst.executeQuery();
			while (st.next()) {
				JSONObject json = new JSONObject();
				int snum = st.getInt("s_num");
				String lwname =st.getString("lw_name");
				System.out.println(lwname);
				//Paper p= new Paper();
				json.put("lwid", st.getInt("lw_id"));
				json.put("lwname",""+lwname+"");
				json.put("sid", st.getInt("s_id"));
				json.put("snum", snum);

				json.put("sname",st.getString("s_name"));
				json.put("lwstate",st.getString("lw_state"));

				json.put("lwoperate", st.getString("lw_operate"));
				json.put("lwbackload",st.getString("lw_backload"));
			    list.add(json);

			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();

		}
		return list;
	}

	@Override
	public int getPapersCount(int eid) {
		// TODO Auto-generated method stub
		StringBuffer sql = new StringBuffer();
		int count;
		sql.append("select count(p.lw_id) from paper p ");
		sql.append("join student s ");
		sql.append("on s.s_id = p.s_id ");
		sql.append("join sub b ");
		sql.append("on b.sub_id= s.sub_id ");
		sql.append("where b.e_id = ? " );
		Connection con = DBConnection.getConnection();
		try {
			PreparedStatement pst = (PreparedStatement) con.prepareStatement(sql.toString());
			pst.setInt(1, eid);
			ResultSet res = pst.executeQuery();
			if (res.next()) {
				count = res.getInt("count(p.lw_id)");
				return count;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 0;

	}

	@Override
	public int checkPapersOfStudent(int lwid, String state) {
		StringBuffer sql = new StringBuffer();
		Connection con = DBConnection.getConnection();

		sql.append("update paper set lw_state =? ");
		sql.append("where lw_id = ? ");

		try {
			PreparedStatement pst = (PreparedStatement) con.prepareStatement(sql.toString());
			pst.setString(1, state);
            pst.setInt(2, lwid);

			int i = pst.executeUpdate();

             return i;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();

		}

		return 0;
	}
}


text:
#include "tensorflow/core/common_runtime/kernel_benchmark_testlib.h"

#include <vector>
#include "tensorflow/core/common_runtime/device.h"
#include "tensorflow/core/common_runtime/device_factory.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/op_segment.h"
#include "tensorflow/core/graph/graph.h"
#include "tensorflow/core/kernels/ops_util.h"
#include "tensorflow/core/lib/core/notification.h"
#include "tensorflow/core/lib/core/threadpool.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/platform/host_info.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/test_benchmark.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/public/session_options.h"
#include "tensorflow/core/public/version.h"
#include "tensorflow/core/util/device_name_utils.h"

namespace tensorflow {
namespace test {

Benchmark::Benchmark(const string& device, Graph* g,
                     const SessionOptions* options, Graph* init) {

  SessionOptions default_options;
  if (!options) {
    options = &default_options;
  }

  testing::StopTiming();
  string t = str_util::Uppercase(device);
  device_ =
      DeviceFactory::NewDevice(t, *options, "/job:localhost/replica:0/task:0");
  CHECK(device_) << "Could not create a " << device << " device";

  pool_ = new thread::ThreadPool(options->env, "blocking",
                                 port::NumSchedulableCPUs());

  auto runner = [this](std::function<void()> closure) {
    pool_->Schedule(closure);
  };

  rendez_ = NewLocalRendezvous();

  const int graph_def_version = g->versions().producer();

  LocalExecutorParams params;
  params.device = device_;
  params.function_library = nullptr;
  params.create_kernel = [this, graph_def_version](const NodeDef& ndef,
                                                   OpKernel** kernel) {
    return CreateNonCachedKernel(device_, nullptr, ndef, graph_def_version,
                                 kernel);
  };
  params.delete_kernel = [](OpKernel* kernel) {
    DeleteNonCachedKernel(kernel);
  };

  if (init) {
    Executor* init_exec;
    TF_CHECK_OK(NewLocalExecutor(params, init, &init_exec));
    Executor::Args args;
    args.rendezvous = rendez_;
    args.runner = runner;
    TF_CHECK_OK(init_exec->Run(args));
    delete init_exec;
  }

  TF_CHECK_OK(NewLocalExecutor(params, g, &exec_));
}

Benchmark::~Benchmark() {
  if (device_) {
    rendez_->Unref();
    delete exec_;
    delete device_;
    delete pool_;
  }
}

void Benchmark::Run(int iters) { RunWithArgs({}, {}, iters); }

string GetRendezvousKey(const Node* node) {
  string send_device;
  TF_CHECK_OK(GetNodeAttr(node->def(), "send_device", &send_device));
  string recv_device;
  TF_CHECK_OK(GetNodeAttr(node->def(), "recv_device", &recv_device));
  string tensor_name;
  TF_CHECK_OK(GetNodeAttr(node->def(), "tensor_name", &tensor_name));
  uint64 send_device_incarnation;
  TF_CHECK_OK(GetNodeAttr(node->def(), "send_device_incarnation",
                          reinterpret_cast<int64*>(&send_device_incarnation)));
  return Rendezvous::CreateKey(send_device, send_device_incarnation,
                               recv_device, tensor_name, FrameAndIter(0, 0));
}

void Benchmark::RunWithArgs(
    const std::vector<std::pair<const Node*, Tensor>>& inputs,
    const std::vector<const Node*>& outputs, int iters) {
  if (!device_ || iters == 0) {
    return;
  }
  // Gets inputs' and outputs' rendezvous keys.
  std::vector<std::pair<string, Tensor>> in;
  for (const auto& p : inputs) {
    in.push_back({GetRendezvousKey(p.first), p.second});
  }
  std::vector<string> out;
  for (const auto& n : outputs) {
    out.push_back(GetRendezvousKey(n));
  }
  Tensor unused;  // In benchmark, we don't care the return value.
  bool is_dead;

  // Warm up
  Executor::Args args;
  args.rendezvous = rendez_;
  args.runner = [this](std::function<void()> closure) {
    pool_->Schedule(closure);
  };
  for (int i = 0; i < 3; ++i) {
    for (const auto& p : in) {
      rendez_->Send(p.first, Rendezvous::Args(), p.second, false);
    }
    TF_CHECK_OK(exec_->Run(args));
    for (const string& key : out) {
      rendez_->Recv(key, Rendezvous::Args(), &unused, &is_dead);
    }
  }
  TF_CHECK_OK(device_->Sync());

  testing::StartTiming();
  while (iters-- > 0) {
    for (const auto& p : in) {
      rendez_->Send(p.first, Rendezvous::Args(), p.second, false);
    }
    TF_CHECK_OK(exec_->Run(args));
    for (const string& key : out) {
      rendez_->Recv(key, Rendezvous::Args(), &unused, &is_dead);
    }
  }

  TF_CHECK_OK(device_->Sync());
  testing::StopTiming();
}

}  // end namespace test
}  // end namespace tensorflow