text:
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/performance_manager/public/decorators/page_live_state_decorator.h"

#include <memory>

#include "base/bind.h"
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "base/task/thread_pool.h"
#include "components/performance_manager/test_support/decorators_utils.h"
#include "components/performance_manager/test_support/graph_test_harness.h"
#include "components/performance_manager/test_support/performance_manager_test_harness.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/web_contents.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace performance_manager {

namespace {

// A test version of a PageLiveStateObserver that records the latest function
// that has been called. Gmock isn't used here as instances of this class will
// be used on a different sequence than the main one and that this add a lot of
// extra complexity.
class TestPageLiveStateObserver : public PageLiveStateObserver {
 public:
  TestPageLiveStateObserver() = default;
  ~TestPageLiveStateObserver() override = default;
  TestPageLiveStateObserver(const TestPageLiveStateObserver& other) = delete;
  TestPageLiveStateObserver& operator=(const TestPageLiveStateObserver&) =
      delete;

  enum class ObserverFunction {
    kNone,
    kOnIsConnectedToUSBDeviceChanged,
    kOnIsConnectedToBluetoothDeviceChanged,
    kOnIsCapturingVideoChanged,
    kOnIsCapturingAudioChanged,
    kOnIsBeingMirroredChanged,
    kOnIsCapturingWindowChanged,
    kOnIsCapturingDisplayChanged,
    kOnIsAutoDiscardableChanged,
    kOnWasDiscardedChanged,
    kOnIsActiveTabChanged,
    kOnContentSettingsChanged,
  };

  void OnIsConnectedToUSBDeviceChanged(const PageNode* page_node) override {
    latest_function_called_ =
        ObserverFunction::kOnIsConnectedToUSBDeviceChanged;
    page_node_passed_ = page_node;
  }
  void OnIsConnectedToBluetoothDeviceChanged(
      const PageNode* page_node) override {
    latest_function_called_ =
        ObserverFunction::kOnIsConnectedToBluetoothDeviceChanged;
    page_node_passed_ = page_node;
  }
  void OnIsCapturingVideoChanged(const PageNode* page_node) override {
    latest_function_called_ = ObserverFunction::kOnIsCapturingVideoChanged;
    page_node_passed_ = page_node;
  }
  void OnIsCapturingAudioChanged(const PageNode* page_node) override {
    latest_function_called_ = ObserverFunction::kOnIsCapturingAudioChanged;
    page_node_passed_ = page_node;
  }
  void OnIsBeingMirroredChanged(const PageNode* page_node) override {
    latest_function_called_ = ObserverFunction::kOnIsBeingMirroredChanged;
    page_node_passed_ = page_node;
  }
  void OnIsCapturingWindowChanged(const PageNode* page_node) override {
    latest_function_called_ = ObserverFunction::kOnIsCapturingWindowChanged;
    page_node_passed_ = page_node;
  }
  void OnIsCapturingDisplayChanged(const PageNode* page_node) override {
    latest_function_called_ = ObserverFunction::kOnIsCapturingDisplayChanged;
    page_node_passed_ = page_node;
  }
  void OnIsAutoDiscardableChanged(const PageNode* page_node) override {
    latest_function_called_ = ObserverFunction::kOnIsAutoDiscardableChanged;
    page_node_passed_ = page_node;
  }
  void OnWasDiscardedChanged(const PageNode* page_node) override {
    latest_function_called_ = ObserverFunction::kOnWasDiscardedChanged;
    page_node_passed_ = page_node;
  }
  void OnIsActiveTabChanged(const PageNode* page_node) override {
    latest_function_called_ = ObserverFunction::kOnIsActiveTabChanged;
    page_node_passed_ = page_node;
  }
  void OnContentSettingsChanged(const PageNode* page_node) override {
    latest_function_called_ = ObserverFunction::kOnContentSettingsChanged;
    page_node_passed_ = page_node;
  }

  ObserverFunction latest_function_called_ = ObserverFunction::kNone;
  raw_ptr<const PageNode> page_node_passed_ = nullptr;
};

class MockPageLiveStateDelegate
    : public performance_manager::PageLiveStateDecorator::Delegate {
 public:
  MockPageLiveStateDelegate() = default;

 private:
  std::map<ContentSettingsType, ContentSetting> GetContentSettingsForUrl(
      content::WebContents* web_contents,
      const GURL& url) override {
    return {
        {ContentSettingsType::NOTIFICATIONS, CONTENT_SETTING_ALLOW},
    };
  }
};

}  // namespace

class PageLiveStateDecoratorTest : public PerformanceManagerTestHarness {
 protected:
  PageLiveStateDecoratorTest() = default;
  ~PageLiveStateDecoratorTest() override = default;
  PageLiveStateDecoratorTest(const PageLiveStateDecoratorTest& other) = delete;
  PageLiveStateDecoratorTest& operator=(const PageLiveStateDecoratorTest&) =
      delete;

  void SetUp() override {
    PerformanceManagerTestHarness::SetUp();
    SetContents(CreateTestWebContents());
    observer_ = std::make_unique<TestPageLiveStateObserver>();

    base::RunLoop run_loop;
    auto quit_closure = run_loop.QuitClosure();
    PerformanceManager::CallOnGraph(
        FROM_HERE,
        base::BindOnce(
            [](base::WeakPtr<PageNode> page_node,
               TestPageLiveStateObserver* observer,
               base::OnceClosure quit_closure) {
              EXPECT_TRUE(page_node);
              PageLiveStateDecorator::Data::GetOrCreateForPageNode(
                  page_node.get())
                  ->AddObserver(observer);
              std::move(quit_closure).Run();
            },
            PerformanceManager::GetPrimaryPageNodeForWebContents(
                web_contents()),
            observer_.get(), std::move(quit_closure)));
    run_loop.Run();
  }

  void TearDown() override {
    base::RunLoop run_loop;
    auto quit_closure = run_loop.QuitClosure();
    PerformanceManager::CallOnGraph(
        FROM_HERE,
        base::BindOnce(
            [](base::WeakPtr<PageNode> page_node,
               TestPageLiveStateObserver* observer,
               base::OnceClosure quit_closure) {
              EXPECT_TRUE(page_node);
              PageLiveStateDecorator::Data::GetOrCreateForPageNode(
                  page_node.get())
                  ->RemoveObserver(observer);
              std::move(quit_closure).Run();
            },
            PerformanceManager::GetPrimaryPageNodeForWebContents(
                web_contents()),
            observer_.get(), std::move(quit_closure)));
    run_loop.Run();

    PerformanceManager::GetTaskRunner()->DeleteSoon(FROM_HERE,
                                                    std::move(observer_));
    DeleteContents();
    PerformanceManagerTestHarness::TearDown();
  }

  void VerifyObserverExpectationOnPMSequence(
      TestPageLiveStateObserver::ObserverFunction expected_call) {
    base::RunLoop run_loop;
    auto quit_closure = run_loop.QuitClosure();
    PerformanceManager::CallOnGraph(
        FROM_HERE,
        base::BindOnce(
            [](base::WeakPtr<PageNode> page_node,
               TestPageLiveStateObserver* observer,
               TestPageLiveStateObserver::ObserverFunction expected_call,
               base::OnceClosure quit_closure) {
              EXPECT_TRUE(page_node);
              EXPECT_EQ(expected_call, observer->latest_function_called_);
              EXPECT_EQ(page_node.get(), observer->page_node_passed_);
              std::move(quit_closure).Run();
            },
            PerformanceManager::GetPrimaryPageNodeForWebContents(
                web_contents()),
            observer_.get(), expected_call, std::move(quit_closure)));
    run_loop.Run();
  }

  void OnGraphCreated(GraphImpl* graph) override {
    graph->PassToGraph(std::make_unique<PageLiveStateDecorator>(
        base::SequenceBound<MockPageLiveStateDelegate>(
            content::GetUIThreadTaskRunner({}))));
  }

  scoped_refptr<base::SequencedTaskRunner> task_runner() {
    return content::GetUIThreadTaskRunner({});
  }

 private:
  std::unique_ptr<TestPageLiveStateObserver> observer_;
};

TEST_F(PageLiveStateDecoratorTest, OnIsConnectedToUSBDeviceChanged) {
  testing::EndToEndBooleanPropertyTest(
      web_contents(), &PageLiveStateDecorator::Data::GetOrCreateForPageNode,
      &PageLiveStateDecorator::Data::IsConnectedToUSBDevice,
      &PageLiveStateDecorator::OnIsConnectedToUSBDeviceChanged);
  VerifyObserverExpectationOnPMSequence(
      TestPageLiveStateObserver::ObserverFunction::
          kOnIsConnectedToUSBDeviceChanged);
}

TEST_F(PageLiveStateDecoratorTest, OnIsConnectedToBluetoothDeviceChanged) {
  testing::EndToEndBooleanPropertyTest(
      web_contents(), &PageLiveStateDecorator::Data::GetOrCreateForPageNode,
      &PageLiveStateDecorator::Data::IsConnectedToBluetoothDevice,
      &PageLiveStateDecorator::OnIsConnectedToBluetoothDeviceChanged);
  VerifyObserverExpectationOnPMSequence(
      TestPageLiveStateObserver::ObserverFunction::
          kOnIsConnectedToBluetoothDeviceChanged);
}

TEST_F(PageLiveStateDecoratorTest, OnIsCapturingVideoChanged) {
  testing::EndToEndBooleanPropertyTest(
      web_contents(), &PageLiveStateDecorator::Data::GetOrCreateForPageNode,
      &PageLiveStateDecorator::Data::IsCapturingVideo,
      &PageLiveStateDecorator::OnIsCapturingVideoChanged);
  VerifyObserverExpectationOnPMSequence(
      TestPageLiveStateObserver::ObserverFunction::kOnIsCapturingVideoChanged);
}

TEST_F(PageLiveStateDecoratorTest, OnIsCapturingAudioChanged) {
  testing::EndToEndBooleanPropertyTest(
      web_contents(), &PageLiveStateDecorator::Data::GetOrCreateForPageNode,
      &PageLiveStateDecorator::Data::IsCapturingAudio,
      &PageLiveStateDecorator::OnIsCapturingAudioChanged);
  VerifyObserverExpectationOnPMSequence(
      TestPageLiveStateObserver::ObserverFunction::kOnIsCapturingAudioChanged);
}

TEST_F(PageLiveStateDecoratorTest, OnIsBeingMirroredChanged) {
  testing::EndToEndBooleanPropertyTest(
      web_contents(), &PageLiveStateDecorator::Data::GetOrCreateForPageNode,
      &PageLiveStateDecorator::Data::IsBeingMirrored,
      &PageLiveStateDecorator::OnIsBeingMirroredChanged);
  VerifyObserverExpectationOnPMSequence(
      TestPageLiveStateObserver::ObserverFunction::kOnIsBeingMirroredChanged);
}

TEST_F(PageLiveStateDecoratorTest, OnIsCapturingWindowChanged) {
  testing::EndToEndBooleanPropertyTest(
      web_contents(), &PageLiveStateDecorator::Data::GetOrCreateForPageNode,
      &PageLiveStateDecorator::Data::IsCapturingWindow,
      &PageLiveStateDecorator::OnIsCapturingWindowChanged);
  VerifyObserverExpectationOnPMSequence(
      TestPageLiveStateObserver::ObserverFunction::kOnIsCapturingWindowChanged);
}

TEST_F(PageLiveStateDecoratorTest, OnIsCapturingDisplayChanged) {
  testing::EndToEndBooleanPropertyTest(
      web_contents(), &PageLiveStateDecorator::Data::GetOrCreateForPageNode,
      &PageLiveStateDecorator::Data::IsCapturingDisplay,
      &PageLiveStateDecorator::OnIsCapturingDisplayChanged);
  VerifyObserverExpectationOnPMSequence(
      TestPageLiveStateObserver::ObserverFunction::
          kOnIsCapturingDisplayChanged);
}

TEST_F(PageLiveStateDecoratorTest, SetIsAutoDiscardable) {
  testing::EndToEndBooleanPropertyTest(
      web_contents(), &PageLiveStateDecorator::Data::GetOrCreateForPageNode,
      &PageLiveStateDecorator::Data::IsAutoDiscardable,
      &PageLiveStateDecorator::SetIsAutoDiscardable,
      /*default_state=*/true);
  VerifyObserverExpectationOnPMSequence(
      TestPageLiveStateObserver::ObserverFunction::kOnIsAutoDiscardableChanged);
}

TEST_F(PageLiveStateDecoratorTest, OnWasDiscardedChanged) {
  testing::EndToEndBooleanPropertyTest(
      web_contents(), &PageLiveStateDecorator::Data::GetOrCreateForPageNode,
      &PageLiveStateDecorator::Data::WasDiscarded,
      &PageLiveStateDecorator::SetWasDiscarded,
      /*default_state=*/false);
  VerifyObserverExpectationOnPMSequence(
      TestPageLiveStateObserver::ObserverFunction::kOnWasDiscardedChanged);
}

TEST_F(PageLiveStateDecoratorTest, OnIsActiveTabChanged) {
  testing::EndToEndBooleanPropertyTest(
      web_contents(), &PageLiveStateDecorator::Data::GetOrCreateForPageNode,
      &PageLiveStateDecorator::Data::IsActiveTab,
      &PageLiveStateDecorator::SetIsActiveTab,
      /*default_state=*/false);
  VerifyObserverExpectationOnPMSequence(
      TestPageLiveStateObserver::ObserverFunction::kOnIsActiveTabChanged);
}

TEST_F(PageLiveStateDecoratorTest, OnContentSettingsChanged) {
  base::WeakPtr<PageNode> node =
      PerformanceManager::GetPrimaryPageNodeForWebContents(web_contents());

  {
    base::RunLoop run_loop;
    PerformanceManager::CallOnGraph(
        FROM_HERE, base::BindLambdaForTesting([&]() {
          ASSERT_TRUE(node);
          const PageLiveStateDecorator::Data* data =
              PageLiveStateDecorator::Data::FromPageNode(node.get());
          ASSERT_TRUE(data);
          EXPECT_EQ(data->IsContentSettingTypeAllowed(
                        ContentSettingsType::NOTIFICATIONS),
                    false);
          run_loop.Quit();
        }));
    run_loop.Run();
  }

  PageLiveStateDecorator::SetContentSettings(
      web_contents(),
      {
          {ContentSettingsType::NOTIFICATIONS, CONTENT_SETTING_ALLOW},
      });

  {
    base::RunLoop run_loop;
    PerformanceManager::CallOnGraph(
        FROM_HERE, base::BindLambdaForTesting([&]() {
          ASSERT_TRUE(node);
          const PageLiveStateDecorator::Data* data =
              PageLiveStateDecorator::Data::FromPageNode(node.get());
          ASSERT_TRUE(data);
          EXPECT_EQ(data->IsContentSettingTypeAllowed(
                        ContentSettingsType::NOTIFICATIONS),
                    true);
          run_loop.Quit();
        }));
    run_loop.Run();
  }

  VerifyObserverExpectationOnPMSequence(
      TestPageLiveStateObserver::ObserverFunction::kOnContentSettingsChanged);

  PageLiveStateDecorator::SetContentSettings(
      web_contents(),
      {
          {ContentSettingsType::NOTIFICATIONS, CONTENT_SETTING_BLOCK},
      });

  {
    base::RunLoop run_loop;
    PerformanceManager::CallOnGraph(
        FROM_HERE, base::BindLambdaForTesting([&]() {
          ASSERT_TRUE(node);
          const PageLiveStateDecorator::Data* data =
              PageLiveStateDecorator::Data::FromPageNode(node.get());
          ASSERT_TRUE(data);
          EXPECT_EQ(data->IsContentSettingTypeAllowed(
                        ContentSettingsType::NOTIFICATIONS),
                    false);
          run_loop.Quit();
        }));
    run_loop.Run();
  }

  VerifyObserverExpectationOnPMSequence(
      TestPageLiveStateObserver::ObserverFunction::kOnContentSettingsChanged);
}

// Content settings aren't fetched on navigation on Android.
#if !BUILDFLAG(IS_ANDROID)
TEST_F(PageLiveStateDecoratorTest, GetContentSettingsOnNavigation) {
  base::WeakPtr<PageNode> node =
      PerformanceManager::GetPrimaryPageNodeForWebContents(web_contents());
  {
    base::RunLoop run_loop;
    auto quit_closure = run_loop.QuitClosure();
    PerformanceManager::CallOnGraph(
        FROM_HERE, base::BindLambdaForTesting([&]() {
          ASSERT_TRUE(node);
          const PageLiveStateDecorator::Data* data =
              PageLiveStateDecorator::Data::FromPageNode(node.get());
          ASSERT_TRUE(data);
          EXPECT_EQ(data->IsContentSettingTypeAllowed(
                        ContentSettingsType::NOTIFICATIONS),
                    false);
          PageNodeImpl::FromNode(node.get())
              ->OnMainFrameNavigationCommitted(
                  /*same_document=*/false,
                  /*navigation_committed_time=*/base::TimeTicks::Now(),
                  /*navigation_id=*/1,
                  /*url=*/GURL("http://www.example.com"),
                  /*contents_mime_type=*/"text/html");

          // Posting the quit_closure run on the same task runner as the content
          // settings fetch ensures it's run after the settings are done being
          // retrieved.
          task_runner()->PostTask(FROM_HERE, base::BindLambdaForTesting([&]() {
                                    std::move(quit_closure).Run();
                                  }));
        }));
    run_loop.Run();
  }

  VerifyObserverExpectationOnPMSequence(
      TestPageLiveStateObserver::ObserverFunction::kOnContentSettingsChanged);

  {
    base::RunLoop run_loop;
    PerformanceManager::CallOnGraph(
        FROM_HERE, base::BindLambdaForTesting([&]() {
          ASSERT_TRUE(node);
          const PageLiveStateDecorator::Data* data =
              PageLiveStateDecorator::Data::FromPageNode(node.get());
          ASSERT_TRUE(data);
          EXPECT_EQ(data->IsContentSettingTypeAllowed(
                        ContentSettingsType::NOTIFICATIONS),
                    true);
          run_loop.Quit();
        }));
    run_loop.Run();
  }

  VerifyObserverExpectationOnPMSequence(
      TestPageLiveStateObserver::ObserverFunction::kOnContentSettingsChanged);
}
#endif

}  // namespace performance_manager


text:
local _M = { }

function _M.Push(selfScene, className, flags, ...)

	className = className or "";
	flags = flags or 0;
	local native = nil;
	local scriptObject = nil;

	if type(className) == "table" then
		return _M.PushEx(selfScene, "", "", className, flags, ...);
	else
		if (FileSystem.ExistsLua(className)) then
			return _M.PushEx(selfScene, "", "", className, flags, ...);
		end

		return selfScene:PushName(className, flags);
	end
end

function _M.PushEx(selfScene, className, editorFile, scriptFile, flags, ...)
	className = className or "";
	editorFile = editorFile or "";
	scriptFile = scriptFile or "";
	flags = flags or 0;

	local scriptObject = nil;
	if type(scriptFile) == "table" then
		scriptObject = scriptFile.new(...);
	else
		if scriptFile ~= "" then
			if (FileSystem.ExistsLua(scriptFile)) then
				scriptObject = require(scriptFile).new(...);
			else
				error("Cannot find script file:%s", scriptFile);
				return;
			end
		end
	end

	local native=nil;
	if scriptObject then
		className=scriptObject.__className or className;
		editorFile=scriptObject.__editorFile or editorFile;
		local native = ml.LayerFactory.Create(className, editorFile,ml.NodeCreateFlags.BindScriptChildren);
		native:SetScriptObject(scriptObject);
	else
		native = ml.LayerFactory.Create(className, editorFile,ml.NodeCreateFlags.BindScriptRecursively);
	end

	selfScene:PushObject(native, flags);
	return native;
end

function _M.Apply(val)
	local meta = getmetatable(val);
	meta.Push = _M.Push;
	meta.PushEx = _M.PushEx;
end

return _M;

redpajama_set_name: RedPajamaGithub


text:
package openblocks.events;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import openmods.events.network.BlockEventPacket;
import openmods.movement.PlayerMovementEvent;
import openmods.network.event.EventDirection;
import openmods.network.event.NetworkEventMeta;
import openmods.utils.ByteUtils;

@NetworkEventMeta(direction = EventDirection.C2S)
public class ElevatorActionEvent extends BlockEventPacket {

	public ElevatorActionEvent() {}

	public ElevatorActionEvent(int dimension, int xCoord, int yCoord, int zCoord, PlayerMovementEvent.Type type) {
		super(dimension, xCoord, yCoord, zCoord);
		this.type = type;
	}

	public PlayerMovementEvent.Type type;

	@Override
	protected void readFromStream(DataInput input) throws IOException {
		super.readFromStream(input);
		int typeId = ByteUtils.readVLI(input);
		type = PlayerMovementEvent.Type.VALUES[typeId];
	}

	@Override
	protected void writeToStream(DataOutput output) throws IOException {
		super.writeToStream(output);
		ByteUtils.writeVLI(output, type.ordinal());
	}
}


text:
package com.github.quintans.ezSQL.dml;

public class Union {
  private QueryDSL query;
  private boolean all;

  public Union(QueryDSL query, boolean all) {
    this.query = query;
    this.all = all;
  }

  @SuppressWarnings("unchecked")
  public <T extends QueryDSL> T getQuery() {
    return (T) query;
  }

  public boolean isAll() {
    return all;
  }
}


text:
"""add flag _order field

Revision ID: eb3f7dc1b16f
Revises: 67bf6ca63a9c
Create Date: 2018-12-14 10:56:12.295780

"""
import sqlalchemy as sa
from alembic import op
from sqlalchemy.engine.reflection import Inspector

conn = op.get_bind()
inspector = Inspector.from_engine(conn)
tables = inspector.get_table_names()

# revision identifiers, used by Alembic.
revision = "eb3f7dc1b16f"
down_revision = "67bf6ca63a9c"
branch_labels = None
depends_on = None

def _table_has_column(table, column):
    has_column = False
    for col in inspector.get_columns(table):
        if column not in col["name"]:
            continue
        has_column = True
    return has_column

def _has_table(table_name):
    tables = inspector.get_table_names()
    return table_name in tables

def upgrade():
    if not _table_has_column("flag", "_order"):
        op.add_column("flag", sa.Column("_order", sa.INTEGER))
        op.create_index("order", "flag", ["_order"])

def downgrade():
    if _table_has_column("flag", "_order"):
        op.drop_column("flag", "_order")


text:
module ActionController
  module Routing
    # Much of the slow performance from routes comes from the
    # complexity of expiry, :requirements matching, defaults providing
    # and figuring out which url pattern to use.  With named routes
    # we can avoid the expense of finding the right route.  So if
    # they've provided the right number of arguments, and have no
    # :requirements, we can just build up a string and return it.
    #
    # To support building optimisations for other common cases, the
    # generation code is seperated into several classes
    module Optimisation
      def generate_optimisation_block(route, kind)
        return "" unless route.optimise?
        OPTIMISERS.inject("") do |memo, klazz|
          memo << klazz.new(route, kind).source_code
          memo
        end
      end

      class Optimiser
        attr_reader :route, :kind
        def initialize(route, kind)
          @route = route
          @kind  = kind
        end

        def guard_condition
          'false'
        end

        def generation_code
          'nil'
        end

        def source_code
          if applicable?
            "return #{generation_code} if #{guard_condition}\n"
          else
            "\n"
          end
        end

        def applicable?
          true
        end
      end

      # Given a route:
      # map.person '/people/:id'
      #
      # If the user calls person_url(@person), we can simply
      # return a string like "/people/#{@person.to_param}"
      # rather than triggering the expensive logic in url_for
      class PositionalArguments < Optimiser
        def guard_condition
          number_of_arguments = route.segment_keys.size
          # if they're using foo_url(:id=>2) it's one
          # argument, but we don't want to generate /foos/id2
          if number_of_arguments == 1
            "args.size == 1 && !args.first.is_a?(Hash)"
          else
            "args.size == #{number_of_arguments}"
          end
        end

        def generation_code
          elements = []
          idx = 0

          if kind == :url
            elements << '#{request.protocol}'
            elements << '#{request.host_with_port}'
          end

          # The last entry in route.segments appears to # *always* be a
          # 'divider segment' for '/' but we have assertions to ensure that
          # we don't include the trailing slashes, so skip them.
          ((route.segments.size == 1 && kind == :path) ? route.segments : route.segments[0..-2]).each do |segment|
            if segment.is_a?(DynamicSegment)
              elements << segment.interpolation_chunk("args[#{idx}].to_param")
              idx += 1
            else
              elements << segment.interpolation_chunk
            end
          end
          %("#{elements * ''}")
        end
      end

      # This case is mostly the same as the positional arguments case
      # above, but it supports additional query parameters as the last
      # argument
      class PositionalArgumentsWithAdditionalParams < PositionalArguments
        def guard_condition
          "args.size == #{route.segment_keys.size + 1}"
        end

        # This case uses almost the Use the same code as positional arguments,
        # but add an args.last.to_query on the end
        def generation_code
          super.insert(-2, '?#{args.last.to_query}')
        end

        # To avoid generating http://localhost/?host=foo.example.com we
        # can't use this optimisation on routes without any segments
        def applicable?
          route.segment_keys.size > 0
        end
      end

      OPTIMISERS = [PositionalArguments, PositionalArgumentsWithAdditionalParams]
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright 2009 Google Inc. All Rights Reserved.

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

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

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

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <LinearLayout
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <LinearLayout android:layout_width="fill_parent"
      android:layout_height="wrap_content" android:paddingTop="4dip"
      android:layout_marginLeft="10dip" android:layout_marginRight="10dip"
      android:orientation="vertical">
      <EditText android:id="@+id/account_name" android:layout_marginTop="5dip"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:hint="@string/enter_account_label" android:singleLine="true" />
      <EditText android:id="@+id/key_value" android:layout_marginTop="5dip"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:hint="@string/enter_key_hint"
        android:singleLine="true" android:inputType="textNoSuggestions"/>
      <Spinner android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:layout_marginTop="5dip"
        android:id="@+id/type_choice" android:prompt="@string/type_prompt" />
    </LinearLayout>
  </LinearLayout>
</ScrollView>


text:
package com.sun.xml.fastinfoset.roundtriptests;

import com.sun.xml.fastinfoset.roundtriptests.rtt.DOMRoundTripRtt;
import com.sun.xml.fastinfoset.roundtriptests.rtt.DOMSAXRoundTripRtt;
import com.sun.xml.fastinfoset.roundtriptests.rtt.RoundTripRtt;
import com.sun.xml.fastinfoset.roundtriptests.rtt.SAXRoundTripRtt;
import com.sun.xml.fastinfoset.roundtriptests.rtt.SAXStAXDiffRtt;
import com.sun.xml.fastinfoset.roundtriptests.rtt.StAXRoundTripRtt;
import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

/**
 * @author Alexey Stashok
 */
public class AllRoundTripTest {

    private RoundTripRtt[] roundTripTests = new RoundTripRtt[] {
        new SAXRoundTripRtt(), new StAXRoundTripRtt(), new DOMRoundTripRtt(),
        new DOMSAXRoundTripRtt(), new SAXStAXDiffRtt()};

    public void processAllRttTests(String testSrc, String report) {
        File testSrcFile = new File(testSrc);
        RoundTripReport reporter = new RoundTripReport();
        for (int i=0; i<roundTripTests.length; i++) {
            SingleRountTripTest roundTripTest = new SingleRountTripTest(roundTripTests[i], reporter);
            roundTripTest.processFileOrFolder(testSrcFile);
        }

        cleanupDiffs(testSrcFile);

        try {
            PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(report)));
            try {
                writer.print(reporter.generateReport());
            } finally {
                writer.close();
            }
        } catch (FileNotFoundException ex) {
            System.out.println("Error generating report!");
        }
    }

    private void cleanupDiffs(File testSrcFile) {
        if (testSrcFile.isFile()) {
            testSrcFile = testSrcFile.getParentFile();
        }

        FileUtils.removeFileRecursivelly(testSrcFile, new FileFilter() {
            public boolean accept(File file) {
                if (file.isDirectory()) {
                    return !file.getName().equals(".") && !file.getName().equals("..");
                } else if (file.isFile()) {
                    String filename = file.getName();
                    return filename.endsWith(".finf") || filename.endsWith(".sax-event") ||
                            filename.indexOf(".diff") != -1;
                }
                return false;
            }
        });
    }

    public static void main(String[] args) {
        if (args.length < 2) {
            System.out.println("Not enough parameters!!!");
            System.out.println("Use AllRoundTripTest <test_src> <report_filename>");
            System.out.println("Where <test_src> - testing file or folder");
            System.out.println("<report_filename> - file for generating report");
            System.exit(0);
        }

        new AllRoundTripTest().processAllRttTests(args[0], args[1]);
    }
}


text:
*Aliases:* `rand()`

Returns a random decimal number between `a` and `b` (`a` and `b` default to 0 and 1).

```javascript
Calc.random();
// 0.1168003953062
Calc.random(5);
// 3.8679374323692173
Calc.random(10, 20);
// 15.86298251291737
```

The method will also return a random array index, if given a array.

```javascript
Calc.random(['a', 'b', 'c']);
// 2
```

If you want to receive a random integer instead, see the [`randInt()`](/calc/docs/randInt/) method.


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.datastream.v1.model;

/**
 * JSON file format configuration.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Datastream API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class JsonFileFormat extends com.google.api.client.json.GenericJson {

  /**
   * Compression of the loaded JSON file.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String compression;

  /**
   * The schema file format along JSON data files.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String schemaFileFormat;

  /**
   * Compression of the loaded JSON file.
   * @return value or {@code null} for none
   */
  public java.lang.String getCompression() {
    return compression;
  }

  /**
   * Compression of the loaded JSON file.
   * @param compression compression or {@code null} for none
   */
  public JsonFileFormat setCompression(java.lang.String compression) {
    this.compression = compression;
    return this;
  }

  /**
   * The schema file format along JSON data files.
   * @return value or {@code null} for none
   */
  public java.lang.String getSchemaFileFormat() {
    return schemaFileFormat;
  }

  /**
   * The schema file format along JSON data files.
   * @param schemaFileFormat schemaFileFormat or {@code null} for none
   */
  public JsonFileFormat setSchemaFileFormat(java.lang.String schemaFileFormat) {
    this.schemaFileFormat = schemaFileFormat;
    return this;
  }

  @Override
  public JsonFileFormat set(String fieldName, Object value) {
    return (JsonFileFormat) super.set(fieldName, value);
  }

  @Override
  public JsonFileFormat clone() {
    return (JsonFileFormat) super.clone();
  }

}


text:
/*
 * dummy.c
 *
 *  Created on: 12.02.2010
 *      Author: henning
 */

#include "../defs.h"
#include "../kernel_routes.h"
#include "../kernel_tunnel.h"
#include "../net_os.h"

int olsr_os_init_iptunnel(void) {
  return -1;
}

void olsr_os_cleanup_iptunnel(void) {
}

struct olsr_iptunnel_entry *olsr_os_add_ipip_tunnel(union olsr_ip_addr *target __attribute__ ((unused)),
    bool transportV4 __attribute__ ((unused))) {
  return NULL;
}

void olsr_os_del_ipip_tunnel(struct olsr_iptunnel_entry *t __attribute__ ((unused))) {
  return;
}

bool olsr_if_isup(const char * dev __attribute__ ((unused))) {
  return false;
}

int olsr_if_set_state(const char *dev __attribute__ ((unused)),
    bool up __attribute__ ((unused))) {
  return -1;
}

void olsr_os_niit_4to6_route(const struct olsr_ip_prefix *dst_v4 __attribute__ ((unused)),
    bool set __attribute__ ((unused))) {
}
void olsr_os_niit_6to4_route(const struct olsr_ip_prefix *dst_v6 __attribute__ ((unused)),
    bool set __attribute__ ((unused))) {
}
void olsr_os_inetgw_tunnel_route(uint32_t if_idx __attribute__ ((unused)),
    bool ipv4 __attribute__ ((unused)),
    bool set __attribute__ ((unused))) {
}

int olsr_os_policy_rule(int family __attribute__ ((unused)),
    int rttable __attribute__ ((unused)),
    uint32_t priority __attribute__ ((unused)),
    const char *if_name __attribute__ ((unused)),
    bool set __attribute__ ((unused))) {
  return -1;
}

int olsr_os_localhost_if(union olsr_ip_addr *ip __attribute__ ((unused)),
    bool create __attribute__ ((unused))) {
  return -1;
}

int olsr_os_ifip(int ifindex __attribute__ ((unused)),
    union olsr_ip_addr *ip __attribute__ ((unused)), bool create __attribute__ ((unused))) {
  return -1;
}


text:
from twisted.plugin import IPlugin
from txircd.module_interface import IMode, IModuleData, Mode, ModuleData
from txircd.utils import ModeType
from zope.interface import implements

class PrivateMode(ModuleData, Mode):
	implements(IPlugin, IModuleData, IMode)

	name = "PrivateMode"
	core = True
	affectedActions = { "displaychannel": 10,
	                    "showchannel-whois": 10 }

	def channelModes(self):
		return [ ("p", ModeType.NoParam, self) ]

	def actions(self):
		return [ ("modeactioncheck-channel-p-displaychannel", 1, self.chanIsPrivateList),
		         ("modeactioncheck-channel-p-showchannel-whois", 1, self.chanIsPrivateWhois) ]

	def chanIsPrivateList(self, channel, displayData, sameChannel, user, usedSearchMask):
		if "p" in channel.modes:
			return True
		return None

	def chanIsPrivateWhois(self, channel, sameChannel, queryUser, targetUser):
		if "p" in channel.modes:
			return True
		return None

	def apply(self, actionName, channel, param, *params):
		if actionName == "displaychannel":
			displayData, sameChannel, user, usedSearchMask = params
			if usedSearchMask:
				displayData.clear()
			elif user not in channel.users:
				displayData["name"] = "*"
				displayData["modestopic"] = "[]"
			return
		if actionName == "showchannel-whois":
			sameChannel, queryUser, targetUser = params
			if queryUser not in channel.users:
				return False
			return None

privateMode = PrivateMode()


text:
using System.Collections.Generic;
using System.Linq;
using NHibernate.Driver;
using PholioVisualisation.PholioObjects;

namespace PholioVisualisation.DataConstruction
{
    public class RankDataList
    {
        public static List<CoreDataSet> ValidDataList(IEnumerable<CoreDataSet> dataList, int polarityId)
        {
            List<CoreDataSet> validDataList;
            if (polarityId == PolarityIds.RagHighIsGood)
            {
                validDataList = dataList
                    .Where(x => x.IsValueValid)
                    .OrderByDescending(x => x.Value)
                    .ToList();
            }
            else
            {
                validDataList = dataList
                    .Where(x => x.IsValueValid)
                    .OrderBy(x => x.Value)
                    .ToList();
            }

            return validDataList;
        }
    }
}


text:
namespace gfx {

template class SizeBase<SizeF, float>;

std::string SizeF::ToString() const {
  return base::StringPrintf("%fx%f", width(), height());
}

SizeF ScaleSize(const SizeF& s, float x_scale, float y_scale) {
  SizeF scaled_s(s);
  scaled_s.Scale(x_scale, y_scale);
  return scaled_s;
}

}  // namespace gfx


text:
import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';

import { EtiquetaPage } from '../etiqueta/etiqueta';
import { ContenidoPage } from '../contenido/contenido';
import { Food } from '../../providers/food/food';
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  public food: {id: number, nombre: string, desc:string, img: string, etiqueta: string};
  constructor(public navCtrl: NavController, public navParams: NavParams, public foodProvider: Food) {
      let foodId = navParams.get("food_id");
      this.food = foodProvider.getFoodFromId(foodId);
  }

  verEtiqueta() {
    //this.navCtrl.push(EtiquetaPage);
    this.navCtrl.push(EtiquetaPage, {"food_id": this.food.id});
  }

  verContenido(){
    //this.navCtrl.push(EtiquetaPage);
    this.navCtrl.push(ContenidoPage, {"food_id": this.food.id});
  }

}


text:
//
//  LiveViewController.m
//  ZombieMovie
//
//  Created by apple on 16/6/9.
//  Copyright © 2016年 一位97年的iOS开发者,喜欢学习新知识(姿势😄),如果你和我有相同爱好就加我🐧:450002197,记得备注iOS开发者. All rights reserved.
//

#import "LiveViewController.h"
#import <IJKMediaFramework/IJKMediaFramework.h>
#import "SVProgressHUD.h"
#import "UIImageView+WebCache.h"
#import <Accelerate/Accelerate.h>

@interface LiveViewController ()
@property (atomic, strong) NSURL *url;

@property (atomic, retain) id <IJKMediaPlayback> player;

@property (weak, nonatomic) UIView *PlayerView;

@property (nonatomic, assign)int number;

@property (nonatomic, strong)UIImageView *dimIamge;
@end

@implementation LiveViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor blackColor];

    //直播视频
//    self.url = [NSURL URLWithString:_liveUrl];
    self.url = [NSURL URLWithString:@"rtmp://10.129.157.86:1935/live1/1234"];
    NSLog(@"url = %@",self.url);
    _player = [[IJKFFMoviePlayerController alloc] initWithContentURL:self.url withOptions:nil];
    UIView *playerView = [self.player view];
    UIView *displayView = [[UIView alloc] initWithFrame:self.view.bounds];
    self.PlayerView = displayView;
    self.PlayerView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:self.PlayerView];
    playerView.frame = self.PlayerView.bounds;
    playerView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.PlayerView insertSubview:playerView atIndex:1];
    [_player setScalingMode:IJKMPMovieScalingModeAspectFill];
    [self installMovieNotificationObservers];
    [self loadingView];
    [self changeBackBtn];

    // Do any additional setup after loading the view.
}

// 加载图
- (void)loadingView
{
    self.dimIamge = [[UIImageView alloc] initWithFrame:self.view.bounds];
    [_dimIamge sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://img.meelive.cn/%@",_imageUrl]]];
    UIVisualEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    UIVisualEffectView *visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
    visualEffectView.frame = _dimIamge.bounds;
    [_dimIamge addSubview:visualEffectView];
    [self.view addSubview:_dimIamge];

}

-(void)viewWillAppear:(BOOL)animated{
    if (![self.player isPlaying]) {
        [self.player prepareToPlay];
    }
}

#pragma Selector func

- (void)loadStateDidChange:(NSNotification*)notification {
    IJKMPMovieLoadState loadState = _player.loadState;

    if ((loadState & IJKMPMovieLoadStatePlaythroughOK) != 0) {
        NSLog(@"LoadStateDidChange: IJKMovieLoadStatePlayThroughOK: %d\n",(int)loadState);
    }else if ((loadState & IJKMPMovieLoadStateStalled) != 0) {
        NSLog(@"loadStateDidChange: IJKMPMovieLoadStateStalled: %d\n", (int)loadState);
    } else {
        NSLog(@"loadStateDidChange: ???: %d\n", (int)loadState);
    }
}

- (void)moviePlayBackFinish:(NSNotification*)notification {
    int reason =[[[notification userInfo] valueForKey:IJKMPMoviePlayerPlaybackDidFinishReasonUserInfoKey] intValue];
    switch (reason) {
        case IJKMPMovieFinishReasonPlaybackEnded:
            NSLog(@"playbackStateDidChange: IJKMPMovieFinishReasonPlaybackEnded: %d\n", reason);
            break;

        case IJKMPMovieFinishReasonUserExited:
            NSLog(@"playbackStateDidChange: IJKMPMovieFinishReasonUserExited: %d\n", reason);
            break;

        case IJKMPMovieFinishReasonPlaybackError:
            NSLog(@"playbackStateDidChange: IJKMPMovieFinishReasonPlaybackError: %d\n", reason);
            break;

        default:
            NSLog(@"playbackPlayBackDidFinish: ???: %d\n", reason);
            break;
    }
}

- (void)mediaIsPreparedToPlayDidChange:(NSNotification*)notification {
    NSLog(@"mediaIsPrepareToPlayDidChange\n");
}

- (void)moviePlayBackStateDidChange:(NSNotification*)notification {
    _dimIamge.hidden = YES;
    switch (_player.playbackState) {

        case IJKMPMoviePlaybackStateStopped:
            NSLog(@"IJKMPMoviePlayBackStateDidChange %d: stoped", (int)_player.playbackState);
            break;

        case IJKMPMoviePlaybackStatePlaying:
            NSLog(@"IJKMPMoviePlayBackStateDidChange %d: playing", (int)_player.playbackState);
            break;

        case IJKMPMoviePlaybackStatePaused:
            NSLog(@"IJKMPMoviePlayBackStateDidChange %d: paused", (int)_player.playbackState);
            break;

        case IJKMPMoviePlaybackStateInterrupted:
            NSLog(@"IJKMPMoviePlayBackStateDidChange %d: interrupted", (int)_player.playbackState);
            break;

        case IJKMPMoviePlaybackStateSeekingForward:
        case IJKMPMoviePlaybackStateSeekingBackward: {
            NSLog(@"IJKMPMoviePlayBackStateDidChange %d: seeking", (int)_player.playbackState);
            break;
        }

        default: {
            NSLog(@"IJKMPMoviePlayBackStateDidChange %d: unknown", (int)_player.playbackState);
            break;
        }
    }
}

#pragma Install Notifiacation

- (void)installMovieNotificationObservers {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(loadStateDidChange:)
                                                 name:IJKMPMoviePlayerLoadStateDidChangeNotification
                                               object:_player];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(moviePlayBackFinish:)
                                                 name:IJKMPMoviePlayerPlaybackDidFinishNotification
                                               object:_player];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(mediaIsPreparedToPlayDidChange:)
                                                 name:IJKMPMediaPlaybackIsPreparedToPlayDidChangeNotification
                                               object:_player];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(moviePlayBackStateDidChange:)
                                                 name:IJKMPMoviePlayerPlaybackStateDidChangeNotification
                                               object:_player];

}

- (void)removeMovieNotificationObservers {
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:IJKMPMoviePlayerLoadStateDidChangeNotification
                                                  object:_player];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:IJKMPMoviePlayerPlaybackDidFinishNotification
                                                  object:_player];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:IJKMPMediaPlaybackIsPreparedToPlayDidChangeNotification
                                                  object:_player];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:IJKMPMoviePlayerPlaybackStateDidChangeNotification
                                                  object:_player];

}

// 左右按钮
- (void)changeBackBtn
{
    // 返回
    UIButton * backBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    backBtn.frame = CGRectMake(10, 64 / 2 - 8, 33, 33);
    [backBtn setImage:[UIImage imageNamed:@"返回"] forState:(UIControlStateNormal)];
    [backBtn addTarget:self action:@selector(goBack) forControlEvents:(UIControlEventTouchUpInside)];
    backBtn.layer.shadowColor = [UIColor blackColor].CGColor;
    backBtn.layer.shadowOffset = CGSizeMake(0, 0);
    backBtn.layer.shadowOpacity = 0.5;
    backBtn.layer.shadowRadius = 1;
    [self.view addSubview:backBtn];

    // 暂停
    UIButton * playBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    playBtn.frame = CGRectMake([UIScreen mainScreen].bounds.size.width - 33-10, 64 / 2 - 8, 33, 33);

    if (self.number == 0) {
        [playBtn setImage:[UIImage imageNamed:@"暂停"] forState:(UIControlStateNormal)];
        [playBtn setImage:[UIImage imageNamed:@"开始"] forState:(UIControlStateSelected)];
    }else{
        [playBtn setImage:[UIImage imageNamed:@"开始"] forState:(UIControlStateNormal)];
        [playBtn setImage:[UIImage imageNamed:@"暂停"] forState:(UIControlStateSelected)];
    }

    [playBtn addTarget:self action:@selector(play_btn:) forControlEvents:(UIControlEventTouchUpInside)];
    playBtn.layer.shadowColor = [UIColor blackColor].CGColor;
    playBtn.layer.shadowOffset = CGSizeMake(0, 0);
    playBtn.layer.shadowOpacity = 0.5;
    playBtn.layer.shadowRadius = 1;
    [self.view addSubview:playBtn];

}

//
- (void)goBack
{
    [self.player shutdown];
    [self.navigationController popViewControllerAnimated:true];

}

// 暂停开始
- (void)play_btn:(UIButton *)sender {

    sender.selected =! sender.selected;
    if (![self.player isPlaying]) {
        [self.player play];
    }else{
        [self.player pause];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
 */

@end


text:
package sunwin.zhangdong.web.controller.backend;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import sunwin.zhangdong.domain.User;
import sunwin.zhangdong.service.RegisterService;
import sunwin.zhangdong.web.comm.R;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * Created by Administrator on 2016/12/13.
 */
@Controller
public class RegisterController {

    @Autowired
    private R r;

    @Autowired
    private RegisterService registerService;

    /** 注册页
     * @param modelMap
     * @return
     */
    @RequestMapping(value = R.register, method = RequestMethod.GET)
    public String register(ModelMap modelMap){

        return "vm-backend/user/register";
    }

    /**  保证页面中的name属性和控制器方法的形参一致哦! 这样参数就会按照名称匹配的方式匹配进来!
     *
     * @param request
     * @param user
     * @param repassword
     * @return
     */
    @RequestMapping(value = R.register,method = RequestMethod.POST)
    public ModelAndView register(HttpServletRequest request, User user, String repassword, HttpServletResponse response) throws  Exception{
        ModelAndView mav = new ModelAndView();
        // 1.验证码与服务器生成的放到session中的匹配? 这是后端第一件要做的!

        // 2.用户名是否已经注册,用户名是唯一的哦!(先看是否注册过,然后再加密保存到数据库中好一点吧)
        if(! registerService.hasMatchUser(user.getUserName())){

            user.setUserId(registerService.getMaxId() + 1);    // 设置id   先查出当前user表的最大id,此基础上加1

            // 用户名从页面直接传进来就绑定到domain上了,所以不用设置了!

            String newPwd = BCrypt.hashpw(user.getPassword(), BCrypt.gensalt()); // 3.密码加密加盐保存到数据库中
            user.setPassword(newPwd);

            user.setLastVisit(new java.util.Date());   // java的数据类型和数据库的数据类型自动转换?

            user.setLastIp(request.getRemoteAddr());    // 获取用户的ip

            user.setUserRole("管理员");

            user.setCreateTime(new Date());   // 设置用户domain的创建时间

            registerService.register(user);            // 将用户信息添加到数据库中

            mav.addObject("message","注册成功,请登录!");   // 注册成功后的反馈哦!
            mav.setViewName("vm-backend/user/login");
        }else{
            mav.addObject("message","用户名已注册");
            mav.setViewName("vm-backend/user/register");
        }
        // 这个return是 if-else之外的哦!  即使不写else     不用下面这种方式是因为界面挑战的太快
//        mav.setViewName("vm-backend/user/login");      // 注册成功后返回到指定页面哦!
        return  mav;
    }

}


text:
package com.amazonaws.services.ec2.model.transform;

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

import javax.xml.stream.events.XMLEvent;

import com.amazonaws.services.ec2.model.*;
import com.amazonaws.transform.Unmarshaller;
import com.amazonaws.transform.MapEntry;
import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;

/**
 * InstanceNetworkInterfaceSpecification StAX Unmarshaller
 */
public class InstanceNetworkInterfaceSpecificationStaxUnmarshaller
        implements
        Unmarshaller<InstanceNetworkInterfaceSpecification, StaxUnmarshallerContext> {

    public InstanceNetworkInterfaceSpecification unmarshall(
            StaxUnmarshallerContext context) throws Exception {
        InstanceNetworkInterfaceSpecification instanceNetworkInterfaceSpecification = new InstanceNetworkInterfaceSpecification();
        int originalDepth = context.getCurrentDepth();
        int targetDepth = originalDepth + 1;

        if (context.isStartOfDocument())
            targetDepth += 1;

        while (true) {
            XMLEvent xmlEvent = context.nextEvent();
            if (xmlEvent.isEndDocument())
                return instanceNetworkInterfaceSpecification;

            if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {

                if (context.testExpression("networkInterfaceId", targetDepth)) {
                    instanceNetworkInterfaceSpecification
                            .setNetworkInterfaceId(StringStaxUnmarshaller
                                    .getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("deviceIndex", targetDepth)) {
                    instanceNetworkInterfaceSpecification
                            .setDeviceIndex(IntegerStaxUnmarshaller
                                    .getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("subnetId", targetDepth)) {
                    instanceNetworkInterfaceSpecification
                            .setSubnetId(StringStaxUnmarshaller.getInstance()
                                    .unmarshall(context));
                    continue;
                }

                if (context.testExpression("description", targetDepth)) {
                    instanceNetworkInterfaceSpecification
                            .setDescription(StringStaxUnmarshaller
                                    .getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("privateIpAddress", targetDepth)) {
                    instanceNetworkInterfaceSpecification
                            .setPrivateIpAddress(StringStaxUnmarshaller
                                    .getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("SecurityGroupId/SecurityGroupId",
                        targetDepth)) {
                    instanceNetworkInterfaceSpecification
                            .withGroups(StringStaxUnmarshaller.getInstance()
                                    .unmarshall(context));
                    continue;
                }

                if (context.testExpression("deleteOnTermination", targetDepth)) {
                    instanceNetworkInterfaceSpecification
                            .setDeleteOnTermination(BooleanStaxUnmarshaller
                                    .getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("privateIpAddressesSet/item",
                        targetDepth)) {
                    instanceNetworkInterfaceSpecification
                            .withPrivateIpAddresses(PrivateIpAddressSpecificationStaxUnmarshaller
                                    .getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("secondaryPrivateIpAddressCount",
                        targetDepth)) {
                    instanceNetworkInterfaceSpecification
                            .setSecondaryPrivateIpAddressCount(IntegerStaxUnmarshaller
                                    .getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("associatePublicIpAddress",
                        targetDepth)) {
                    instanceNetworkInterfaceSpecification
                            .setAssociatePublicIpAddress(BooleanStaxUnmarshaller
                                    .getInstance().unmarshall(context));
                    continue;
                }
            } else if (xmlEvent.isEndElement()) {
                if (context.getCurrentDepth() < originalDepth) {
                    return instanceNetworkInterfaceSpecification;
                }
            }
        }
    }

    private static InstanceNetworkInterfaceSpecificationStaxUnmarshaller instance;

    public static InstanceNetworkInterfaceSpecificationStaxUnmarshaller getInstance() {
        if (instance == null)
            instance = new InstanceNetworkInterfaceSpecificationStaxUnmarshaller();
        return instance;
    }
}


text:
package org.apache.tiles.mvel;

import java.util.Arrays;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;

import java.util.HashMap;
import java.util.Map;

import org.apache.tiles.context.TilesRequestContextHolder;
import org.apache.tiles.request.ApplicationContext;
import org.apache.tiles.request.Request;
import org.junit.Before;
import org.junit.Test;
import org.mvel2.integration.VariableResolver;

/**
 * Tests {@link TilesContextBeanVariableResolverFactory}.
 *
 * @version $Rev$ $Date$
 * @since 2.2.0
 */
public class TilesContextBeanVariableResolverFactoryTest {

    /**
     * The expected session scope calls.
     */
    private static final int EXPECTED_SESSION_CALLS = 3;

    /**
     * The expected request scope calls.
     */
    private static final int EXPECTED_REQUEST_CALLS = 4;

    /**
     * The Tiles request.
     */
    private Request request;

    /**
     * The Tiles application context.
     */
    private ApplicationContext applicationContext;

    /**
     * The object to test.
     */
    private TilesContextBeanVariableResolverFactory factory;

    /**
     * Sets up the object.
     */
    @Before
    public void setUp() {
        request = createMock(Request.class);
        TilesRequestContextHolder holder = new TilesRequestContextHolder();
        holder.setTilesRequestContext(request);
        applicationContext = createMock(ApplicationContext.class);
        factory = new TilesContextBeanVariableResolverFactory(holder);
    }

    /**
     * Test method for {@link TilesContextBeanVariableResolverFactory#createVariableResolver(String)}.
     */
    @Test
    public void testCreateVariableResolver() {
        Map<String, Object> requestScope = new HashMap<String, Object>();
        requestScope.put("one", 1);
        expect(request.getContext("request")).andReturn(requestScope).anyTimes();
        Map<String, Object> applicationScope = new HashMap<String, Object>();
        applicationScope.put("two", 2);
        Map<String, Object> sessionScope = new HashMap<String, Object>();
        sessionScope.put("three", "three");
        expect(request.getContext("session")).andReturn(sessionScope).anyTimes();
        expect(request.getAvailableScopes()).andReturn(
                Arrays.asList(new String[] { "request", "session", "application" }))
                .anyTimes();
        expect(request.getContext("application")).andReturn(applicationScope).anyTimes();
        replay(request, applicationContext);

        VariableResolver resolver = factory.createVariableResolver("one");
        assertEquals(1, resolver.getValue());
        assertEquals(Integer.class, resolver.getType());
        resolver = factory.createVariableResolver("two");
        assertEquals(2, resolver.getValue());
        resolver = factory.createVariableResolver("three");
        assertEquals("three", resolver.getValue());
        resolver = factory.createVariableResolver("four");
        assertEquals(Object.class, resolver.getType());
        assertNull(resolver.getValue());
        verify(request, applicationContext);
    }

    /**
     * Test method for {@link TilesContextBeanVariableResolverFactory#isTarget(String)}.
     */
    @Test
    public void testIsTarget() {
        Map<String, Object> requestScope = new HashMap<String, Object>();
        requestScope.put("one", 1);
        expect(request.getContext("request")).andReturn(requestScope).times(
                EXPECTED_REQUEST_CALLS);
        Map<String, Object> applicationScope = new HashMap<String, Object>();
        applicationScope.put("two", 2);
        Map<String, Object> sessionScope = new HashMap<String, Object>();
        sessionScope.put("three", "three");
        expect(request.getContext("session")).andReturn(sessionScope).times(
                EXPECTED_SESSION_CALLS);
        expect(request.getAvailableScopes()).andReturn(
                Arrays.asList(new String[] { "request", "session", "application" }))
                .anyTimes();
        expect(request.getContext("application")).andReturn(applicationScope).anyTimes();
        replay(request, applicationContext);

        assertTrue(factory.isTarget("one"));
        assertTrue(factory.isTarget("two"));
        assertTrue(factory.isTarget("three"));
        assertFalse(factory.isTarget("four"));
        verify(request, applicationContext);
    }
}


text:
module Virtus

  module Model

    # @api private
    def self.included(descendant)
      super
      descendant.send(:include, ClassInclusions)
    end

    # @api private
    def self.extended(descendant)
      super
      descendant.extend(Extensions)
    end

    module Core

      # @api private
      def self.included(descendant)
        super
        descendant.extend(ClassMethods)
        descendant.send(:include, ClassInclusions::Methods)
        descendant.send(:include, InstanceMethods)
      end
      private_class_method :included

      # @api private
      def self.extended(descendant)
        super
        descendant.extend(Extensions::Methods)
        descendant.extend(InstanceMethods)
      end
      private_class_method :extended

    end # Core

    module Constructor

      # @api private
      def self.included(descendant)
        super
        descendant.send(:include, InstanceMethods::Constructor)
      end
      private_class_method :included

    end # Constructor

    module MassAssignment

      # @api private
      def self.included(descendant)
        super
        descendant.send(:include, InstanceMethods::MassAssignment)
      end
      private_class_method :included

      # @api private
      def self.extended(descendant)
        super
        descendant.extend(InstanceMethods::MassAssignment)
      end
      private_class_method :extended

    end # MassAssignment

  end # Model
end # Virtus


text:
App.Models.WithProperties.prototype.firstPoperty = {
    secondDepthProperty: function () {
        'use strict';
    }
};
App.Models.WithProperties.prototype.secondProperty = /(test{1,2})[a-z0-9]+/gi;

App.Models.WithProperties.prototype.multilineFunction = function (test) {
    'use strict';
    return !!test;
};

/**
 *
 * @param test
 * @returns {boolean}
 */
App.Models.WithProperties.prototype.multilineFunctionWithComment = function (test) {
    'use strict';
    return !!test;
};
// @param test
// @returns {boolean}
App.Models.WithProperties.prototype.multilineFunctionWithInlineComment = function (test) {
    'use strict';
    return !!test;
};


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

namespace Seal.Geometries
{
    public class RoundedRectangleGeometry:IGeometry
    {
        public Rectangle Bounds
        {
            get { throw new NotImplementedException(); }
        }

        public bool Contains(ref Point p)
        {
            throw new NotImplementedException();
        }
    }
}


text:
package com.sk.app.proxmock.application.domain.providers.statuscode

import com.fasterxml.jackson.annotation.JsonCreator
import com.sk.app.proxmock.application.configuration.ConfigurationContext
import com.sk.app.proxmock.toolset.serialization.Yaml
import org.springframework.messaging.Message
import org.springframework.util.StringUtils._

/**
 * Created by Szymon on 05.10.2016.
 */
case class StaticFromFileStatusCodeProvider(path: String) extends StatusCodeProvider {
  require(hasText(path), "path in StaticFromFileStatusCodeProvider cannot be blank")

  override def get(context: ConfigurationContext, message: Message[Object]): Int = {
    Yaml.parse(context.fileToString(path), classOf[Int])
  }
}

object StaticFromFileStatusCodeProvider {
  @JsonCreator
  def create(path: String): StaticFromFileStatusCodeProvider =
    StaticFromFileStatusCodeProvider(path)
}


text:
// Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.devtools.build.lib.syntax;

import com.google.common.annotations.VisibleForTesting;
import com.google.devtools.build.lib.events.Location;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;

/**
 * Root class for nodes in the Abstract Syntax Tree of the Build language.
 *
 * The standard {@link Object#equals} and {@link Object#hashCode} methods are not supported. This is
 * because their implementation would require traversing the entire tree in the worst case, and we
 * don't want this kind of cost to occur implicitly. An incomplete way to compare for equality is to
 * test whether two ASTs have the same string representation under {@link #prettyPrint()}. This
 * might miss some metadata, but it's useful in test assertions.
 */
public abstract class ASTNode implements Serializable {

  private Location location;

  protected ASTNode() {}

  /**
   * Returns whether this node represents a new scope, e.g. a function call.
   */
  protected boolean isNewScope()  {
    return false;
  }

  /** Returns an exception which should be thrown instead of the original one. */
  protected final EvalException maybeTransformException(EvalException original) {
    // If there is already a non-empty stack trace, we only add this node iff it describes a
    // new scope (e.g. FuncallExpression).
    if (original instanceof EvalExceptionWithStackTrace) {
      EvalExceptionWithStackTrace real = (EvalExceptionWithStackTrace) original;
      if (isNewScope()) {
        real.registerNode(this);
      }
      return real;
    }

    if (original.canBeAddedToStackTrace()) {
      return new EvalExceptionWithStackTrace(original, this);
    } else {
      return original;
    }
  }

  @VisibleForTesting  // productionVisibility = Visibility.PACKAGE_PRIVATE
  public void setLocation(Location location) {
    this.location = location;
  }

  public Location getLocation() {
    return location;
  }

  /** @return the same node with its location set, in a slightly more fluent style */
  public static <NODE extends ASTNode> NODE setLocation(Location location, NODE node) {
    node.setLocation(location);
    return node;
  }

  /** Number of spaces that each indentation level expands to when pretty-printing. */
  public static final int INDENT_WIDTH = 2;

  /** Writes out the indentation prefix for a line. */
  protected void printIndent(Appendable buffer, int indentLevel) throws IOException {
    for (int i = 0; i < indentLevel * INDENT_WIDTH; i++) {
      buffer.append(' ');
    }
  }

  /**
   * Writes out a suite of statements. The statements are indented one more level than given, i.e.,
   * the {@code indentLevel} parameter should be the same as the parent node's.
   *
   *
This also prints out a {@code pass} line if the suite is empty.
   */
  protected void printSuite(Appendable buffer, List<Statement> statements, int parentIndentLevel)
      throws IOException {
    if (statements.isEmpty()) {
      printIndent(buffer, parentIndentLevel + 1);
      buffer.append("pass\n");
    } else {
      for (Statement stmt : statements) {
        stmt.prettyPrint(buffer, parentIndentLevel + 1);
      }
    }
  }

  /**
   * Writes a pretty-printed representation of this node to a buffer, assuming the given starting
   * indentation level.
   *
   *
For expressions, the indentation level is ignored. For statements, the indentation is
   * written, then the statement contents (which may include multiple lines with their own
   * indentation), then a newline character.
   *
   *
Indentation expands to {@code INDENT_WIDTH} many spaces per indent.
   *
   *
Pretty printing returns the canonical source code corresponding to an AST. Generally, the
   * output can be round-tripped: Pretty printing an AST and then parsing the result should give you
   * back an equivalent AST.
   *
   *
Pretty printing can also be used as a proxy for comparing for equality between two ASTs.
   * This can be very useful in tests. However, it is still possible for two different trees to have
   * the same pretty printing. In particular, {@link BuildFileAST} includes import metadata and
   * comment information that is not reflected in the string.
   */
  public abstract void prettyPrint(Appendable buffer, int indentLevel) throws IOException;

  /** Same as {@link #prettyPrint(Appendable, int)}, except with no indent. */
  public void prettyPrint(Appendable buffer) throws IOException {
    prettyPrint(buffer, 0);
  }

  /** Returns a pretty-printed representation of this node. */
  public String prettyPrint() {
    StringBuilder builder = new StringBuilder();
    try {
      prettyPrint(builder);
    } catch (IOException e) {
      // Not possible for StringBuilder.
      throw new AssertionError(e);
    }
    return builder.toString();
  }

  /**
   * Print the syntax node in a form useful for debugging.
   *
   *
The output is not precisely specified; use {@link #prettyPrint()} if you need more stable
   * and complete information. For instance, this function may omit child statements of compound
   * statements, or parentheses around some expressions. It may also abbreviate large list literals.
   */
  @Override
  public String toString() {
    return prettyPrint();
  }

  @Override
  public int hashCode() {
    throw new UnsupportedOperationException();
  }

  @Override
  public boolean equals(Object that) {
    throw new UnsupportedOperationException();
  }

  /**
   * Implements the double dispatch by calling into the node specific
   * visit method of the {@link SyntaxTreeVisitor}
   *
   * @param visitor the {@link SyntaxTreeVisitor} instance to dispatch to.
   */
  public abstract void accept(SyntaxTreeVisitor visitor);

}


text:
layout: page
title: Kerr Alpha Logistics Award Ceremony
date: 2016-05-24
author: Eric Mays
tags: weekly links, java
status: published
summary: Mauris malesuada nisl eu lacus sagittis fermentum. Donec vestibulum, tortor.
banner: images/banner/office-01.jpg
booking:
  startDate: 10/24/2018
  endDate: 10/28/2018
  ctyhocn: MKEFKHX
  groupCode: KALAC
published: true
---
Sed et sagittis odio, vitae accumsan magna. Nam dui lorem, sollicitudin vitae imperdiet non, fringilla sed diam. Phasellus dictum tortor at sapien semper, in convallis nisi sodales. Etiam sodales ante quis odio luctus dictum quis quis leo. Phasellus nec lorem vitae ligula semper aliquet. Sed eu malesuada nunc. Phasellus semper, turpis laoreet tincidunt finibus, est magna tincidunt turpis, sed blandit est purus malesuada ligula. Donec fringilla a arcu eu consequat. Vivamus varius tristique leo, quis aliquet dolor finibus eu. Duis eu felis interdum, elementum velit sit amet, sagittis tortor. Pellentesque id neque fermentum, pharetra nulla suscipit, euismod quam. Vestibulum pulvinar dui nec pellentesque lacinia. In hac habitasse platea dictumst.

* Quisque at est id sem mollis elementum tempus et elit
* Phasellus rutrum sem non molestie congue.

Donec pulvinar massa vel neque vehicula, quis finibus enim suscipit. In bibendum neque a orci tincidunt ultricies. Aliquam erat volutpat. Donec gravida erat sit amet volutpat posuere. Quisque imperdiet viverra facilisis. Curabitur quis varius ante, vel ornare ipsum. Aliquam vel efficitur risus. Donec tristique viverra gravida. Suspendisse potenti. Suspendisse potenti.
Nunc convallis ultricies consequat. Maecenas tempor vestibulum congue. Cras in faucibus nulla. Interdum et malesuada fames ac ante ipsum primis in faucibus. Donec eget turpis eros. Aenean luctus augue vel nisi molestie varius. Fusce condimentum gravida enim. Donec porttitor facilisis vehicula. Praesent nec mi ac metus vehicula sagittis non non metus. Proin pellentesque lacus leo, non varius urna dictum ac. Proin venenatis rutrum mauris, in auctor risus sodales ut. Nullam tortor ex, sollicitudin quis arcu quis, imperdiet consequat est. Donec porttitor sed dui vitae sollicitudin.


text:
package net.tatamobile.cricket;

import org.cocos2dx.lib.Cocos2dxActivity;
import org.cocos2dx.lib.Cocos2dxGLSurfaceView;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;

public class Cricket extends Cocos2dxActivity{

    public static SharedPreferences sharedPreferences;
    public static SharedPreferences.Editor editor;

    protected void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);

	      sharedPreferences = this.getSharedPreferences("cricket",Context.MODE_PRIVATE);
	      editor = sharedPreferences.edit();
	}

    public Cocos2dxGLSurfaceView onCreateView() {
    	Cocos2dxGLSurfaceView glSurfaceView = new Cocos2dxGLSurfaceView(this);
    	// Cricket should create stencil buffer
    	glSurfaceView.setEGLConfigChooser(5, 6, 5, 0, 16, 8);

    	return glSurfaceView;
    }

    public static void saveBool(String key, boolean value)
    {
         try
         {
             //SharedPreferences.Editor editor = sharedPreferences.edit();
             editor.putBoolean(key,value);
             editor.commit();
         }
         catch (Exception e)
         {
             return;
         }
    }
    public static boolean getBool(String key, boolean defValue)
    {
         try
         {
               boolean v = sharedPreferences.getBoolean(key, defValue);
               return v;
         }
         catch (Exception e)
         {
              return false;
         }
    }
    public static void saveInt(String key, int value)
    {
         try
         {
             //SharedPreferences.Editor editor = sharedPreferences.edit();
             editor.putInt(key,value);
             editor.commit();
         }
         catch (Exception e)
         {
             return;
         }
    }
    public static int getInt(String key, int defValue)
    {
         try
         {
               int v = sharedPreferences.getInt(key, defValue);
               return v;
         }
         catch (Exception e)
         {
              return -1000;
         }
    }

    //保存数组的方法
    public static void saveIntArr(String key,int[] value,int ROW,int COL)
    {
        for(int i=0;i<ROW;i++)
        {
            for(int j=0;j<COL;j++)
            {
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putInt(key+i+j,value[i*COL+j]);
                editor.commit();
            }
        }
    }

    //得到数组的方法
    public static int[] getIntArr(String key,int ROW,int COL)
    {
        int arr[] = new int[ROW*COL];
        for(int i=0;i<ROW;i++)
        {
            for(int j=0;j<COL;j++)
            {
                arr[i*COL+j] = sharedPreferences.getInt(key+i+j, -1000);
            }
        }
        return arr;
    }

    static {
        System.loadLibrary("cocos2dcpp");
    }
}


text:
/**
 * This class is generated by jOOQ
 */
package com.skcraft.plume.common.service.sql.model.log;

import com.skcraft.plume.common.service.sql.model.log.tables.Log;
import com.skcraft.plume.common.service.sql.model.log.tables.LogWorld;

import javax.annotation.Generated;

/**
 * Convenience access to all tables in log
 */
@Generated(
	value = {
		"http://www.jooq.org",
		"jOOQ version:3.6.2"
	},
	comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class Tables {

	/**
	 * The table log.log
	 */
	public static final Log LOG = com.skcraft.plume.common.service.sql.model.log.tables.Log.LOG;

	/**
	 * The table log.log_world
	 */
	public static final LogWorld LOG_WORLD = com.skcraft.plume.common.service.sql.model.log.tables.LogWorld.LOG_WORLD;
}


text:
	/*
  	Flaticon icon font: Flaticon
  	Creation date: 18/04/2016 12:40
  	*/

@font-face {
  font-family: "Flaticon";
  src: url("./Flaticon.eot");
  src: url("./Flaticon.eot?#iefix") format("embedded-opentype"),
       url("./Flaticon.woff") format("woff"),
       url("./Flaticon.ttf") format("truetype"),
       url("./Flaticon.svg#Flaticon") format("svg");
  font-weight: normal;
  font-style: normal;
}

@media screen and (-webkit-min-device-pixel-ratio:0) {
  @font-face {
    font-family: "Flaticon";
    src: url("./Flaticon.svg#Flaticon") format("svg");
  }
}

[class^="flaticon-"]:before, [class*=" flaticon-"]:before,
[class^="flaticon-"]:after, [class*=" flaticon-"]:after {
  font-family: Flaticon;
        font-size: inherit;
font-style: normal;
margin-left: 0;
}

.flaticon-arrows:before { content: "\f100"; }
.flaticon-arrows-1:before { content: "\f101"; }
.flaticon-arrows-2:before { content: "\f102"; }
.flaticon-arrows-3:before { content: "\f103"; }
.flaticon-arrows-4:before { content: "\f104"; }
.flaticon-box:before { content: "\f105"; }
.flaticon-business:before { content: "\f106"; }
.flaticon-business-1:before { content: "\f107"; }
.flaticon-coins:before { content: "\f108"; }
.flaticon-commerce:before { content: "\f109"; }
.flaticon-computer:before { content: "\f10a"; }
.flaticon-computer-1:before { content: "\f10b"; }
.flaticon-cross:before { content: "\f10c"; }
.flaticon-fashion:before { content: "\f10d"; }
.flaticon-favorite:before { content: "\f10e"; }
.flaticon-game:before { content: "\f10f"; }
.flaticon-gear:before { content: "\f110"; }
.flaticon-interface:before { content: "\f111"; }
.flaticon-interface-1:before { content: "\f112"; }
.flaticon-interface-2:before { content: "\f113"; }
.flaticon-interface-3:before { content: "\f114"; }
.flaticon-interface-4:before { content: "\f115"; }
.flaticon-internet:before { content: "\f116"; }
.flaticon-locked:before { content: "\f117"; }
.flaticon-mark:before { content: "\f118"; }
.flaticon-medical:before { content: "\f119"; }
.flaticon-money:before { content: "\f11a"; }
.flaticon-nation:before { content: "\f11b"; }
.flaticon-note:before { content: "\f11c"; }
.flaticon-note-1:before { content: "\f11d"; }
.flaticon-other:before { content: "\f11e"; }
.flaticon-people:before { content: "\f11f"; }
.flaticon-people-1:before { content: "\f120"; }
.flaticon-people-2:before { content: "\f121"; }
.flaticon-placeholder:before { content: "\f122"; }
.flaticon-recycle:before { content: "\f123"; }
.flaticon-school:before { content: "\f124"; }
.flaticon-screen:before { content: "\f125"; }
.flaticon-shapes:before { content: "\f126"; }
.flaticon-sheet:before { content: "\f127"; }
.flaticon-signs:before { content: "\f128"; }
.flaticon-social:before { content: "\f129"; }
.flaticon-social-1:before { content: "\f12a"; }
.flaticon-social-2:before { content: "\f12b"; }
.flaticon-social-3:before { content: "\f12c"; }
.flaticon-social-4:before { content: "\f12d"; }
.flaticon-social-5:before { content: "\f12e"; }
.flaticon-social-network:before { content: "\f12f"; }
.flaticon-squares:before { content: "\f130"; }
.flaticon-technology:before { content: "\f131"; }
.flaticon-technology-1:before { content: "\f132"; }
.flaticon-technology-2:before { content: "\f133"; }
.flaticon-technology-3:before { content: "\f134"; }
.flaticon-time:before { content: "\f135"; }
.flaticon-tool:before { content: "\f136"; }
.flaticon-transport:before { content: "\f137"; }
.flaticon-typography:before { content: "\f138"; }
.flaticon-video:before { content: "\f139"; }
.flaticon-weather:before { content: "\f13a"; }
.flaticon-weather-1:before { content: "\f13b"; }
.flaticon-work:before { content: "\f13c"; }


text:
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.

#pragma once

#include "CurveFactory.generated.h"

/**
 * Factory that creates curve assets, prompting to pick the kind of curve at creation time
 */

UCLASS()
class UCurveFactory : public UFactory
{
	GENERATED_UCLASS_BODY()

	/** The type of blueprint that will be created */
	UPROPERTY(EditAnywhere, Category=CurveFactory)
	TSubclassOf<UCurveBase> CurveClass;

	// UFactory Interface
	virtual bool ConfigureProperties() override;
	virtual UObject* FactoryCreateNew(UClass* Class,UObject* InParent,FName Name,EObjectFlags Flags,UObject* Context,FFeedbackContext* Warn) override;
	// End of UFactory interface
};

/**
 * Factory that creates float curve assets
 */

UCLASS()
class UCurveFloatFactory : public UCurveFactory
{
	GENERATED_UCLASS_BODY()

	// UFactory interface
	virtual bool ConfigureProperties() override;
	// End of UFactory interface
};


text:
package org.config4jms.sonicmq;

import javax.jms.JMSException;
import javax.jms.Session;

import org.config4j.Configuration;
import org.config4j.ConfigurationException;
import org.config4j.SchemaValidator;

import org.config4jms.Config4JMSException;

import org.config4jms.base.ObtainMethodData;
import org.config4jms.base.TypeDefinition;

import progress.message.jclient.Topic;

public class TopicInfo extends Info
{
	private Topic				topic;
	private SessionInfo			creator;
	private String				obtainMethod;
	private String				createdBy;
	private String				createTopicName;
	private String				name;
	private String				topicName;

	public TopicInfo(
		org.config4jms.Config4JMS	config4jms,
		String						scope,
		TypeDefinition				typeDef) throws Config4JMSException
	{
		super(config4jms, scope, typeDef);
	}

	public void validateConfiguration() throws Config4JMSException
	{
		String[]				scopeSchema;
		SchemaValidator			createScopeSv = new SchemaValidator();
		String[]				createScopeSchema;
		SchemaValidator			scopeSv = new SchemaValidator();

		scopeSchema = new String[] {
							"obtainMethod=string",
							"createdBy=string",
							"name=string",
							"topicName=string",
							"create=scope",
		};
		createScopeSchema = new String[] {
							"topicName=string",
		};

		try {
			//--------
			// Schema checks for scope and scope+".create"
			//--------
			scopeSv.parseSchema(scopeSchema);
			scopeSv.validate(cfg, scope, "", false,
							 Configuration.CFG_SCOPE_AND_VARS);

			if (cfg.type(scope, "create") == Configuration.CFG_SCOPE) {
				createScopeSv.parseSchema(createScopeSchema);
				createScopeSv.validate(cfg, scope, "create", false,
									   Configuration.CFG_SCOPE_AND_VARS);
			}

			//--------
			// Get the required attributes
			//--------
			obtainMethod = cfg.lookupString(scope, "obtainMethod");
			if (obtainMethod.equals("create")) {
				createdBy = cfg.lookupString(scope, "createdBy");
				createTopicName = cfg.lookupString(scope, "create.topicName");
			} else {
				createdBy = null;
			}
		} catch(ConfigurationException ex) {
			throw new Config4JMSException(ex.getMessage());
		}

		//--------
		// Check that cross-references to other scopes are valid.
		//--------
		if (createdBy != null) {
			creator = (SessionInfo)jms.getInfo(createdBy);
			if (creator == null) {
				throw new Config4JMSException(cfg.fileName() + ": value of "
							+ cfg.mergeNames(scope, "createdBy") + " ('"
							+ createdBy + "') does not specify the name of a "
							+ "Session.");
			}
		}

		//--------
		// Get the optional attributes
		//--------
		name = lookupOptionalString("name");
		topicName = lookupOptionalString("topicName");
	}

	public void createJMSObject() throws Config4JMSException
	{
		ObtainMethodData		omData;
		Session					session;

		omData = parseObtainMethod(obtainMethod,
								   new String[]{"jndi#", "file#", "create"});
		if (!omData.isOK()) {
			throw new Config4JMSException(cfg.fileName() + ": bad value ('"
					+ obtainMethod + "') for '"
					+ cfg.mergeNames(scope, "obtainMethod")
					+ "'; should be 'jndi#path', 'file#filename' or 'create'");
		}

		if (omData.getMethod().equals("create")) {
			session = creator.getSession();
			try {
				topic = (Topic)session.createTopic(createTopicName);
			} catch(JMSException ex) {
				throw new Config4JMSException(ex, cfg.fileName() + ": error in "
										+ "creating object for " + scope
										+ "; Session.createQueue() failed: "
										+ ex.toString());
			}
		} else {
			topic = (Topic)importFromFileOrJNDI(omData, scope, Topic.class);
		}

		//--------
		// Set optional attributes
		//--------
		setAttribute(topic, "name", "setName", String.class, name);
		setAttribute(topic, "topicName", "setTopicName", String.class,
					 topicName);
	}

	Topic getTopic()
	{
		return topic;
	}

	public Object getObject()
	{
		return topic;
	}

}


text:
game.HeroCreep = me.Entity.extend({
	init: function(x, y, settings){
		this._super(me.Entity, 'init', [x, y, {
			image: "creep2",
			width: 100,
			height: 85,
			spritewidth: "100",
			spriteheight: "85",
			getShape: function(){
				return(new me.Rect(0, 0, 100, 85)).toPolygon();
			}
		}]);
		this.health = game.data.playerHealth;
		this.alwaysUpdate = true;
		// this.attacking lets us know if the enemy is currently attacking
		this.attacking = false;
		// keeps track of when our creep attacks anything
		this.lastAttacking = new Date().getTime();
		// keeps track of the last time our creep hit anything
		this.lastHit = new Date().getTime();
		this.now = new Date().getTime();
		this.body.setVelocity(3, 20);

		this.type = "HeroCreep";

		this.renderable.addAnimation("walk", [0, 1, 2, 3, 4,], 80);
		this.renderable.setCurrentAnimation("walk");
	},

	loseHealth: function(damage){
		this.health = this.health - damage;
		// setting the health of the creep
	},

	update: function(delta){
		// removes creep when dead
		if(this.health <= 0){
			me.game.world.removeChild(this);
		}
		this.now = new Date().getTime();

		// Has the creep walk left
		this.body.vel.x += this.body.accel.x * me.timer.tick;
		this.flipX(true);

		me.collision.check(this, true, this.collideHandler.bind(this), true);

		this.body.update(delta);

		this._super(me.Entity, "update", [delta]);

		return true;
	},

	collideHandler: function(response){
		if(response.b.type==='FriendBase'){
			this.attacking=true;
			// this.lastAttacking=this.now;

			this.body.vel.x = 0;
			// keeps movingthe creep to the right to maintain position
			this.pos.x = this.pos.x + 1;
			// checks that it has has been at least one second since the creep has hits something
			if((this.now-this.lastHit >= 300) && xdif>0){
				// updates the last hit timer
				this.lastHit = this.now;
				// makes the player  call its loseHealth functionand passes it a damage of 1
				response.b.loseHealth(game.data.playerAttack);
			}
			if(xdif>0){
				// keeps movingthe creep to the right to maintain position
				this.pos.x = this.pos.x + 1;
				this.body.vel.x = 0;
			}
			// checks that it has has been at least one second since the creep has hit a base
			if((this.now-this.lastHit >= 300)){
				// updates the last hit timer
				this.lastHit = this.now;
				// makes the player base call its loseHealth functionand passes it a damage of 1
				response.b.loseHealth(game.data.playerAttack);
			}
		}else if(response.b.type==='FriendCreep'){
			var xdif = this.pos.x - response.b.pos.x;

			this.attacking=true;
			// this.lastAttacking=this.now;
			this.body.vel.x = 0;
			// keeps movingthe creep to the right to maintain position
			this.pos.x = this.pos.x + 1;
			// checks that it has has been at least one second since the creep has hits something
			if((this.now-this.lastHit >= 300) && xdif>0){
				// updates the last hit timer
				this.lastHit = this.now;
				// makes the player  call its loseHealth functionand passes it a damage of 1
				response.b.loseHealth(game.data.playerAttack);
			}
		}
	}
});


text:
package sample;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.context.ServletWebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.integration.annotation.MessageEndpoint;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.messaging.Message;
import org.springframework.web.client.RestTemplate;

/**
 * @author Dave Syer
 *
 */
@MessageEndpoint
public class SampleService implements ApplicationListener<ServletWebServerInitializedEvent> {

	private static final Log log = LogFactory.getLog(SampleService.class);

	@Autowired
	private RestTemplate restTemplate;

	private int port;

	@ServiceActivator(inputChannel = "messages")
	public void log(Message<?> message) {
		log.info("Received: " + message);
		this.restTemplate.getForObject("http://localhost:" + this.port + "/foo", String.class);
	}

	@Override
	public void onApplicationEvent(ServletWebServerInitializedEvent event) {
		this.port = event.getSource().getPort();
	}

}


text:
package com.squareup.wire.protos.redacted;

import com.squareup.wire.Message;
import com.squareup.wire.ProtoField;
import java.lang.Object;
import java.lang.Override;

public final class RedactedCycleB extends Message {
  private static final long serialVersionUID = 0L;

  @ProtoField(
      tag = 1
  )
  public final RedactedCycleA a;

  public RedactedCycleB(RedactedCycleA a) {
    this.a = a;
  }

  private RedactedCycleB(Builder builder) {
    this(builder.a);
    setBuilder(builder);
  }

  @Override
  public boolean equals(Object other) {
    if (other == this) return true;
    if (!(other instanceof RedactedCycleB)) return false;
    return equals(a, ((RedactedCycleB) other).a);
  }

  @Override
  public int hashCode() {
    int result = hashCode;
    return result != 0 ? result : (hashCode = a != null ? a.hashCode() : 0);
  }

  public static final class Builder extends com.squareup.wire.Message.Builder<RedactedCycleB> {
    public RedactedCycleA a;

    public Builder() {
    }

    public Builder(RedactedCycleB message) {
      super(message);
      if (message == null) return;
      this.a = message.a;
    }

    public Builder a(RedactedCycleA a) {
      this.a = a;
      return this;
    }

    @Override
    public RedactedCycleB build() {
      return new RedactedCycleB(this);
    }
  }
}


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { StyleSheet, View } from 'react-native';
import { BarCodeScanner, Permissions } from 'expo';
import { Text } from 'native-base';
import { AlertIcon } from '~/components/Icons/';
import SimpleMessage from '../SimpleMessage/';
import styles from './styles';

class BarCodeScannerPlus extends Component {
  constructor(props) {
    super(props);
    this.state = {
      hasCameraPermission: null,
      cameraMode: props.defaultCameraMode,
      torchMode: props.defaultTorchMode,
    };
  }

  async componentWillMount() {
    const { status } = await Permissions.askAsync(Permissions.CAMERA);
    this.setState({
      hasCameraPermission: status === 'granted',
    });
  }

  toggleTorchMode = () => {
    this.setState({ torchMode: !this.state.torchMode });
  }

  toggleCameraMode = () => {
    this.setState({ cameraMode: this.state.cameraMode === 'back' ? 'front' : 'back' });
  }

  _onBarCodeRead = (data) => {
    if (this.props.paused) {
      return false;
    }
    if (this.props.onBarCodeRead) {
      this.props.onBarCodeRead(data);
    }
  }

  renderToolbar() {
    const { IconReverseCamera, IconReverseCameraActive, IconFlashCamera, IconFlashCameraActive } = this.props;

    if (!IconReverseCamera && !IconFlashCamera) {
      return null;
    }
    return (
      <View style={styles.toolbar}>
        { IconReverseCamera ? (
          this.state.cameraMode === 'back' && IconReverseCameraActive ?
            <IconReverseCameraActive onPress={this.toggleCameraMode} style={styles.toolbarIcon} /> :
            <IconReverseCamera onPress={this.toggleCameraMode} style={styles.toolbarIcon} />
        ) : null}

        { IconFlashCamera ? (
          this.state.torchMode && IconFlashCameraActive ?
            <IconFlashCameraActive onPress={this.toggleTorchMode} style={styles.toolbarIcon} /> :
            <IconFlashCamera onPress={this.toggleTorchMode} style={styles.toolbarIcon} />
        ) : null}
      </View>
    );
  }

  render() {
    const { hasCameraPermission } = this.state;

    if (hasCameraPermission === null) {
      return (
        <SimpleMessage
          text={this.props.permissionRequestText}
          loader={true}
        />
      );
    }

    if (hasCameraPermission === false) {
      return (
        <SimpleMessage
          text={this.props.permissionDeniedText}
          Icon={AlertIcon}
        />
      );
    }

    return (
      <View style={styles.container}>
        <BarCodeScanner
          onBarCodeRead={this._onBarCodeRead}
          style={StyleSheet.absoluteFill}
          type={this.state.cameraMode}
          torchMode={this.state.torchMode ? 'on' : 'off'}
        />

        {this.renderToolbar()}

        {this.props.paused ? null : (
          <View style={styles.frameWrapper}>
            <View style={styles.frame}>
              <Text style={styles.frameText}>{this.props.adviseText}</Text>
            </View>
          </View>
        )}
      </View>
    );
  }
}

BarCodeScannerPlus.propTypes = {
  defaultCameraMode: PropTypes.oneOf(['back', 'front']),
  defaultTorchMode: PropTypes.bool,
  onBarCodeRead: PropTypes.func,
  adviseText: PropTypes.string,
  paused: PropTypes.bool,
  IconReverseCamera: PropTypes.func,
  IconReverseCameraActive: PropTypes.func,
  IconFlashCamera: PropTypes.func,
  IconFlashCameraActive: PropTypes.func,
  permissionRequestText: PropTypes.string,
  permissionDeniedText: PropTypes.string,
};

BarCodeScannerPlus.defaultProps = {
  defaultCameraMode: 'back',
  defaultTorchMode: false,
  onBarCodeRead: null,
  adviseText: 'Scan a barcode',
  paused: false,
  IconReverseCamera: null,
  IconReverseCameraActive: null,
  IconFlashCamera: null,
  IconFlashCameraActive: null,
  permissionRequestText: "Requesting access to the camera",
  permissionDeniedText: "The app cannot use the camera. Allow the application to access the camera in your device preferences to use the barcode scanner.",
}

export default BarCodeScannerPlus;


text:
<?php //echo base_url(); ?>
<?php //echo site_url(); ?>

请登录

                        <?php //echo validation_errors(); ?>
                        <?php echo form_open('admin/login/validate'); ?>
                            <fieldset>

                                    <input class="form-control" placeholder="Username" name="username" type="text" value="admin" autofocus>

                                <?php echo form_error('username', '
', '
'); ?>

                                    <input class="form-control" placeholder="Password" name="password" type="password" value="123456">

                                <?php echo form_error('password', '
', '
'); ?>

<?php if( isset($msg) ) echo $msg; ?>

                                <button type="submit" onclick="login_change();" class="btn btn-lg btn-success btn-block loging">登录</button>
                            </fieldset>
                        </form>


text:
__author__ = 'Hinsteny'

class Node(object):

    def __init__(self, data):
        self.data = data
        self.prev = None
        self.next = None

class DoublyLinkedList(object):

    def __init__(self):
        self.head = None
        self.tail = None
        # Number of nodes in list
        self.count = 0

    def add_node(self, cls, data):
        '''
        Add node instance of class cls.
        :param cls:
        :param data:
        :return:
        '''
        return self.insert_node(cls, data, self.tail, None)

    def insert_node(self, cls, data, prev, next):
        '''
        Insert node instaance of class cls.
        :param cls:
        :param data:
        :param pre:
        :param next:
        :return:
        '''
        node = cls(data)
        node.prev = prev
        node.next = next
        if prev:
            prev.next = node
        if next:
            next.prev = node
        if not self.head or next is self.head:
            self.head = node
        if not self.tail or next is self.tail:
            self.tail = node
        self.count += 1
        return node

    def remove_node(self, node):
        if node is self.tail:
            self.tail = node.prev
        else:
            node.next.prev = node.prev

        if node is self.head:
            self.head = node.next
        else:
            node.prev.next = node.next
        self.count -= 1

    def get_nodes_data(self):
        '''

        :return:
        '''
        data = []
        node = self.head
        while node:
            data.append(node.data)
            node = node.next
        return node

class FreqNode(DoublyLinkedList, Node):
    '''
    Frequency node containin
    '''