text:
module Braintree
  class TestingGateway # :nodoc:

    def initialize(gateway)
      @gateway = gateway
      @config = gateway.config
      @config.assert_has_access_token_or_keys
      @transaction_gateway = TransactionGateway.new(gateway)
    end

    def settle(transaction_id)
      check_environment

      response = @config.http.put("#{@config.base_merchant_path}/transactions/#{transaction_id}/settle")
      @transaction_gateway._handle_transaction_response(response)
    end

    def settlement_confirm(transaction_id)
      check_environment

      response = @config.http.put("#{@config.base_merchant_path}/transactions/#{transaction_id}/settlement_confirm")
      @transaction_gateway._handle_transaction_response(response)
    end

    def settlement_decline(transaction_id)
      check_environment

      response = @config.http.put("#{@config.base_merchant_path}/transactions/#{transaction_id}/settlement_decline")
      @transaction_gateway._handle_transaction_response(response)
    end

    def settlement_pending(transaction_id)
      check_environment

      response = @config.http.put("#{@config.base_merchant_path}/transactions/#{transaction_id}/settlement_pending")
      @transaction_gateway._handle_transaction_response(response)
    end

    def check_environment
      raise TestOperationPerformedInProduction if @config.environment == :production
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
import wtforms_json
from wtforms import Form
from wtforms.fields import BooleanField, StringField

wtforms_json.init()

class LocationForm(Form):
    name = StringField()
    address = StringField()

class EventForm(Form):
    name = StringField()
    is_public = BooleanField()

json = {
    'name': 'First Event',
    'location': {'name': 'some location'},
}

form = EventForm.from_json(json)

print(form.data)
print(form.patch_data)

# json = {
#     'some_unknown_key': 'some_value'
# }

# Throws exception
# form = EventForm.from_json(json, skip_unknown_keys=False)


text:
package org.bakasoft.dbchord.schema;

import org.bakasoft.dbchord.ApplicationException;
import org.bakasoft.dbchord.tools.StringTool;

abstract public class NamedElement<P> extends Element<P> {

	private String name;

	@Override
	public String getName() {
		return name;
	}

	public void setName(final String name) {
		if (StringTool.isEmpty(name)) {
			throw new ApplicationException("missing name");
		}

		if (container != null && StringTool.areDifferent(this.name, name) && container.containsName(name)) {
			throw new ApplicationException("name already exists");
		}

		this.name = name;
	}
}


text:
RSpec.describe RuboCop::Cop::Lint::Void do
  subject(:cop) { described_class.new(config) }

  let(:config) { RuboCop::Config.new }

  described_class::BINARY_OPERATORS.each do |op|
    it "registers an offense for void op #{op} if not on last line" do
      inspect_source(<<-RUBY.strip_indent)
        a #{op} b
        a #{op} b
        a #{op} b
      RUBY
      expect(cop.offenses.size).to eq(2)
    end
  end

  described_class::BINARY_OPERATORS.each do |op|
    it "accepts void op #{op} if on last line" do
      expect_no_offenses(<<-RUBY.strip_indent)
        something
        a #{op} b
      RUBY
    end
  end

  described_class::BINARY_OPERATORS.each do |op|
    it "accepts void op #{op} by itself without a begin block" do
      expect_no_offenses("a #{op} b")
    end
  end

  unary_operators = %i[+ - ~ !]
  unary_operators.each do |op|
    it "registers an offense for void op #{op} if not on last line" do
      inspect_source(<<-RUBY.strip_indent)
        #{op}b
        #{op}b
        #{op}b
      RUBY
      expect(cop.offenses.size).to eq(2)
    end
  end

  unary_operators.each do |op|
    it "accepts void op #{op} if on last line" do
      expect_no_offenses(<<-RUBY.strip_indent)
        something
        #{op}b
      RUBY
    end
  end

  unary_operators.each do |op|
    it "accepts void op #{op} by itself without a begin block" do
      expect_no_offenses("#{op}b")
    end
  end

  %w[var @var @@var VAR $var].each do |var|
    it "registers an offense for void var #{var} if not on last line" do
      inspect_source(["#{var} = 5",
                      var,
                      'top'])
      expect(cop.offenses.size).to eq(1)
    end
  end

  %w(1 2.0 :test /test/ [1] {}).each do |lit|
    it "registers an offense for void lit #{lit} if not on last line" do
      inspect_source([lit,
                      'top'])
      expect(cop.offenses.size).to eq(1)
    end
  end

  it 'registers an offense for void `self` if not on last line' do
    expect_offense(<<-RUBY.strip_indent)
      self; top
      ^^^^ `self` used in void context.
    RUBY
  end

  it 'registers an offense for void `defined?` if not on last line' do
    expect_offense(<<-RUBY.strip_indent)
      defined?(x)
      ^^^^^^^^^^^ `defined?(x)` used in void context.
      top
    RUBY
  end

  context 'when checking for methods with no side effects' do
    let(:config) do
      RuboCop::Config.new(
        'Lint/Void' => {
          'CheckForMethodsWithNoSideEffects' => true
        }
      )
    end

    it 'registers an offense if not on last line' do
      expect_offense(<<-RUBY.strip_indent)
        x.sort
        ^^^^^^ Method `#sort` used in void context. Did you mean `#sort!`?
        top(x)
      RUBY
    end

    it 'registers an offense for chained methods' do
      expect_offense(<<-RUBY.strip_indent)
        x.sort.flatten
        ^^^^^^^^^^^^^^ Method `#flatten` used in void context. Did you mean `#flatten!`?
        top(x)
      RUBY
    end
  end

  context 'when not checking for methods with no side effects' do
    let(:config) do
      RuboCop::Config.new(
        'Lint/Void' => {
          'CheckForMethodsWithNoSideEffects' => false
        }
      )
    end

    it 'does not register an offense for void nonmutating methods' do
      expect_no_offenses(<<-RUBY.strip_indent)
        x.sort
        top(x)
      RUBY
    end
  end

  it 'registers an offense for void literal in a method definition' do
    expect_offense(<<-RUBY.strip_indent)
      def something
        42
        ^^ Literal `42` used in void context.
        42
      end
    RUBY
  end

  it 'registers two offenses for void literals in an initialize method' do
    expect_offense(<<-RUBY.strip_indent)
      def initialize
        42
        ^^ Literal `42` used in void context.
        42
        ^^ Literal `42` used in void context.
      end
    RUBY
  end

  it 'registers two offenses for void literals in a setter method' do
    expect_offense(<<-RUBY.strip_indent)
      def foo=(rhs)
        42
        ^^ Literal `42` used in void context.
        42
        ^^ Literal `42` used in void context.
      end
    RUBY
  end

  it 'registers two offenses for void literals in a `#each` method' do
    expect_offense(<<-RUBY.strip_indent)
      array.each do |_item|
        42
        ^^ Literal `42` used in void context.
        42
        ^^ Literal `42` used in void context.
      end
    RUBY
  end

  it 'handles `#each` block with single expression' do
    expect_offense(<<-RUBY.strip_indent)
      array.each do |_item|
        42
        ^^ Literal `42` used in void context.
      end
    RUBY
  end

  it 'handles empty block' do
    expect_no_offenses(<<-RUBY.strip_indent)
      array.each { |_item| }
    RUBY
  end

  it 'registers two offenses for void literals in `#tap` method' do
    expect_offense(<<-RUBY.strip_indent)
      foo.tap do |x|
        42
        ^^ Literal `42` used in void context.
        42
        ^^ Literal `42` used in void context.
      end
    RUBY
  end

  it 'registers two offenses for void literals in a `for`' do
    expect_offense(<<-RUBY.strip_indent)
      for _item in array do
        42
        ^^ Literal `42` used in void context.
        42
        ^^ Literal `42` used in void context.
      end
    RUBY
  end

  it 'handles explicit begin blocks' do
    expect_offense(<<-RUBY.strip_indent)
      begin
       1
       ^ Literal `1` used in void context.
       2
      end
    RUBY
  end

  it 'accepts short call syntax' do
    expect_no_offenses(<<-RUBY.strip_indent)
      lambda.(a)
      top
    RUBY
  end

  it 'accepts backtick commands' do
    expect_no_offenses(<<-RUBY.strip_indent)
      `touch x`
      nil
    RUBY
  end

  it 'accepts percent-x commands' do
    expect_no_offenses(<<-RUBY.strip_indent)
      %x(touch x)
      nil
    RUBY
  end
end


text:
void clock_timer_init(void);

uint8_t clock_timer_consume_overflows(void);

void clock_timer_add_overflows(uint8_t overflows_added);

#endif


text:
namespace media {
class AudioBus;
}

namespace content {

class MediaStreamAudioProcessor;
class WebRtcAudioDeviceImpl;
class WebRtcLocalAudioRenderer;
class WebRtcLocalAudioTrack;

// This class manages the capture data flow by getting data from its
// |source_|, and passing it to its |tracks_|.
// The threading model for this class is rather complex since it will be
// created on the main render thread, captured data is provided on a dedicated
// AudioInputDevice thread, and methods can be called either on the Libjingle
// thread or on the main render thread but also other client threads
// if an alternative AudioCapturerSource has been set.
class CONTENT_EXPORT WebRtcAudioCapturer
    : public base::RefCountedThreadSafe<WebRtcAudioCapturer>,
      NON_EXPORTED_BASE(public media::AudioCapturerSource::CaptureCallback) {
 public:
  // Used to construct the audio capturer. |render_view_id| specifies the
  // render view consuming audio for capture, |render_view_id| as -1 is used
  // by the unittests to skip creating a source via
  // AudioDeviceFactory::NewInputDevice(), and allow injecting their own source
  // via SetCapturerSourceForTesting() at a later state.  |device_info|
  // contains all the device information that the capturer is created for.
  // |constraints| contains the settings for audio processing.
  // TODO(xians): Implement the interface for the audio source and move the
  // |constraints| to ApplyConstraints().
  // Called on the main render thread.
  static scoped_refptr<WebRtcAudioCapturer> CreateCapturer(
      int render_view_id,
      const StreamDeviceInfo& device_info,
      const blink::WebMediaConstraints& constraints,
      WebRtcAudioDeviceImpl* audio_device);

  // Add a audio track to the sinks of the capturer.
  // WebRtcAudioDeviceImpl calls this method on the main render thread but
  // other clients may call it from other threads. The current implementation
  // does not support multi-thread calling.
  // The first AddTrack will implicitly trigger the Start() of this object.
  void AddTrack(WebRtcLocalAudioTrack* track);

  // Remove a audio track from the sinks of the capturer.
  // If the track has been added to the capturer, it  must call RemoveTrack()
  // before it goes away.
  // Called on the main render thread or libjingle working thread.
  void RemoveTrack(WebRtcLocalAudioTrack* track);

  // Called when a stream is connecting to a peer connection. This will set
  // up the native buffer size for the stream in order to optimize the
  // performance for peer connection.
  void EnablePeerConnectionMode();

  // Volume APIs used by WebRtcAudioDeviceImpl.
  // Called on the AudioInputDevice audio thread.
  void SetVolume(int volume);
  int Volume() const;
  int MaxVolume() const;

  // Audio parameters utilized by the source of the audio capturer.
  // TODO(phoglund): Think over the implications of this accessor and if we can
  // remove it.
  media::AudioParameters source_audio_parameters() const;

  // Gets information about the paired output device. Returns true if such a
  // device exists.
  bool GetPairedOutputParameters(int* session_id,
                                 int* output_sample_rate,
                                 int* output_frames_per_buffer) const;

  const std::string& device_id() const { return device_info_.device.id; }
  int session_id() const { return device_info_.session_id; }

  // Stops recording audio. This method will empty its track lists since
  // stopping the capturer will implicitly invalidate all its tracks.
  // This method is exposed to the public because the media stream track can
  // call Stop() on its source.
  void Stop();

  // Called by the WebAudioCapturerSource to get the audio processing params.
  // This function is triggered by provideInput() on the WebAudio audio thread,
  // TODO(xians): Remove after moving APM from WebRtc to Chrome.
  void GetAudioProcessingParams(base::TimeDelta* delay, int* volume,
                                bool* key_pressed);

  // Used by the unittests to inject their own source to the capturer.
  void SetCapturerSourceForTesting(
      const scoped_refptr<media::AudioCapturerSource>& source,
      media::AudioParameters params);

  void StartAecDump(const base::PlatformFile& aec_dump_file);
  void StopAecDump();

 protected:
  friend class base::RefCountedThreadSafe<WebRtcAudioCapturer>;
  virtual ~WebRtcAudioCapturer();

 private:
  class TrackOwner;
  typedef TaggedList<TrackOwner> TrackList;

  WebRtcAudioCapturer(int render_view_id,
                      const StreamDeviceInfo& device_info,
                      const blink::WebMediaConstraints& constraints,
                      WebRtcAudioDeviceImpl* audio_device);

  // AudioCapturerSource::CaptureCallback implementation.
  // Called on the AudioInputDevice audio thread.
  virtual void Capture(media::AudioBus* audio_source,
                       int audio_delay_milliseconds,
                       double volume,
                       bool key_pressed) OVERRIDE;
  virtual void OnCaptureError() OVERRIDE;

  // Initializes the default audio capturing source using the provided render
  // view id and device information. Return true if success, otherwise false.
  bool Initialize();

  // SetCapturerSource() is called if the client on the source side desires to
  // provide their own captured audio data. Client is responsible for calling
  // Start() on its own source to have the ball rolling.
  // Called on the main render thread.
  void SetCapturerSource(
      const scoped_refptr<media::AudioCapturerSource>& source,
      media::ChannelLayout channel_layout,
      float sample_rate);

  // Starts recording audio.
  // Triggered by AddSink() on the main render thread or a Libjingle working
  // thread. It should NOT be called under |lock_|.
  void Start();

  // Helper function to get the buffer size based on |peer_connection_mode_|
  // and sample rate;
  int GetBufferSize(int sample_rate) const;

  // Used to DCHECK that we are called on the correct thread.
  base::ThreadChecker thread_checker_;

  // Protects |source_|, |audio_tracks_|, |running_|, |loopback_fifo_|,
  // |params_| and |buffering_|.
  mutable base::Lock lock_;

  // A tagged list of audio tracks that the audio data is fed
  // to. Tagged items need to be notified that the audio format has
  // changed.
  TrackList tracks_;

  // The audio data source from the browser process.
  scoped_refptr<media::AudioCapturerSource> source_;

  // Cached audio constraints for the capturer.
  blink::WebMediaConstraints constraints_;

  // Audio processor doing processing like FIFO, AGC, AEC and NS. Its output
  // data is in a unit of 10 ms data chunk.
  scoped_refptr<MediaStreamAudioProcessor> audio_processor_;

  bool running_;

  int render_view_id_;

  // Cached information of the device used by the capturer.
  const StreamDeviceInfo device_info_;

  // Stores latest microphone volume received in a CaptureData() callback.
  // Range is [0, 255].
  int volume_;

  // Flag which affects the buffer size used by the capturer.
  bool peer_connection_mode_;

  // Cache value for the audio processing params.
  base::TimeDelta audio_delay_;
  bool key_pressed_;

  // Flag to help deciding if the data needs audio processing.
  bool need_audio_processing_;

  // Raw pointer to the WebRtcAudioDeviceImpl, which is valid for the lifetime
  // of RenderThread.
  WebRtcAudioDeviceImpl* audio_device_;

  DISALLOW_COPY_AND_ASSIGN(WebRtcAudioCapturer);
};

}  // namespace content

#endif  // CONTENT_RENDERER_MEDIA_WEBRTC_AUDIO_CAPTURER_H_


text:
CREATE TABLE user (
  id         BIGINT(20)            AUTO_INCREMENT,
  username   VARCHAR(32)  NOT NULL,
  password   VARCHAR(512) NOT NULL,
  email      VARCHAR(32),
  ip_addr    VARCHAR(128),
  is_valid   VARCHAR(1)   NOT NULL
  COMMENT '0:valid, 1:invalid',
  created_at DATETIME     NOT NULL,
  created_by VARCHAR(32)  NOT NULL DEFAULT 'SYS',
  updated_at DATETIME     NOT NULL,
  updated_by VARCHAR(32)  NOT NULL DEFAULT 'SYS',
  PRIMARY KEY pk_user_id (id),
  UNIQUE KEY uk_user_name(username)
);

INSERT INTO user VALUES
  (NULL, 'admin', 'admin', 'admin@lu.com', '127.0.0.1', '0', now(), 'SYS', now(), 'SYS'),
  (NULL, 'lijiantao761', '123456', 'lijiantao761@lu.com', '127.0.0.1', '0', now(), 'SYS', now(), 'SYS'),
  (NULL, 'liuxi683', '123456', 'liuxi683@lu.com', '127.0.0.1', '0', now(), 'SYS', now(), 'SYS');

CREATE TABLE uploaded_file_info
(
  id           BIGINT(20) PRIMARY KEY    NOT NULL AUTO_INCREMENT,
  file_name    VARCHAR(64)               NOT NULL,
  file_md5_sum VARCHAR(32)               NOT NULL,
  store_path   VARCHAR(512)              NOT NULL,
  uploaded_by  BIGINT(20)                NOT NULL,
  uploaded_at  DATETIME                  NOT NULL,
  created_at   DATETIME                  NOT NULL,
  created_by   VARCHAR(32) DEFAULT 'SYS' NOT NULL,
  updated_at   DATETIME                  NOT NULL,
  updated_by   VARCHAR(32) DEFAULT 'SYS' NOT NULL
);
CREATE INDEX ufi_idx_file_name
  ON uploaded_file_info (file_name);
CREATE UNIQUE INDEX UK_file_md5_sum
  ON uploaded_file_info (file_md5_sum);
CREATE INDEX ufi_idx_file_uploaded_at
  ON uploaded_file_info (uploaded_at);

CREATE TABLE IF NOT EXISTS note (
  id          BIGINT(20) AUTO_INCREMENT NOT NULL PRIMARY KEY,
  title       VARCHAR(128)              NOT NULL UNIQUE KEY,
  description VARCHAR(512),
  owner       BIGINT(20),
  status      VARCHAR(1)                NOT NULL
  COMMENT '0:init, 5:processing 9:finish',
  type        VARCHAR(1)                NOT NULL
  COMMENT '0:todo 1:positive 2:negative 9:other',
  finish_time DATETIME,
  created_at  DATETIME                  NOT NULL,
  created_by  VARCHAR(32) DEFAULT 'SYS' NOT NULL,
  updated_at  DATETIME                  NOT NULL,
  updated_by  VARCHAR(32) DEFAULT 'SYS' NOT NULL
);

/*
insert into note VALUES
  (null, 'code review 20170515','desc',4,'0','0',null,now(), 'SYS', now(), 'SYS'),
  (null, 'code review 20170516','desc',4,'0','0',null,now(), 'SYS', now(), 'SYS'),
  (null, 'code review 20170517','desc',4,'0','0',null,now(), 'SYS', now(), 'SYS');
  */

CREATE TABLE IF NOT EXISTS app_info (
  id                      BIGINT(20) AUTO_INCREMENT NOT NULL PRIMARY KEY,
  app_name                VARCHAR(32)               NOT NULL UNIQUE KEY,
  app_desc                VARCHAR(512)              NOT NULL,
  app_owner               BIGINT(20),
  app_user                BIGINT(20),
  app_user2               BIGINT(20),
  app_dfs_info            TEXT,
  app_conf_info           TEXT,
  app_kms_info            TEXT,
  app_http_info           TEXT,
  app_lupay_util_info     TEXT,
  app_withhold_info       TEXT,
  app_pay_info            TEXT,
  app_inter_bank_wh_info  TEXT,
  app_inter_bank_pay_info TEXT,
  app_security_info       TEXT,
  created_at              DATETIME                  NOT NULL,
  created_by              VARCHAR(32) DEFAULT 'SYS' NOT NULL,
  updated_at              DATETIME                  NOT NULL,
  updated_by              VARCHAR(32) DEFAULT 'SYS' NOT NULL
);


text:
package com.wms.opensource.shopfast.listener;

import android.annotation.SuppressLint;
import android.graphics.PorterDuff.Mode;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;

public class ImageViewSrcSelector implements OnTouchListener {

	@SuppressLint("ClickableViewAccessibility")
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN: {
				((ImageView) v).getDrawable().setColorFilter(0xe0f47521,
						Mode.SRC_ATOP);
				((ImageView) v).invalidate();
				break;
			}
			case MotionEvent.ACTION_UP: {
				((ImageView) v).getDrawable().clearColorFilter();
				((ImageView) v).invalidate();
				break;
			}
		}
		return false;
	}

}


text:
.class final Lcom/android/internal/os/BatteryStatsImpl$MyHandler;
.super Landroid/os/Handler;
.source "BatteryStatsImpl.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/internal/os/BatteryStatsImpl;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x10
    name = "MyHandler"
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/internal/os/BatteryStatsImpl;

# direct methods
.method public constructor <init>(Lcom/android/internal/os/BatteryStatsImpl;Landroid/os/Looper;)V
    .locals 2
    .param p1, "this$0"    # Lcom/android/internal/os/BatteryStatsImpl;
    .param p2, "looper"    # Landroid/os/Looper;

    .prologue
    .line 143
    iput-object p1, p0, Lcom/android/internal/os/BatteryStatsImpl$MyHandler;->this$0:Lcom/android/internal/os/BatteryStatsImpl;

    .line 144
    const/4 v0, 0x0

    const/4 v1, 0x1

    invoke-direct {p0, p2, v0, v1}, Landroid/os/Handler;-><init>(Landroid/os/Looper;Landroid/os/Handler$Callback;Z)V

    .line 143
    return-void
.end method

# virtual methods
.method public handleMessage(Landroid/os/Message;)V
    .locals 5
    .param p1, "msg"    # Landroid/os/Message;

    .prologue
    const/4 v3, 0x0

    .line 149
    iget-object v4, p0, Lcom/android/internal/os/BatteryStatsImpl$MyHandler;->this$0:Lcom/android/internal/os/BatteryStatsImpl;

    invoke-static {v4}, Lcom/android/internal/os/BatteryStatsImpl;->-get0(Lcom/android/internal/os/BatteryStatsImpl;)Lcom/android/internal/os/BatteryStatsImpl$BatteryCallback;

    move-result-object v1

    .line 150
    .local v1, "cb":Lcom/android/internal/os/BatteryStatsImpl$BatteryCallback;
    iget v4, p1, Landroid/os/Message;->what:I

    packed-switch v4, :pswitch_data_0

    .line 148
    :cond_0
    :goto_0
    return-void

    .line 152
    :pswitch_0
    iget-object v4, p0, Lcom/android/internal/os/BatteryStatsImpl$MyHandler;->this$0:Lcom/android/internal/os/BatteryStatsImpl;

    monitor-enter v4

    .line 153
    :try_start_0
    iget-object v3, p0, Lcom/android/internal/os/BatteryStatsImpl$MyHandler;->this$0:Lcom/android/internal/os/BatteryStatsImpl;

    invoke-virtual {v3}, Lcom/android/internal/os/BatteryStatsImpl;->updateCpuTimeLocked()V
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    monitor-exit v4

    .line 155
    if-eqz v1, :cond_0

    .line 156
    invoke-interface {v1}, Lcom/android/internal/os/BatteryStatsImpl$BatteryCallback;->batteryNeedsCpuUpdate()V

    goto :goto_0

    .line 152
    :catchall_0
    move-exception v3

    monitor-exit v4

    throw v3

    .line 160
    :pswitch_1
    if-eqz v1, :cond_0

    .line 161
    iget v4, p1, Landroid/os/Message;->arg1:I

    if-eqz v4, :cond_1

    const/4 v3, 0x1

    :cond_1
    invoke-interface {v1, v3}, Lcom/android/internal/os/BatteryStatsImpl$BatteryCallback;->batteryPowerChanged(Z)V

    goto :goto_0

    .line 165
    :pswitch_2
    if-eqz v1, :cond_0

    .line 167
    iget-object v4, p0, Lcom/android/internal/os/BatteryStatsImpl$MyHandler;->this$0:Lcom/android/internal/os/BatteryStatsImpl;

    monitor-enter v4

    .line 168
    :try_start_1
    iget-object v3, p0, Lcom/android/internal/os/BatteryStatsImpl$MyHandler;->this$0:Lcom/android/internal/os/BatteryStatsImpl;

    iget-boolean v3, v3, Lcom/android/internal/os/BatteryStatsImpl;->mCharging:Z

    if-eqz v3, :cond_2

    const-string/jumbo v0, "android.os.action.CHARGING"
    :try_end_1
    .catchall {:try_start_1 .. :try_end_1} :catchall_1

    .local v0, "action":Ljava/lang/String;
    :goto_1
    monitor-exit v4

    .line 171
    new-instance v2, Landroid/content/Intent;

    invoke-direct {v2, v0}, Landroid/content/Intent;-><init>(Ljava/lang/String;)V

    .line 172
    .local v2, "intent":Landroid/content/Intent;
    const/high16 v3, 0x4000000

    invoke-virtual {v2, v3}, Landroid/content/Intent;->addFlags(I)Landroid/content/Intent;

    .line 173
    invoke-interface {v1, v2}, Lcom/android/internal/os/BatteryStatsImpl$BatteryCallback;->batterySendBroadcast(Landroid/content/Intent;)V

    goto :goto_0

    .line 169
    .end local v0    # "action":Ljava/lang/String;
    .end local v2    # "intent":Landroid/content/Intent;
    :cond_2
    :try_start_2
    const-string/jumbo v0, "android.os.action.DISCHARGING"
    :try_end_2
    .catchall {:try_start_2 .. :try_end_2} :catchall_1

    .restart local v0    # "action":Ljava/lang/String;
    goto :goto_1

    .line 167
    .end local v0    # "action":Ljava/lang/String;
    :catchall_1
    move-exception v3

    monitor-exit v4

    throw v3

    .line 150
    :pswitch_data_0
    .packed-switch 0x1
        :pswitch_0
        :pswitch_1
        :pswitch_2
    .end packed-switch
.end method


text:
function s = applyDefaults(s, defaults, validate_fcns)
% Given a (possibly empty) struct s and a struct of default values
% defaults, return a new struct with any values missing from s filled in
% with values from defaults. The new struct will have the union of the
% fields of s and defaults.
% @param s the incoming  structure
% @param defaults a structure with default values for the fields
% @param validate_fcns is a structure with function handles which will
%   check the content of the fields.
% Example:
%   functon myfun(param1, param2, options)
%
%      if nargin<3, options=struct(); end
%      defaults.option1 = true;   valid.option1 = @islogical;
%      defaults.option2 = 'blue'; valid.option2 = @(x)(ischar(x) && x(1)=='b');
%      options = applyDefaults(options,defaults,valid);

if isempty(s)
  s = struct();
end

fields = fieldnames(defaults);
for i=1:numel(fields)
  f = fields{i};
  if ~isfield(s, f)
    s.(f) = defaults.(f);
  end
end

if nargin>2
  fields = fieldnames(validate_fcns);
  for i=1:numel(fields)
    f = fields{i};
    assert(feval(validate_fcns.(f),s.(f)),'Drake:InvalidOption','You have specified an invalid option');
  end
end


text:
package rice.pastry.routing;

import rice.pastry.NodeHandle;

public interface RouteMessageNotification {

  void sendFailed(RouteMessage message, Exception e);

  void sendSuccess(RouteMessage message, NodeHandle nextHop);

}


text:
import pymssql

from user import getPassword

class SQLConnection:

    """Connecto to Microsoft SQL DB """
    def __init__(self, userType=None, userName=None):
        self.server = "autionDB"

        if userType == "admin":
            self.user = userName
            self.password = getPassword(userName)
        elif userType == "agent":
            self.user = userName
            self.password = getPassword(userName)
        elif userType == "participant":
            self.user = "Participant"
            self.password = "AppParticipant"
        else:
            self.user = "App"
            self.password = "app"

    def connect(self):
        return  pymssql.connect(self.server,
            self.user,self.password,'AuctionSystem')

    def close(self, con):
        con.close()


text:
package com.thales.window.Manifest;

import javafx.geometry.Insets;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.text.Font;

/**
 * @author Will Crisp
 */
public class GenerationView extends HBox {

  private Label generationCount = new Label();
  private Label boxCount = new Label();
  private Label totalPriority = new Label();

  public GenerationView() {
    super(40);
    setPadding(new Insets(20, 0, 20, 20));
    setMinWidth(600);
    generationCount.setFont(new Font("Arial", 24));
    boxCount.setFont(new Font("Arial", 24));
    totalPriority.setFont(new Font("Arial", 24));
    getChildren().addAll(generationCount, boxCount, totalPriority);
  }

  public void setGeneration(long generation) {
    generationCount.setText("Gen: " + String.valueOf(generation));
  }

  public void setBoxCount(long generation) {
    boxCount.setText("Containers: " + String.valueOf(generation));
  }
  public void setPriority(long generation) {
    totalPriority.setText("Total Priority: " + String.valueOf(generation));
  }

}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Annls Sci. Nat. , Bot. , sér. 2 10: 343 (1838)

#### Original name
Graphium atrum Desm., 1838

### Remarks
null


text:
package com.company.mandeep.wifigarage;

import com.squareup.okhttp.OkHttpClient;

import retrofit.RequestInterceptor;
import retrofit.RestAdapter;
import retrofit.client.OkClient;

/**
 * Created by Mandeep on 1/15/2015.
 */
public class RestClient {
    private static API REST_CLIENT;
    private static String ROOT =
            "https://api.spark.io";
    static {
        setupRestClient();
    }

    private RestClient() {}

    public static API get() {
        return REST_CLIENT;
    }

    private static void setupRestClient() {

        RequestInterceptor requestInterceptor = new RequestInterceptor() {
            @Override
            public void intercept(RequestFacade request) {
                request.addHeader("Authorization","Bearer "+ AppConfig.getSparkCoreAuthToken());
            }
        };

        RestAdapter builder = new RestAdapter.Builder()
                .setEndpoint(ROOT)
                .setRequestInterceptor(requestInterceptor)
                .build();

        REST_CLIENT = builder.create(API.class);
    }
}


text:
//
// Copyright (c) Microsoft Corporation.  All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//

using System;
using System.Collections.Generic;
using System.Web.SessionState;

namespace Microsoft.Web.Redis
{
    internal class RedisConnectionWrapper : ICacheConnection
    {
        internal static RedisSharedConnection sharedConnection;
        static object lockForSharedConnection = new object();

        public KeyGenerator Keys { set; get; }

        internal IRedisClientConnection redisConnection;
        ProviderConfiguration configuration;

        public RedisConnectionWrapper(ProviderConfiguration configuration, string id)
        {
            this.configuration = configuration;
            Keys = new KeyGenerator(id, configuration.ApplicationName);

            // Pool is created by server when it starts. don't want to lock everytime when check pool == null.
            // so that is why pool == null exists twice.
            if (sharedConnection == null)
            {
                lock (lockForSharedConnection)
                {
                    if (sharedConnection == null)
                    {
                        sharedConnection = new RedisSharedConnection(configuration,() => new StackExchangeClientConnection(configuration));
                    }
                }
            }
            redisConnection = sharedConnection.TryGetConnection();
        }

        public TimeSpan GetLockAge(object lockId)
        {
            // This method do not use redis
            string lockDateTimeTicksFromLockId = lockId.ToString();
            long lockTimeTicks;
            if (long.TryParse(lockDateTimeTicksFromLockId, out lockTimeTicks))
            {
                return DateTime.Now.Subtract(new DateTime(lockTimeTicks));
            }
            else
            { //lock id is not valid so release item exclusive should be called so make lock age very large
                return DateTime.Now.Subtract(new DateTime());
            }
        }

/*-------Start of UpdateExpiryTime operation-----------------------------------------------------------------------------------------------------------------------------------------------*/

        // KEYS[1] = = data-id, internal-id
        // ARGV[1] = session-timeout
        // this order should not change LUA script depends on it
        // if data doesn't exists then do nothing
        static readonly string updateExpiryTimeScript = (@"
                local dataExists = redis.call('EXISTS', KEYS[1])
                if dataExists == 0 then
                    return 1;
                end

                local SessionTimeout = redis.call('HGET', KEYS[2], 'SessionTimeout')
                if SessionTimeout ~= false then
                    redis.call('EXPIRE',KEYS[1], SessionTimeout)
                    redis.call('EXPIRE',KEYS[2], SessionTimeout)
                else
                    redis.call('EXPIRE',KEYS[1],ARGV[1])
                    redis.call('HMSET', KEYS[2], 'SessionTimeout', ARGV[1])
                    redis.call('EXPIRE',KEYS[2],ARGV[1])
                end
                return 1"
                );

        public void UpdateExpiryTime(int timeToExpireInSeconds)
        {
            string[] keyArgs = new string[] { Keys.DataKey, Keys.InternalKey };
            object[] valueArgs = new object[1];
            valueArgs[0] = timeToExpireInSeconds;

            redisConnection.Eval(updateExpiryTimeScript, keyArgs, valueArgs);
        }

/*-------End of UpdateExpiryTime operation-----------------------------------------------------------------------------------------------------------------------------------------------*/

/*-------Start of Set operation-----------------------------------------------------------------------------------------------------------------------------------------------*/

        // KEYS[1] = = data-id, internal-id
        // ARGV[1] = last-index-in-list, ARGV[2] = session-timeout
        // ARGV[3..] = { data as key and value one by one }
        // this order should not change LUA script depends on it
        static readonly string setScript = (@"
                redis.call('HMSET', KEYS[1], unpack(ARGV, 3, ARGV[1]))
                redis.call('EXPIRE',KEYS[1],ARGV[2])
                redis.call('HMSET', KEYS[2], 'SessionTimeout', ARGV[2])
                redis.call('EXPIRE',KEYS[2],ARGV[2])
                return 1"
                );

        private bool SetPrepare(ISessionStateItemCollection data, int sessionTimeout, out string[] keyArgs, out object[] valueArgs)
        {
            keyArgs = null;
            valueArgs = null;
            if (data != null && data.Count > 0)
            {
                ChangeTrackingSessionStateItemCollection sessionItems = (ChangeTrackingSessionStateItemCollection)data;
                List<object> list = RedisUtility.GetNewItemsAsList(sessionItems);
                if (list.Count > 0)
                {
                    keyArgs = new string[] { Keys.DataKey, Keys.InternalKey };
                    valueArgs = new object[list.Count + 2]; // this +2 is for first 2 values in ARGV that we will add now
                    valueArgs[0] = list.Count + 2;
                    valueArgs[1] = sessionTimeout;
                    list.CopyTo(valueArgs, 2);
                    return true;
                }
            }
            return false;
        }

        public void Set(ISessionStateItemCollection data, int sessionTimeout)
        {
            string[] keyArgs;
            object[] valueArgs;
            if (SetPrepare(data, sessionTimeout, out keyArgs, out valueArgs))
            {
                redisConnection.Eval(setScript, keyArgs, valueArgs);
            }
        }

/*-------End of Set operation-----------------------------------------------------------------------------------------------------------------------------------------------*/

/*-------Start of Lock set operation-----------------------------------------------------------------------------------------------------------------------------------------------*/

        // KEYS = { write-lock-id, data-id, internal-id }
        // ARGV = { write-lock-value-that-we-want-to-set, request-timout }
        // lockValue = 1) (Initially) write lock value that we want to set (ARGV[1]) if we get lock successfully this will return as retArray[1]
        //             2) If another write lock exists than its lock value from cache
        // retArray = {lockValue , session data if lock was taken successfully, session timeout value if exists, wheather lock was taken or not}
        static readonly string writeLockAndGetDataScript = (@"
                local retArray = {}
                local lockValue = ARGV[1]
                local locked = redis.call('SETNX',KEYS[1],ARGV[1])
                local IsLocked = true

                if locked == 0 then
                    lockValue = redis.call('GET',KEYS[1])
                else
                    redis.call('EXPIRE',KEYS[1],ARGV[2])
                    IsLocked = false
                end

                retArray[1] = lockValue
                if lockValue == ARGV[1] then retArray[2] = redis.call('HGETALL',KEYS[2]) else retArray[2] = '' end

                local SessionTimeout = redis.call('HGET', KEYS[3], 'SessionTimeout')
                if SessionTimeout ~= false then
                    retArray[3] = SessionTimeout
                    redis.call('EXPIRE',KEYS[2], SessionTimeout)
                    redis.call('EXPIRE',KEYS[3], SessionTimeout)
                else
                    retArray[3] = '-1'
                end

                retArray[4] = IsLocked
                return retArray
                ");

        public bool TryTakeWriteLockAndGetData(DateTime lockTime, int lockTimeout, out object lockId, out ISessionStateItemCollection data, out int sessionTimeout)
        {
            string expectedLockId = lockTime.Ticks.ToString();
            object rowDataFromRedis = null;
            string[] keyArgs = new string[] { Keys.LockKey, Keys.DataKey, Keys.InternalKey };
            object[] valueArgs = new object[] { expectedLockId, lockTimeout };

            rowDataFromRedis = redisConnection.Eval(writeLockAndGetDataScript, keyArgs, valueArgs);

            bool ret = false;
            data = null;

            lockId = redisConnection.GetLockId(rowDataFromRedis);
            sessionTimeout = redisConnection.GetSessionTimeout(rowDataFromRedis);
            bool isLocked = redisConnection.IsLocked(rowDataFromRedis);
            if (!isLocked && lockId.ToString().Equals(expectedLockId))
            {
                ret = true;
                data = redisConnection.GetSessionData(rowDataFromRedis);
            }
            return ret;
        }

        // KEYS = { write-lock-id, data-id, internal-id }
        // ARGV = { }
        // lockValue = 1) (Initially) read lock value that we want to set (ARGV[1]) if we get lock successfully this will return as retArray[1]
        //             3) If write lock exists than its lock value from cache
        // retArray = {lockValue , session data if lock does not exist}
        static readonly string readLockAndGetDataScript = (@"
                    local retArray = {}
                    local lockValue = ''
                    local writeLockValue = redis.call('GET',KEYS[1])
                    if writeLockValue ~= false then
                       lockValue = writeLockValue
                    end
                    retArray[1] = lockValue
                    if lockValue == '' then retArray[2] = redis.call('HGETALL',KEYS[2]) else retArray[2] = '' end

                    local SessionTimeout = redis.call('HGET', KEYS[3], 'SessionTimeout')
                    if SessionTimeout ~= false then
                        retArray[3] = SessionTimeout
                        redis.call('EXPIRE',KEYS[2], SessionTimeout)
                        redis.call('EXPIRE',KEYS[3], SessionTimeout)
                    else
                        retArray[3] = '-1'
                    end
                    return retArray
                    ");

        public bool TryCheckWriteLockAndGetData(out object lockId, out ISessionStateItemCollection data, out int sessionTimeout)
        {
            object rowDataFromRedis = null;
            string[] keyArgs = new string[] { Keys.LockKey, Keys.DataKey, Keys.InternalKey };
            object[] valueArgs = new object[] { };

            rowDataFromRedis = redisConnection.Eval(readLockAndGetDataScript, keyArgs, valueArgs);

            bool ret = false;
            data = null;

            lockId = redisConnection.GetLockId(rowDataFromRedis);
            sessionTimeout = redisConnection.GetSessionTimeout(rowDataFromRedis);
            if (lockId.ToString().Equals(""))
            {
                // If lockId = "" means no lock exists and we got data from store.
                lockId = null;
                ret = true;
                data = redisConnection.GetSessionData(rowDataFromRedis);
            }
            return ret;
        }

/*-------End of Lock set operation-----------------------------------------------------------------------------------------------------------------------------------------------*/

/*-------Start of Lock release operation-----------------------------------------------------------------------------------------------------------------------------------------------*/

        public void TryReleaseLockIfLockIdMatch(object lockId, int sessionTimeout)
        {
            string[] keyArgs = { Keys.LockKey, Keys.DataKey, Keys.InternalKey };
            object[] valueArgs = { lockId, sessionTimeout };
            redisConnection.Eval(releaseWriteLockIfLockMatchScript, keyArgs, valueArgs);
        }

        // KEYS[1] = write-lock-id, KEYS[2] = data-id, KEYS[3] = internal-id
        // ARGV = { write-lock-value }, ARGV[2] = session time out
        static readonly string releaseWriteLockIfLockMatchScript = (@"
                local writeLockValueFromCache = redis.call('GET',KEYS[1])
                if writeLockValueFromCache == ARGV[1] then
                    redis.call('DEL',KEYS[1])
                end
                local SessionTimeout = redis.call('HGET', KEYS[3], 'SessionTimeout')
                if SessionTimeout ~= false then
                    redis.call('EXPIRE',KEYS[2], SessionTimeout)
                    redis.call('EXPIRE',KEYS[3], SessionTimeout)
                else
                    redis.call('EXPIRE',KEYS[2],ARGV[2])
                end
                return 1
                ");

/*-------End of Lock release operation-----------------------------------------------------------------------------------------------------------------------------------------------*/

        // KEYS = { write-lock-id, data-id, internal-id}
        // ARGV = { write-lock-value }
        static readonly string removeIfLockMatchScript = (@"
                local lockValue = redis.call('GET',KEYS[1])
                if lockValue ==  ARGV[1] then
                    redis.call('DEL',KEYS[2])
                    redis.call('DEL',KEYS[3])
                    redis.call('DEL',KEYS[1])
                end return 1
                ");

        public void TryRemoveAndReleaseLockIfLockIdMatch(object lockId)
        {
            string[] keyArgs = { Keys.LockKey, Keys.DataKey, Keys.InternalKey };
            object[] valueArgs = { lockId.ToString() };
            redisConnection.Eval(removeIfLockMatchScript, keyArgs, valueArgs);
        }

/*-------Start of TryUpdateIfLockIdMatch operation-----------------------------------------------------------------------------------------------------------------------------------------------*/

        // KEYS[1] = write-lock-id, KEYS[2] = data-id, KEYS[3] = internal-id
        // ARGV[1] = write-lock-value, ARGV[2] = session time out,
        // ARGV[3] = number of items removed, ARGV[4] = number of items removed start index in ARGV, ARGV[5] = number of items removed end index in ARGV,
        // ARGV[6] = number of items updated, ARGV[7] = number of items updated start index in ARGV, ARGV[8] = number of items updated end index in ARGV,
        // ARGV[9...] = actual data
        // this order should not change LUA script depends on it
        static readonly string removeAndUpdateIfLockMatchScript = (@"
                local writeLockValueFromCache = redis.call('GET',KEYS[1])
                if writeLockValueFromCache == ARGV[1] then
                    if tonumber(ARGV[3]) ~= 0 then redis.call('HDEL', KEYS[2], unpack(ARGV, ARGV[4], ARGV[5])) end
                    if tonumber(ARGV[6]) ~= 0 then redis.call('HMSET', KEYS[2], unpack(ARGV, ARGV[7], ARGV[8])) end
                    redis.call('EXPIRE',KEYS[2],ARGV[2])
                    redis.call('HMSET', KEYS[3], 'SessionTimeout', ARGV[2])
                    redis.call('EXPIRE',KEYS[3],ARGV[2])
                    redis.call('DEL',KEYS[1])
                end return 1");

        private bool TryUpdateIfLockIdMatchPrepare(object lockId, ISessionStateItemCollection data, int sessionTimeout, out string[] keyArgs, out object[] valueArgs)
        {
            keyArgs = null;
            valueArgs = null;
            if (data != null)
            {
                List<object> list = new List<object>();
                ChangeTrackingSessionStateItemCollection sessionItems = (ChangeTrackingSessionStateItemCollection)data;
                int noOfItemsRemoved = RedisUtility.AppendRemoveItemsInList(sessionItems, list);
                int noOfItemsUpdated = RedisUtility.AppendUpdatedOrNewItemsInList(sessionItems, list);

                keyArgs = new string[] { Keys.LockKey, Keys.DataKey, Keys.InternalKey };
                valueArgs = new object[list.Count + 8]; // this +8 is for first wight values in ARGV that we will add now
                valueArgs[0] = lockId;
                valueArgs[1] = sessionTimeout;
                valueArgs[2] = noOfItemsRemoved;
                valueArgs[3] = 9; // In Lua index starts from 1 so first item deleted will be 9th.
                valueArgs[4] = noOfItemsRemoved + 8; // index for last removed item
                valueArgs[5] = noOfItemsUpdated;
                valueArgs[6] = noOfItemsRemoved + 9; // first item updated will be next to last item removed
                valueArgs[7] = list.Count + 8; // index for last item in list in LUA

                // if nothing is changed in session then also execute update script to update session timeout
                if (list.Count != 0)
                {
                    list.CopyTo(valueArgs, 8);
                }
                return true;
            }
            return false;
        }

        public void TryUpdateAndReleaseLockIfLockIdMatch(object lockId, ISessionStateItemCollection data, int sessionTimeout)
        {
            string[] keyArgs;
            object[] valueArgs;
            if (TryUpdateIfLockIdMatchPrepare(lockId, data, sessionTimeout, out keyArgs, out valueArgs))
            {
                redisConnection.Eval(removeAndUpdateIfLockMatchScript, keyArgs, valueArgs);
            }
        }

/*-------End of TryUpdateIfLockIdMatch operation-----------------------------------------------------------------------------------------------------------------------------------------------*/
    }
}


text:
<?php
namespace xleeuwx\Affiliate\Model\DealExtreme;

use xleeuwx\Affiliate\Model\ProductImport;

class DealExtremeProductAdapter extends ProductImport
{

    function getExternalProductDetails($productID)
    {
        // TODO: Implement getExternalProductDetails() method.
    }

    function getExternalProduct($productID)
    {
        // TODO: Implement getExternalProduct() method.
    }

    function getExternalProductPrice($productID)
    {
        // TODO: Implement getExternalProductPrice() method.
    }

    function updateExternalProduct($productID)
    {
        // TODO: Implement updateExternalProduct() method.
    }

}


text:
@implementation ABI11_0_0EXGLViewManager

ABI11_0_0RCT_EXPORT_MODULE(ExponentGLViewManager);

- (UIView *)view
{
  return [[ABI11_0_0EXGLView alloc] initWithManager:self];
}

ABI11_0_0RCT_EXPORT_VIEW_PROPERTY(onSurfaceCreate, ABI11_0_0RCTDirectEventBlock);

@end


text:
APPPATH="/var/www/magento"

cd "$APPPATH"

echo "Symlink module files"

sudo rm -rf $APPPATH/app/code/local
sudo ln -s /vagrant/src/modules $APPPATH/app/code/local

sudo cp -rs /vagrant/src/xml/* $APPPATH/app/etc/modules
sudo cp -rs /vagrant/src/lib/* $APPPATH/lib

n98-magerun.phar cache:flush


text:
.class public Landroid/net/wifi/aware/IdentityChangedListener;
.super Ljava/lang/Object;
.source "IdentityChangedListener.java"

# direct methods
.method public constructor <init>()V
    .locals 0

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public onIdentityChanged([B)V
    .locals 0

    return-void
.end method


text:
const DrawCard = require('../../drawcard.js');

class SalladhorSaan extends DrawCard {
    setupCardAbilities() {
        this.reaction({
            when: {
                afterChallenge: ({challenge}) => (
                    challenge.winner === this.controller &&
                    challenge.isParticipating(this))
            },
            target: {
                activePromptTitle: 'Select a card',
                cardCondition: card => (
                    card.location === 'hand' &&
                    card.controller === this.controller &&
                    ((card.hasTrait('Warship') && card.getType() === 'location') ||
                    (card.hasTrait('Weapon') && card.getType() === 'attachment')))
            },
            handler: context => {
                this.controller.putIntoPlay(context.target);
                this.game.addMessage('{0} uses {1} to put {2} into play', this.controller, this, context.target);
            }
        });
    }
}

SalladhorSaan.code = '04107';

module.exports = SalladhorSaan;


text:
using namespace gpos;
using namespace gpdxl;

//---------------------------------------------------------------------------
//	@function:
//		CDXLScalarComp::CDXLScalarComp
//
//	@doc:
//		Constructs a scalar comparison node
//
//---------------------------------------------------------------------------
CDXLScalarComp::CDXLScalarComp
	(
	IMemoryPool *pmp,
	IMDId *pmdidOp,
	const CWStringConst *pstrCompOpName
	)
	:
	CDXLScalar(pmp),
	m_pmdid(pmdidOp),
	m_pstrCompOpName(pstrCompOpName)
{
	GPOS_ASSERT(m_pmdid->FValid());
}

//---------------------------------------------------------------------------
//	@function:
//		CDXLScalarComp::~CDXLScalarComp
//
//	@doc:
//		Destructor
//
//---------------------------------------------------------------------------
CDXLScalarComp::~CDXLScalarComp()
{
	m_pmdid->Release();
	GPOS_DELETE(m_pstrCompOpName);
}

//---------------------------------------------------------------------------
//	@function:
//		CDXLScalarComp::PstrCmpOpName
//
//	@doc:
//		Comparison operator name
//
//---------------------------------------------------------------------------
const CWStringConst *
CDXLScalarComp::PstrCmpOpName() const
{
	return m_pstrCompOpName;
}

//---------------------------------------------------------------------------
//	@function:
//		CDXLScalarComp::Pmdid
//
//	@doc:
//		Comparison operator id
//
//---------------------------------------------------------------------------
IMDId *
CDXLScalarComp::Pmdid() const
{
	return m_pmdid;
}

//---------------------------------------------------------------------------
//	@function:
//		CDXLScalarComp::Edxlop
//
//	@doc:
//		Operator type
//
//---------------------------------------------------------------------------
Edxlopid
CDXLScalarComp::Edxlop() const
{
	return EdxlopScalarCmp;
}

//---------------------------------------------------------------------------
//	@function:
//		CDXLScalarComp::PstrOpName
//
//	@doc:
//		Operator name
//
//---------------------------------------------------------------------------
const CWStringConst *
CDXLScalarComp::PstrOpName() const
{
	return CDXLTokens::PstrToken(EdxltokenScalarComp);
}

//---------------------------------------------------------------------------
//	@function:
//		CDXLScalarComp::SerializeToDXL
//
//	@doc:
//		Serialize operator in DXL format
//
//---------------------------------------------------------------------------
void
CDXLScalarComp::SerializeToDXL
	(
	CXMLSerializer *pxmlser,
	const CDXLNode *pdxln
	)
	const
{
	GPOS_CHECK_ABORT;

	const CWStringConst *pstrElemName = PstrOpName();

	pxmlser->OpenElement(CDXLTokens::PstrToken(EdxltokenNamespacePrefix), pstrElemName);
	pxmlser->AddAttribute(CDXLTokens::PstrToken(EdxltokenComparisonOp), PstrCmpOpName());

	m_pmdid->Serialize(pxmlser, CDXLTokens::PstrToken(EdxltokenOpNo));

	pdxln->SerializeChildrenToDXL(pxmlser);
	pxmlser->CloseElement(CDXLTokens::PstrToken(EdxltokenNamespacePrefix), pstrElemName);

	GPOS_CHECK_ABORT;
}

#ifdef GPOS_DEBUG
//---------------------------------------------------------------------------
//	@function:
//		CDXLScalarComp::AssertValid
//
//	@doc:
//		Checks whether operator node is well-structured
//
//---------------------------------------------------------------------------
void
CDXLScalarComp::AssertValid
	(
	const CDXLNode *pdxln,
	BOOL fValidateChildren
	)
	const
{
	const ULONG ulArity = pdxln->UlArity();
	GPOS_ASSERT(2 == ulArity);

	for (ULONG ul = 0; ul < ulArity; ++ul)
	{
		CDXLNode *pdxlnArg = (*pdxln)[ul];
		GPOS_ASSERT(EdxloptypeScalar == pdxlnArg->Pdxlop()->Edxloperatortype() ||
					EdxloptypeLogical == pdxlnArg->Pdxlop()->Edxloperatortype());

		if (fValidateChildren)
		{
			pdxlnArg->Pdxlop()->AssertValid(pdxlnArg, fValidateChildren);
		}
	}
}
#endif // GPOS_DEBUG

// EOF


text:
const path = require('path')

module.exports = {
  // electron-packager options
  // Docs: https://simulatedgreg.gitbooks.io/electron-vue/content/docs/building_your_app.html
  name: 'QuasarElectronApp',

  // Electron version
  electronVersion: require('../node_modules/electron/package.json').version,
  arch: 'x64',
  asar: true,
  dir: path.join(__dirname, '../../dist'),
  icon: path.join(__dirname, '../icons/icon'),
  ignore: /\b(node_modules|src|icons)\b/,
  out: path.join(__dirname, '../dist'),
  overwrite: true,
  platform: process.env.PLATFORM_TARGET || 'all'
}


text:
#include "tensorflow/contrib/quantization/kernels/quantization_utils.h"

namespace tensorflow {

void GetOutputMinAndMaxForQuantizedAdd(float input_min, float input_max,
                                       float smaller_input_min,
                                       float smaller_input_max,
                                       float* output_min, float* output_max) {
  // We need to have a good range to add our two arguments together in. This
  // is surprisingly tricky, since it has to satisfy a few different needs:
  //  - Must be symmetrical around zero, so that 0 + 0 = 0.
  //  - Must hold the largest of the argument ranges.
  //  - Should have enough range that the bits of the lowest and highest
  //    arguments overlap if possible without the lower getting truncated.
  //  - Should have some headroom so that there's no overflow.
  //  - Needs to be signed.
  // This leads us to use a scheme where we (assuming the inputs are eight bit
  // and the output is 32-bit) use the bottom 32 - 17 = 15 bits to store the
  // accumulated results. This gives us all the properties we need.
  *output_max =
      std::max(input_max, std::max(-input_min, std::max(smaller_input_max,
                                                        -smaller_input_min))) *
      (1 << 17);
  *output_min = -(*output_max);
}

}  // namespace tensorflow


text:
"""
Base classes and methods shared between torrent client implementations
"""
from __future__ import unicode_literals, absolute_import
from abc import ABCMeta, abstractmethod
from collections import namedtuple, defaultdict
import logging
from tranny import app
from tranny.app import config
from tranny.exceptions import ConfigError
from tranny import events
from tranny.plugin import BasePlugin
from tranny import api

client_speed = namedtuple('client_speed', ['up', 'dn'])

class TorrentState(object):
    STARTED = 'started'
    STOPPED = 'stopped'
    PAUSED = STOPPED
    CHECKING = 'checking'
    DOWNLOADING = 'downloading'

class TorrentClient(BasePlugin):
    """
    Base class to provide a interface for interacting with backend torrent
    clients.
    """

    __metaclass__ = ABCMeta

    config_key = 'undefined'

    def __init__(self):
        super(TorrentClient, self).__init__(self.config_key)
        self.connected = False
        self.log = logging.getLogger(__name__)
        self._last_state = {}
        self._last_update = 0

    def add(self, data, download_dir=None):
        """ Upload a new torrent to the backend client.

        :param data:
        :type data:
        :param download_dir:
        :type download_dir:
        :return:
        :rtype:
        """
        raise NotImplementedError("add is not implemented")

    @abstractmethod
    def client_version(self):
        """ Fetch and return the client version if available

        :return: Client version
        :rtype: unicode
        """
        return self.__class__.__name__

    def __str__(self):
        return self.client_version()

    def client_information(self):
        """ Fetch information about the client, for display purposes only

        :return: Client info
        :rtype: dict
        """
        return {'Version': self.client_version()}

    @abstractmethod
    def current_speeds(self):
        """ Fetch a tuple of the current upload and download speeds in the client

        :return: Upload and download speed in kbps
        :rtype: tuple
        """
        return client_speed(0.0, 0.0)

    @abstractmethod
    def torrent_list(self):
        raise NotImplementedError('torrent_list undefined')

    @abstractmethod
    def torrent_status(self, info_hash):
        raise NotImplementedError("torrent_status undefined")

    @abstractmethod
    def torrent_pause(self, info_hash):
        raise NotImplementedError("torrent_pause undefined")

    @abstractmethod
    def torrent_start(self, info_hash):
        raise NotImplementedError("torrent_start undefined")

    @abstractmethod
    def torrent_remove(self, info_hash):
        raise NotImplementedError("torrent_remove undefined")

    @abstractmethod
    def torrent_reannounce(self, info_hash):
        raise NotImplementedError("torrent_reannounce undefined")

    @abstractmethod
    def torrent_recheck(self, info_hash):
        raise NotImplementedError("torrent_recheck undefined")

    @abstractmethod
    def torrent_files(self, info_hash):
        raise NotImplementedError("torrent_files undefined")

    @abstractmethod
    def torrent_add(self, torrent):
        raise NotImplementedError("torrent_add undefined")

    @abstractmethod
    def torrent_peers(self, info_hash):
        raise NotImplementedError("torrent_peers undefined")

    @abstractmethod
    def torrent_queue_up(self, info_hash):
        pass

    @abstractmethod
    def torrent_queue_down(self, info_hash):
        pass

    @abstractmethod
    def torrent_queue_top(self, info_hash):
        pass

    @abstractmethod
    def torrent_queue_bottom(self, info_hash):
        pass

    @abstractmethod
    def disconnect(self):
        pass

    def get_handlers(self):
        return [
            events.EventHandler(events.EVENT_TICK_5, self.update)
        ]

    def get_events(self):
        new_events = defaultdict(list)
        new_torrents = {t.info_hash: t for t in self.torrent_list()}
        if not self._last_state:
            self._last_state = new_torrents
            return new_events
        known_hashes = {t.info_hash for k, t in self._last_state.items()}
        for torrent in self._last_state.values():
            if torrent.info_hash not in known_hashes:
                # Torrent not in old, must be new
                new_events[events.EVENT_TORRENT_NEW].append(torrent)
                continue
            if not torrent.info_hash in new_torrents:
                # Torrent not in new list, must be removed
                new_events[events.EVENT_TORRENT_REMOVE].append(torrent)
                continue
            # Generate a diff of certain keys
            updates = torrent.changes(self._last_state[torrent.info_hash],
                                      ['ratio', 'up_rate', 'dn_rate', 'up_total', 'dn_total',
                                       'size_completed', 'peers', 'total_peers', 'seeders',
                                       'total_seeders', 'priority'])
            if updates:
                new_events[events.EVENT_TORRENT_UPDATE].append(updates)
        self._last_state = new_torrents
        return new_events

    def update(self, payload=None):
        """
        Update tick handler registered as a plugin
        """
        self.log.debug("Fetching new torrent events")
        new_event = self.get_events()
        for k, v in new_event.items():
            self.log.debug("[{}] {}".format(k, v))
        if new_event:
            api.emit(events.EVENT_TORRENT_UPDATE, data=new_event)
        return payload

    @abstractmethod
    def torrent_move_data(self, info_hash, dest):
        pass

class ClientDataStruct(dict):
    """
    A base class for any data structures that will be returned by clients
    """
    _keys = []

    def __init__(self, **kwargs):
        for key in self._keys:
            self[key] = None
        super(ClientDataStruct, self).__init__(**kwargs)

    def __getitem__(self, key):
        if key not in self._keys:
            raise KeyError("'" + key + "'" + " is not a valid key")
        return super(ClientDataStruct, self).__getitem__(key)

    def __setitem__(self, key, value):
        if key not in self._keys:
            raise KeyError("'" + key + "'" + " is not a valid key")
        super(ClientDataStruct, self).__setitem__(key, value)

    def is_complete(self):
        """Test if all keys have a value, even if that value is empty, e.g. {}"""
        return all(self.get(key, None) is not None for key in self._keys)

    def __unicode__(self):
        return "{} [{}]".format(self['info_hash'], self['name'])

    def __str__(self):
        return self.__unicode__().encode("utf-8")

    def __getattr__(self, name):
        try:
            return self[name]
        except KeyError:
            raise

    def __setattr__(self, name, value):
        if name in self:
            self[name] = value
        else:
            raise AttributeError("Invalid property name: {}".format(name))

    @property
    def key_list(self):
        """ Returns the list of valid keys

        :return: Struct keys
        :rtype: []unicode
        """
        return self._keys

    def changes(self, old, valid_keys=None):
        changes = {}
        if not valid_keys:
            valid_keys = self.keys()
        for key, new_value in self.items():
            if not key in valid_keys:
                continue
            if not old[key] == new_value:
                changes[key] = new_value
        return changes

class ClientPeerData(ClientDataStruct):
    """
    A structure to hold peer data from the client
    """
    _keys = [
        'client',
        'down_speed',
        'up_speed',
        'progress',
        'ip',
        'country'
    ]

class ClientTorrentData(ClientDataStruct):
    """
    A struct used to hold data regarding torrent info sent from the backend client in use
    """
    _keys = [
        'info_hash',
        'name',
        'ratio',
        'up_rate',
        'dn_rate',
        'up_total',
        'dn_total',
        'size',
        'size_completed',
        'seeders',
        'total_seeders',
        'peers',
        'total_peers',
        'priority',
        'private',
        'state',
        'progress',
    ]

class ClientTorrentDataDetail(ClientDataStruct):
    """
    A struct to hold more in depth information about a torrent
    """
    _keys = [
        'info_hash',
        'name',
        'ratio',
        'up_rate',
        'dn_rate',
        'up_total',
        'dn_total',
        'size',
        'size_completed',
        'eta',
        'seeders',
        'total_seeders',
        'peers',
        'total_peers',
        'priority',
        'private',
        'state',
        'progress',
        'tracker_status',
        'next_announce',
        'save_path',
        'piece_length',
        'num_pieces',
        'time_added',
        'distributed_copies',
        'active_time',
        'seeding_time',
        'num_files',
        'comment',
        'queue_position'
    ]

class ClientFileData(ClientDataStruct):
    """
    A struct to hold information about the files inside a torrent
    """
    _keys = [
        'path',
        'size',
        'priority',
        'progress'
    ]

def init_client(client_type=None):
    """ Import & initialize the client set in the configuration file and return the
    usable instance.

    :param client_type: Manually specify a client to load
    :type client_type: unicode
    :return: Configured backend torrent instance
    :rtype: ClientProvider
    """
    if not client_type:
        client_type = config.get_default("general", "client", "transmission").lower()
    if client_type == "rtorrent":
        from tranny.client.rtorrent import RTorrentClient as Client
    elif client_type == "transmission":
        from tranny.client.transmission import TransmissionClient as Client
    elif client_type == "utorrent":
        # from tranny.client.utorrent import UTorrentClient as TorrentClient
        raise NotImplementedError("Utorrent support is currently incomplete. Please use another client")
    elif client_type == "deluge":
        from tranny.client.deluge import DelugeClient as Client
    elif client_type == "simplefile":
        from tranny.client.simplefile import SimpleFileClient as Client
    else:
        raise ConfigError("Invalid client type supplied: {0}".format(client_type))
    config_values = config.get_section_values(Client.config_key)

    client = Client(**config_values)
    from tranny.app import plugin_manager
    plugin_manager.register(client)

    return client

def get():
    """ Return a reference to the current torrent client in use

    TODO remove references to this as its no longer needed

    .. deprecated:: 0.1
        Use the app.torrent_client reference directly

    :return: Current torrent client backend in use
    :rtype: tranny.client.TorrentClient()
    """
    return app.torrent_client


text:
//
//  UIImagePickerController+TKCategory.m
//  Created by Devin Ross on 5/17/13.
//

#import "UIImagePickerController+TKCategory.h"

@implementation UIImagePickerController (TKCategory)

+ (BOOL) hasCamera{
	return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

+ (BOOL) hasFrontCamera{
	return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
}

+ (BOOL) hasRearCamera{
	return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}

@end


text:
layout: post
title: "cars around 1 hacker way"
description: "A cars.com data explore"
category:
tags: []
---
{% include JB/setup %}

I am going to mv to 1 hacker way and I want to buy a new car. So I code a web-spider to collect cars' data on car.com and try to find some usefull info for myself.

I downloaded around 63931 infos of cars which 30 miles around zip code 94025. I encode these info into json lines and then drawed some diagrams to visualize these data.

This bar diagram show the car brand distrubtions.

new car on market for each makes- 30 miles around zipcode 63931

The thing supersing me is *Chevrolet* really have a huge amount of posts. Which make me more interested to find out their news cars' share on market. So I drawed a pie.

makes' new car on market

To have a comparing, I also found the US car brand market shares

We can see that the whole GM take 15% of the cake and the  *Chevrolet* contributed 10% and other parts most come from GMC. For other big players, like these Japanese brands, they market share is little bit bigger than their new car on the market(Toyota 14% > 11.7%, Honda 10% > 5.7%). Ford have 16% market share while only take 9.8% on new cars' pie.

Beside these, I also visulized the Honda civic price distrubtion.

Honda Civic 1.5T Price


text:
/*
 * Generated by XDoclet - Do not edit!
 */
package org.dcm4chex.archive.ejb.interfaces;

/**
 * Home interface for Storage.
 * @xdoclet-generated at ${TODAY}
 * @copyright The XDoclet Team
 * @author XDoclet
 * @version 2.19.0-SNAPSHOT
 */
public interface StorageHome
   extends javax.ejb.EJBHome
{
   public static final String COMP_NAME="java:comp/env/ejb/Storage";
   public static final String JNDI_NAME="ejb/Storage";

   public org.dcm4chex.archive.ejb.interfaces.Storage create()
      throws javax.ejb.CreateException,java.rmi.RemoteException;

}


text:
package org.drools.beliefs.bayes.model;

import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamImplicit;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;

@XStreamAlias("DEFINITION")
public class Definition implements Serializable {

    @XStreamAlias("FOR")
    private String name;

    @XStreamImplicit(itemFieldName = "GIVEN")
    private List<String> given;

    @XStreamAlias("TABLE")
    private String probabilities;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<String> getGiven() {
        return given;
    }

    public void setGiven(List<String> given) {
        this.given = given;
    }

    public String getProbabilities() {
        return probabilities;
    }

    public void setProbabilities(String probabilities) {
        this.probabilities = probabilities;
    }

}


text:
{% extends "base.html" %}
{% load i18n %}

{% block header %}
  <h1>{% block title %}{% trans "Maintenance en cours" %}{% endblock %}</h1>
{% endblock %}

{% block content %}
  {% trans "Cette partie du site sera de retour d'ici une heure." %}
{% endblock %}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".PrivateKeyActivity">

    <fragment
        android:name="pa.com.poroto.pktest.PrivateKeyFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"

        android:id="@+id/fragment_privatekey"
        tools:layout="@layout/fragment_privatekey" />

</RelativeLayout>


text:
<?php
	include('koneksi.php');

    $id_category = $_GET['id_category'];
	$name_category = $_POST['name_category'];

	$query = "UPDATE tbl_category SET name_category='$name_category' WHERE id_category=$id_category";

    $hasil = mysqli_query($koneksi,$query) or die(mysl_error());
    if ($hasil)
    {
        include ("berhasil-editcategory.php");
    }
    else
    {
        echo "Data Gagal Masuk.";exit();
    }

?>

?>


text:
// Copyright 2012 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

// This controls whether this sample is compiled with debugger support.
// You may trace its usages in source text to see what parts of program
// are responsible for debugging support.
// Note that V8 itself should be compiled with enabled debugger support
// to have it all working.
#define SUPPORT_DEBUGGING

#include <v8.h>

#ifdef SUPPORT_DEBUGGING
#include <v8-debug.h>
#endif

#include <fcntl.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

/**
 * This sample program should demonstrate certain aspects of debugging
 * standalone V8-based application.
 *
 * The program reads input stream, processes it line by line and print
 * the result to output. The actual processing is done by custom JavaScript
 * script. The script is specified with command line parameters.
 *
 * The main cycle of the program will sequentially read lines from standard
 * input, process them and print to standard output until input closes.
 * There are 2 possible configuration in regard to main cycle.
 *
 * 1. The main cycle is on C++ side. Program should be run with
 * --main-cycle-in-cpp option. Script must declare a function named
 * "ProcessLine". The main cycle in C++ reads lines and calls this function
 * for processing every time. This is a sample script:

function ProcessLine(input_line) {
  return ">>>" + input_line + "<<<";
}

 *
 * 2. The main cycle is in JavaScript. Program should be run with
 * --main-cycle-in-js option. Script gets run one time at all and gets
 * API of 2 global functions: "read_line" and "print". It should read input
 * and print converted lines to output itself. This a sample script:

while (true) {
  var line = read_line();
  if (!line) {
    break;
  }
  var res = line + " | " + line;
  print(res);
}

 *
 * When run with "-p" argument, the program starts V8 Debugger Agent and
 * allows remote debugger to attach and debug JavaScript code.
 *
 * Interesting aspects:
 * 1. Wait for remote debugger to attach
 * Normally the program compiles custom script and immediately runs it.
 * If programmer needs to debug script from the very beginning, he should
 * run this sample program with "--wait-for-connection" command line parameter.
 * This way V8 will suspend on the first statement and wait for
 * debugger to attach.
 *
 * 2. Unresponsive V8
 * V8 Debugger Agent holds a connection with remote debugger, but it does
 * respond only when V8 is running some script. In particular, when this program
 * is waiting for input, all requests from debugger get deferred until V8
 * is called again. See how "--callback" command-line parameter in this sample
 * fixes this issue.
 */

enum MainCycleType {
  CycleInCpp,
  CycleInJs
};

const char* ToCString(const v8::String::Utf8Value& value);
void ReportException(v8::TryCatch* handler);
v8::Handle<v8::String> ReadFile(const char* name);
v8::Handle<v8::String> ReadLine();

v8::Handle<v8::Value> Print(const v8::Arguments& args);
v8::Handle<v8::Value> ReadLine(const v8::Arguments& args);
bool RunCppCycle(v8::Handle<v8::Script> script, v8::Local<v8::Context> context,
                 bool report_exceptions);

#ifdef SUPPORT_DEBUGGING
v8::Persistent<v8::Context> debug_message_context;

void DispatchDebugMessages() {
  // We are in some random thread. We should already have v8::Locker acquired
  // (we requested this when registered this callback). We was called
  // because new debug messages arrived; they may have already been processed,
  // but we shouldn't worry about this.
  //
  // All we have to do is to set context and call ProcessDebugMessages.
  //
  // We should decide which V8 context to use here. This is important for
  // "evaluate" command, because it must be executed some context.
  // In our sample we have only one context, so there is nothing really to
  // think about.
  v8::Context::Scope scope(debug_message_context);

  v8::Debug::ProcessDebugMessages();
}
#endif

int RunMain(int argc, char* argv[]) {
  v8::V8::SetFlagsFromCommandLine(&argc, argv, true);
  v8::HandleScope handle_scope;

  v8::Handle<v8::String> script_source(NULL);
  v8::Handle<v8::Value> script_name(NULL);
  int script_param_counter = 0;

#ifdef SUPPORT_DEBUGGING
  int port_number = -1;
  bool wait_for_connection = false;
  bool support_callback = false;
#endif

  MainCycleType cycle_type = CycleInCpp;

  for (int i = 1; i < argc; i++) {
    const char* str = argv[i];
    if (strcmp(str, "-f") == 0) {
      // Ignore any -f flags for compatibility with the other stand-
      // alone JavaScript engines.
      continue;
    } else if (strcmp(str, "--main-cycle-in-cpp") == 0) {
      cycle_type = CycleInCpp;
    } else if (strcmp(str, "--main-cycle-in-js") == 0) {
      cycle_type = CycleInJs;
#ifdef SUPPORT_DEBUGGING
    } else if (strcmp(str, "--callback") == 0) {
      support_callback = true;
    } else if (strcmp(str, "--wait-for-connection") == 0) {
      wait_for_connection = true;
    } else if (strcmp(str, "-p") == 0 && i + 1 < argc) {
      port_number = atoi(argv[i + 1]);  // NOLINT
      i++;
#endif
    } else if (strncmp(str, "--", 2) == 0) {
      printf("Warning: unknown flag %s.\nTry --help for options\n", str);
    } else if (strcmp(str, "-e") == 0 && i + 1 < argc) {
      script_source = v8::String::New(argv[i + 1]);
      script_name = v8::String::New("unnamed");
      i++;
      script_param_counter++;
    } else {
      // Use argument as a name of file to load.
      script_source = ReadFile(str);
      script_name = v8::String::New(str);
      if (script_source.IsEmpty()) {
        printf("Error reading '%s'\n", str);
        return 1;
      }
      script_param_counter++;
    }
  }

  if (script_param_counter == 0) {
    printf("Script is not specified\n");
    return 1;
  }
  if (script_param_counter != 1) {
    printf("Only one script may be specified\n");
    return 1;
  }

  // Create a template for the global object.
  v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();

  // Bind the global 'print' function to the C++ Print callback.
  global->Set(v8::String::New("print"), v8::FunctionTemplate::New(Print));

  if (cycle_type == CycleInJs) {
    // Bind the global 'read_line' function to the C++ Print callback.
    global->Set(v8::String::New("read_line"),
                v8::FunctionTemplate::New(ReadLine));
  }

  // Create a new execution environment containing the built-in
  // functions
  v8::Handle<v8::Context> context = v8::Context::New(NULL, global);
  // Enter the newly created execution environment.
  v8::Context::Scope context_scope(context);

#ifdef SUPPORT_DEBUGGING
  debug_message_context = v8::Persistent<v8::Context>::New(context);

  v8::Locker locker;

  if (support_callback) {
    v8::Debug::SetDebugMessageDispatchHandler(DispatchDebugMessages, true);
  }

  if (port_number != -1) {
    v8::Debug::EnableAgent("lineprocessor", port_number, wait_for_connection);
  }
#endif

  bool report_exceptions = true;

  v8::Handle<v8::Script> script;
  {
    // Compile script in try/catch context.
    v8::TryCatch try_catch;
    script = v8::Script::Compile(script_source, script_name);
    if (script.IsEmpty()) {
      // Print errors that happened during compilation.
      if (report_exceptions)
        ReportException(&try_catch);
      return 1;
    }
  }

  {
    v8::TryCatch try_catch;

    script->Run();
    if (try_catch.HasCaught()) {
      if (report_exceptions)
        ReportException(&try_catch);
      return 1;
    }
  }

  if (cycle_type == CycleInCpp) {
    bool res = RunCppCycle(script, v8::Context::GetCurrent(),
                           report_exceptions);
    return !res;
  } else {
    // All is already done.
  }
  return 0;
}

bool RunCppCycle(v8::Handle<v8::Script> script, v8::Local<v8::Context> context,
                 bool report_exceptions) {
#ifdef SUPPORT_DEBUGGING
  v8::Locker lock;
#endif

  v8::Handle<v8::String> fun_name = v8::String::New("ProcessLine");
  v8::Handle<v8::Value> process_val =
      v8::Context::GetCurrent()->Global()->Get(fun_name);

  // If there is no Process function, or if it is not a function,
  // bail out
  if (!process_val->IsFunction()) {
    printf("Error: Script does not declare 'ProcessLine' global function.\n");
    return 1;
  }

  // It is a function; cast it to a Function
  v8::Handle<v8::Function> process_fun =
      v8::Handle<v8::Function>::Cast(process_val);

  while (!feof(stdin)) {
    v8::HandleScope handle_scope;

    v8::Handle<v8::String> input_line = ReadLine();
    if (input_line == v8::Undefined()) {
      continue;
    }

    const int argc = 1;
    v8::Handle<v8::Value> argv[argc] = { input_line };

    v8::Handle<v8::Value> result;
    {
      v8::TryCatch try_catch;
      result = process_fun->Call(v8::Context::GetCurrent()->Global(),
                                 argc, argv);
      if (try_catch.HasCaught()) {
        if (report_exceptions)
          ReportException(&try_catch);
        return false;
      }
    }
    v8::String::Utf8Value str(result);
    const char* cstr = ToCString(str);
    printf("%s\n", cstr);
  }

  return true;
}

int main(int argc, char* argv[]) {
  int result = RunMain(argc, argv);
  v8::V8::Dispose();
  return result;
}

// Extracts a C string from a V8 Utf8Value.
const char* ToCString(const v8::String::Utf8Value& value) {
  return *value ? *value : "<string conversion failed>";
}

// Reads a file into a v8 string.
v8::Handle<v8::String> ReadFile(const char* name) {
  FILE* file = fopen(name, "rb");
  if (file == NULL) return v8::Handle<v8::String>();

  fseek(file, 0, SEEK_END);
  int size = ftell(file);
  rewind(file);

  char* chars = new char[size + 1];
  chars[size] = '\0';
  for (int i = 0; i < size;) {
    int read = fread(&chars[i], 1, size - i, file);
    i += read;
  }
  fclose(file);
  v8::Handle<v8::String> result = v8::String::New(chars, size);
  delete[] chars;
  return result;
}

void ReportException(v8::TryCatch* try_catch) {
  v8::HandleScope handle_scope;
  v8::String::Utf8Value exception(try_catch->Exception());
  const char* exception_string = ToCString(exception);
  v8::Handle<v8::Message> message = try_catch->Message();
  if (message.IsEmpty()) {
    // V8 didn't provide any extra information about this error; just
    // print the exception.
    printf("%s\n", exception_string);
  } else {
    // Print (filename):(line number): (message).
    v8::String::Utf8Value filename(message->GetScriptResourceName());
    const char* filename_string = ToCString(filename);
    int linenum = message->GetLineNumber();
    printf("%s:%i: %s\n", filename_string, linenum, exception_string);
    // Print line of source code.
    v8::String::Utf8Value sourceline(message->GetSourceLine());
    const char* sourceline_string = ToCString(sourceline);
    printf("%s\n", sourceline_string);
    // Print wavy underline (GetUnderline is deprecated).
    int start = message->GetStartColumn();
    for (int i = 0; i < start; i++) {
      printf(" ");
    }
    int end = message->GetEndColumn();
    for (int i = start; i < end; i++) {
      printf("^");
    }
    printf("\n");
  }
}

// The callback that is invoked by v8 whenever the JavaScript 'print'
// function is called.  Prints its arguments on stdout separated by
// spaces and ending with a newline.
v8::Handle<v8::Value> Print(const v8::Arguments& args) {
  bool first = true;
  for (int i = 0; i < args.Length(); i++) {
    v8::HandleScope handle_scope;
    if (first) {
      first = false;
    } else {
      printf(" ");
    }
    v8::String::Utf8Value str(args[i]);
    const char* cstr = ToCString(str);
    printf("%s", cstr);
  }
  printf("\n");
  fflush(stdout);
  return v8::Undefined();
}

// The callback that is invoked by v8 whenever the JavaScript 'read_line'
// function is called. Reads a string from standard input and returns.
v8::Handle<v8::Value> ReadLine(const v8::Arguments& args) {
  if (args.Length() > 0) {
    return v8::ThrowException(v8::String::New("Unexpected arguments"));
  }
  return ReadLine();
}

v8::Handle<v8::String> ReadLine() {
  const int kBufferSize = 1024 + 1;
  char buffer[kBufferSize];

  char* res;
  {
#ifdef SUPPORT_DEBUGGING
    v8::Unlocker unlocker;
#endif
    res = fgets(buffer, kBufferSize, stdin);
  }
  if (res == NULL) {
    v8::Handle<v8::Primitive> t = v8::Undefined();
    return v8::Handle<v8::String>(v8::String::Cast(*t));
  }
  // Remove newline char
  for (char* pos = buffer; *pos != '\0'; pos++) {
    if (*pos == '\n') {
      *pos = '\0';
      break;
    }
  }
  return v8::String::New(buffer);
}