text:
// Copyright © 2017-2018 Mikael Berthe <mikael@lilotux.net>
//
// Licensed under the MIT license.
// Please see the LICENSE file is this directory.

package cmd

import (
	"io/ioutil"
	"os"
	"strings"

	"github.com/pkg/errors"
	"github.com/spf13/cobra"
	flag "github.com/spf13/pflag"

	"github.com/McKael/madon/v2"
)

var statusPostFlags *flag.FlagSet

var statusOpts struct {
	statusID int64
	unset    bool // TODO remove eventually?

	// The following fields are used for the post/toot command
	visibility     string
	sensitive      bool
	spoiler        string
	inReplyToID    int64
	mediaIDs       string
	mediaFilePath  string
	textFilePath   string
	stdin          bool
	addMentions    bool
	sameVisibility bool

	// Used for several subcommands to limit the number of results
	limit, keep uint
	//sinceID, maxID int64
	all bool
}

func init() {
	RootCmd.AddCommand(statusCmd)

	// Subcommands
	statusCmd.AddCommand(statusSubcommands...)

	// Global flags
	statusCmd.PersistentFlags().Int64VarP(&statusOpts.statusID, "status-id", "s", 0, "Status ID number")
	statusCmd.PersistentFlags().UintVarP(&statusOpts.limit, "limit", "l", 0, "Limit number of API results")
	statusCmd.PersistentFlags().UintVarP(&statusOpts.keep, "keep", "k", 0, "Limit number of results")
	//statusCmd.PersistentFlags().Int64Var(&statusOpts.sinceID, "since-id", 0, "Request IDs greater than a value")
	//statusCmd.PersistentFlags().Int64Var(&statusOpts.maxID, "max-id", 0, "Request IDs less (or equal) than a value")
	statusCmd.PersistentFlags().BoolVar(&statusOpts.all, "all", false, "Fetch all results (for reblogged-by/favourited-by)")

	// Subcommand flags
	statusReblogSubcommand.Flags().BoolVar(&statusOpts.unset, "unset", false, "Unreblog the status (deprecated)")
	statusFavouriteSubcommand.Flags().BoolVar(&statusOpts.unset, "unset", false, "Remove the status from the favourites (deprecated)")
	statusPinSubcommand.Flags().BoolVar(&statusOpts.unset, "unset", false, "Unpin the status (deprecated)")
	statusPostSubcommand.Flags().BoolVar(&statusOpts.sensitive, "sensitive", false, "Mark post as sensitive (NSFW)")
	statusPostSubcommand.Flags().StringVar(&statusOpts.visibility, "visibility", "", "Visibility (direct|private|unlisted|public)")
	statusPostSubcommand.Flags().StringVar(&statusOpts.spoiler, "spoiler", "", "Spoiler warning (CW)")
	statusPostSubcommand.Flags().StringVar(&statusOpts.mediaIDs, "media-ids", "", "Comma-separated list of media IDs")
	statusPostSubcommand.Flags().StringVarP(&statusOpts.mediaFilePath, "file", "f", "", "Media file name")
	statusPostSubcommand.Flags().StringVar(&statusOpts.textFilePath, "text-file", "", "Text file name (message content)")
	statusPostSubcommand.Flags().Int64VarP(&statusOpts.inReplyToID, "in-reply-to", "r", 0, "Status ID to reply to")
	statusPostSubcommand.Flags().BoolVar(&statusOpts.stdin, "stdin", false, "Read message content from standard input")
	statusPostSubcommand.Flags().BoolVar(&statusOpts.addMentions, "add-mentions", false, "Add mentions when replying")
	statusPostSubcommand.Flags().BoolVar(&statusOpts.sameVisibility, "same-visibility", false, "Use same visibility as original message (for replies)")

	// Deprecated flags
	statusReblogSubcommand.Flags().MarkDeprecated("unset", "please use unboost instead")
	statusFavouriteSubcommand.Flags().MarkDeprecated("unset", "please use unfavourite instead")
	statusPinSubcommand.Flags().MarkDeprecated("unset", "please use unpin instead")

	// Flag completion
	annotation := make(map[string][]string)
	annotation[cobra.BashCompCustom] = []string{"__madonctl_visibility"}

	statusPostSubcommand.Flags().Lookup("visibility").Annotations = annotation

	// This one will be used to check if the options were explicitly set or not
	statusPostFlags = statusPostSubcommand.Flags()
}

// statusCmd represents the status command
// This command does nothing without a subcommand
var statusCmd = &cobra.Command{
	Use:     "status --status-id ID subcommand",
	Aliases: []string{"st"},
	Short:   "Get status details",
	//Long:    `TBW...`, // TODO
	PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
		// This is common to status and all status subcommands but "post"
		if statusOpts.statusID < 1 && cmd.Name() != "post" {
			return errors.New("missing status ID")
		}
		return madonInit(true)
	},
}

var statusSubcommands = []*cobra.Command{
	&cobra.Command{
		Use:     "show",
		Aliases: []string{"display"},
		Short:   "Get the status",
		RunE: func(cmd *cobra.Command, args []string) error {
			return statusSubcommandRunE(cmd.Name(), args)
		},
	},
	&cobra.Command{
		Use:   "context",
		Short: "Get the status context",
		RunE: func(cmd *cobra.Command, args []string) error {
			return statusSubcommandRunE(cmd.Name(), args)
		},
	},
	&cobra.Command{
		Use:   "card",
		Short: "Get the status card",
		RunE: func(cmd *cobra.Command, args []string) error {
			return statusSubcommandRunE(cmd.Name(), args)
		},
	},
	&cobra.Command{
		Use:   "reblogged-by",
		Short: "Display accounts which reblogged the status",
		RunE: func(cmd *cobra.Command, args []string) error {
			return statusSubcommandRunE(cmd.Name(), args)
		},
	},
	&cobra.Command{
		Use:     "favourited-by",
		Aliases: []string{"favorited-by"},
		Short:   "Display accounts which favourited the status",
		RunE: func(cmd *cobra.Command, args []string) error {
			return statusSubcommandRunE(cmd.Name(), args)
		},
	},
	&cobra.Command{
		Use:     "delete",
		Aliases: []string{"rm"},
		Short:   "Delete the status",
		RunE: func(cmd *cobra.Command, args []string) error {
			return statusSubcommandRunE(cmd.Name(), args)
		},
	},
	&cobra.Command{
		Use:     "mute-conversation",
		Aliases: []string{"mute"},
		Short:   "Mute the conversation containing the status",
		RunE: func(cmd *cobra.Command, args []string) error {
			return statusSubcommandRunE(cmd.Name(), args)
		},
	},
	&cobra.Command{
		Use:     "unmute-conversation",
		Aliases: []string{"unmute"},
		Short:   "Unmute the conversation containing the status",
		RunE: func(cmd *cobra.Command, args []string) error {
			return statusSubcommandRunE(cmd.Name(), args)
		},
	},
	statusReblogSubcommand,
	statusUnreblogSubcommand,
	statusFavouriteSubcommand,
	statusUnfavouriteSubcommand,
	statusPinSubcommand,
	statusUnpinSubcommand,
	statusPostSubcommand,
}

var statusReblogSubcommand = &cobra.Command{
	Use:     "boost",
	Aliases: []string{"reblog"},
	Short:   "Boost (reblog) a status message",
	RunE: func(cmd *cobra.Command, args []string) error {
		return statusSubcommandRunE(cmd.Name(), args)
	},
}

var statusUnreblogSubcommand = &cobra.Command{
	Use:     "unboost",
	Aliases: []string{"unreblog"},
	Short:   "Cancel boost (reblog) of a status message",
	RunE: func(cmd *cobra.Command, args []string) error {
		return statusSubcommandRunE(cmd.Name(), args)
	},
}

var statusFavouriteSubcommand = &cobra.Command{
	Use:     "favourite",
	Aliases: []string{"favorite", "fave"},
	Short:   "Mark the status as favourite",
	RunE: func(cmd *cobra.Command, args []string) error {
		return statusSubcommandRunE(cmd.Name(), args)
	},
}

var statusUnfavouriteSubcommand = &cobra.Command{
	Use:     "unfavourite",
	Aliases: []string{"unfavorite", "unfave"},
	Short:   "Unmark the status as favourite",
	RunE: func(cmd *cobra.Command, args []string) error {
		return statusSubcommandRunE(cmd.Name(), args)
	},
}

var statusPinSubcommand = &cobra.Command{
	Use:   "pin",
	Short: "Pin a status",
	RunE: func(cmd *cobra.Command, args []string) error {
		return statusSubcommandRunE(cmd.Name(), args)
	},
}

var statusUnpinSubcommand = &cobra.Command{
	Use:   "unpin",
	Short: "Unpin a status",
	RunE: func(cmd *cobra.Command, args []string) error {
		return statusSubcommandRunE(cmd.Name(), args)
	},
}

var statusPostSubcommand = &cobra.Command{
	Use:     "post",
	Aliases: []string{"toot", "pouet"},
	Short:   "Post a message (same as 'madonctl toot')",
	Example: `  madonctl status post "Hello, World"
  madonctl status post --spoiler Warning "Spoiled"
  madonctl status toot --visibility private "To my followers only"
  madonctl status toot --sensitive --file image.jpg Image
  madonctl status post --media-ids ID1,ID2,ID3 Image
  madonctl status toot --text-file message.txt
  madonctl status post --in-reply-to STATUSID "@user response"
  madonctl status post --in-reply-to STATUSID --add-mentions "response"
  echo "Hello from #madonctl" | madonctl status toot --stdin

The default visibility can be set in the configuration file with the option
'default_visibility' (or with an environmnent variable).`,
	RunE: func(cmd *cobra.Command, args []string) error {
		return statusSubcommandRunE(cmd.Name(), args)
	},
}

func statusSubcommandRunE(subcmd string, args []string) error {
	opt := statusOpts

	var obj interface{}
	var err error

	var limOpts *madon.LimitParams
	if opt.all || opt.limit > 0 /* || opt.sinceID > 0 || opt.maxID > 0 */ {
		limOpts = new(madon.LimitParams)
		limOpts.All = opt.all
	}

	if opt.limit > 0 {
		limOpts.Limit = int(opt.limit)
	}
	/*
		if opt.maxID > 0 {
			limOpts.MaxID = int64(opt.maxID)
		}
		if opt.sinceID > 0 {
			limOpts.SinceID = int64(opt.sinceID)
		}
	*/

	switch subcmd {
	case "show":
		var status *madon.Status
		status, err = gClient.GetStatus(opt.statusID)
		obj = status
	case "context":
		var context *madon.Context
		context, err = gClient.GetStatusContext(opt.statusID)
		obj = context
	case "card":
		var context *madon.Card
		context, err = gClient.GetStatusCard(opt.statusID)
		obj = context
	case "reblogged-by":
		var accountList []madon.Account
		accountList, err = gClient.GetStatusRebloggedBy(opt.statusID, limOpts)
		if opt.keep > 0 && len(accountList) > int(opt.keep) {
			accountList = accountList[:opt.keep]
		}
		obj = accountList
	case "favourited-by":
		var accountList []madon.Account
		accountList, err = gClient.GetStatusFavouritedBy(opt.statusID, limOpts)
		if opt.keep > 0 && len(accountList) > int(opt.keep) {
			accountList = accountList[:opt.keep]
		}
		obj = accountList
	case "delete":
		err = gClient.DeleteStatus(opt.statusID)
	case "boost", "unboost":
		if opt.unset || subcmd == "unboost" {
			err = gClient.UnreblogStatus(opt.statusID)
		} else {
			err = gClient.ReblogStatus(opt.statusID)
		}
	case "favourite", "unfavourite":
		if opt.unset || subcmd == "unfavourite" {
			err = gClient.UnfavouriteStatus(opt.statusID)
		} else {
			err = gClient.FavouriteStatus(opt.statusID)
		}
	case "pin", "unpin":
		if opt.unset || subcmd == "unpin" {
			err = gClient.UnpinStatus(opt.statusID)
		} else {
			err = gClient.PinStatus(opt.statusID)
		}
	case "mute-conversation":
		var s *madon.Status
		s, err = gClient.MuteConversation(opt.statusID)
		obj = s
	case "unmute-conversation":
		var s *madon.Status
		s, err = gClient.UnmuteConversation(opt.statusID)
		obj = s
	case "post": // toot
		var s *madon.Status
		text := strings.Join(args, " ")
		if opt.textFilePath != "" {
			var b []byte
			if b, err = ioutil.ReadFile(opt.textFilePath); err != nil {
				break
			}
			text = string(b)
		} else if opt.stdin {
			var b []byte
			if b, err = ioutil.ReadAll(os.Stdin); err != nil {
				break
			}
			text = string(b)
		}
		s, err = toot(text)
		obj = s
	default:
		return errors.New("statusSubcommand: internal error")
	}

	if err != nil {
		errPrint("Error: %s", err.Error())
		os.Exit(1)
	}
	if obj == nil {
		return nil
	}

	p, err := getPrinter()
	if err != nil {
		errPrint("Error: %s", err.Error())
		os.Exit(1)
	}
	return p.printObj(obj)
}


text:
package com.bigdata.sync;

import dataClass.*;

public interface HandleData {
	public void handleData(RFNodeData nodeData);
}

redpajama_set_name: RedPajamaGithub


text: SELECT @TableName::regclass::oid AS "Oid";


text:
namespace ash::diagnostics {

class KeyboardInputLog;

// Provides information about input devices connected to the system. Implemented
// in the browser process, constructed within the Diagnostics_UI in the browser
// process, and eventually called by the Diagnostics SWA (a renderer process).
class InputDataProvider : public mojom::InputDataProvider,
                          public ui::DeviceEventObserver,
                          public KeyboardInputDataEventWatcher::Dispatcher,
                          public views::WidgetObserver,
                          public TabletModeObserver,
                          public display::DisplayConfigurator::Observer {
 public:
  explicit InputDataProvider(aura::Window* window,
                             KeyboardInputLog* keyboard_input_log_ptr);
  explicit InputDataProvider(
      aura::Window* window,
      std::unique_ptr<ui::DeviceManager> device_manager,
      std::unique_ptr<EventWatcherFactory> watcher_factory,
      KeyboardInputLog* keyboard_input_log_ptr,
      AcceleratorControllerImpl* accelerator_controller,
      ui::EventRewriterChromeOS::Delegate* event_rewriter_delegate);
  InputDataProvider(const InputDataProvider&) = delete;
  InputDataProvider& operator=(const InputDataProvider&) = delete;
  ~InputDataProvider() override;

  static bool ShouldCloseDialogOnEscape() {
    return should_close_dialog_on_escape_;
  }

  void BindInterface(
      mojo::PendingReceiver<mojom::InputDataProvider> pending_receiver);

  static mojom::ConnectionType ConnectionTypeFromInputDeviceType(
      ui::InputDeviceType type);

  // KeyboardInputDataEventWatcher::Dispatcher:
  void SendInputKeyEvent(uint32_t id,
                         uint32_t key_code,
                         uint32_t scan_code,
                         bool down) override;

  // mojom::InputDataProvider:
  void GetConnectedDevices(GetConnectedDevicesCallback callback) override;

  void ObserveConnectedDevices(
      mojo::PendingRemote<mojom::ConnectedDevicesObserver> observer) override;

  void ObserveKeyEvents(
      uint32_t id,
      mojo::PendingRemote<mojom::KeyboardObserver> observer) override;

  void ObserveTabletMode(
      mojo::PendingRemote<mojom::TabletModeObserver> observer,
      ObserveTabletModeCallback callback) override;

  void ObserveInternalDisplayPowerState(
      mojo::PendingRemote<mojom::InternalDisplayPowerStateObserver> observer)
      override;

  void MoveAppToTestingScreen(uint32_t evdev_id) override;

  void MoveAppBackToPreviousScreen() override;

  void SetA11yTouchPassthrough(bool enabled) override;

  // ui::DeviceEventObserver:
  void OnDeviceEvent(const ui::DeviceEvent& event) override;

  // views::WidgetObserver:
  void OnWidgetVisibilityChanged(views::Widget* widget, bool visible) override;
  void OnWidgetActivationChanged(views::Widget* widget, bool active) override;

  // TabletModeObserver:
  void OnTabletModeStarted() override;
  void OnTabletModeEnded() override;

  // display::DisplayConfigurator::Observer
  void OnPowerStateChanged(chromeos::DisplayPowerState power_state) override;

  // Get the value of is_internal_display_on_ for testing purpose.
  bool is_internal_display_on() { return is_internal_display_on_; }

  void SetLogForTesting(KeyboardInputLog* keyboard_input_log_ptr) {
    keyboard_input_log_ptr_ = keyboard_input_log_ptr;
  }

 protected:
  base::SequenceBound<InputDeviceInfoHelper> info_helper_{
      base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})};

 private:
  void Initialize(aura::Window* window);

  void ProcessDeviceInfo(std::unique_ptr<InputDeviceInformation> device_info);

  void AddTouchDevice(const InputDeviceInformation* device_info);
  void AddKeyboard(const InputDeviceInformation* device_info);

  bool may_send_events_ = false;

  // Review widget state to determine whether it is safe to send events.
  void UpdateMaySendEvents();
  // Pass on pause or resume events to observers if that state has changed.
  void UpdateEventObservers();

  void SendPauseEvents();
  void SendResumeEvents();

  void BlockShortcuts(bool should_block);

  InputDataProviderKeyboard keyboard_helper_;
  InputDataProviderTouch touch_helper_;

  // Handle destroyed KeyboardObservers.
  void OnObservedKeyboardInputDisconnect(uint32_t evdev_id,
                                         mojo::RemoteSetElementId observer_id);
  // Manage watchers that read an evdev and process events for observers.
  void ForwardKeyboardInput(uint32_t id);
  void UnforwardKeyboardInput(uint32_t id);

  const std::string GetKeyboardName(uint32_t id);

  bool IsLoggingEnabled() const;

  base::raw_ptr<KeyboardInputLog> keyboard_input_log_ptr_ =
      nullptr;  // Not Owned.

  // Denotes whether DiagnosticsDialog should be closed when escape is pressed.
  // Currently, this is only false when the keyboard tester is actively in use.
  static bool should_close_dialog_on_escape_;

  // Whether a tablet mode switch is present (which we use as a hint for the
  // top-right key glyph).
  bool has_tablet_mode_switch_ = false;

  // Whether the internal touchscreen is on, used to determine if the internal
  // display is testable or not.
  bool is_internal_display_on_ = true;

  // Id of the previous display the Diagnostics app was in, used to move the app
  // back to previous display when the touchscreen tester is closed.
  int64_t previous_display_id_ = display::kInvalidDisplayId;

  // Map by evdev ids to information blocks.
  base::flat_map<int, mojom::KeyboardInfoPtr> keyboards_;
  base::flat_map<int, std::unique_ptr<InputDataProviderKeyboard::AuxData>>
      keyboard_aux_data_;
  base::flat_map<int, mojom::TouchDeviceInfoPtr> touch_devices_;

  // Map by evdev ids to remote observers and event watchers.
  base::flat_map<int, std::unique_ptr<mojo::RemoteSet<mojom::KeyboardObserver>>>
      keyboard_observers_;
  base::flat_map<int, std::unique_ptr<InputDataEventWatcher>>
      keyboard_watchers_;

  // Timestamp of when keyboard tester is first opened. Undefined if the
  // keyboard tester is not open.
  base::Time keyboard_tester_start_timestamp_;

  bool logged_not_dispatching_key_events_ = false;
  views::Widget* widget_ = nullptr;

  mojo::RemoteSet<mojom::ConnectedDevicesObserver> connected_devices_observers_;

  mojo::Remote<mojom::TabletModeObserver> tablet_mode_observer_;

  mojo::Remote<mojom::InternalDisplayPowerStateObserver>
      internal_display_power_state_observer_;

  mojo::Receiver<mojom::InputDataProvider> receiver_{this};

  std::unique_ptr<ui::DeviceManager> device_manager_;

  std::unique_ptr<EventWatcherFactory> watcher_factory_;

  raw_ptr<AcceleratorControllerImpl> accelerator_controller_;
  raw_ptr<ui::EventRewriterChromeOS::Delegate> event_rewriter_delegate_;

  base::WeakPtrFactory<InputDataProvider> weak_factory_{this};
};

}  // namespace ash::diagnostics

#endif  // ASH_WEBUI_DIAGNOSTICS_UI_BACKEND_INPUT_INPUT_DATA_PROVIDER_H_


text:
async function slow(scale) {
    function fab(n) {
        if (n <= 1) return 1;
        return fab(n - 1) + fab(n - 2);
    }
    return new Promise((resolve, reject) => {
        for (var idx = 0; idx < scale; idx++) {
            fab(40);
            console.log(`count down: ${scale-idx}`);
        }
        resolve("wow");
    });
}

// this method is require according to the fact that javascript does not
// allow await in global context. await must be inside a async function.
async function testSlow(scale) {
    console.log(`before run slow(${scale})`);
    await slow(scale);
    console.log("after run slow");
}

testSlow(5);


text:
def f(url):
    '''Return the representation available at the URL.

    '''
    return open(url).read()


text:
<?php

namespace Klever\Tutor\AccessMethod;

use PHPUnit\Framework\SkippedTestError;

trait TestConfigurationTrait
{
    abstract public function getClassAccessMethodTestConfiguration();

    protected function validateConfiguration($config)
    {
        $accessors = (isset($config['accessors']) && is_array($config['accessors']))
            ? $config['accessors'] : array();

        if (count($accessors) === 0) {
            throw new SkippedTestError(
                'No class access method test configuration provided'
            );
        }
    }

    public function getClassAccessMethodTestData()
    {
        $config = $this->getClassAccessMethodTestConfiguration();
        $this->validateConfiguration($config);

        $data = array();
        foreach ($config['accessors'] as $name => $propertyConfig) {
            if (!isset($propertyConfig['accessor_name'])) {
                $propertyConfig['accessor_name'] = $name;
            }

            $data[] = array(TestConfiguration::fromArray($propertyConfig));
        }

        return $data;
    }
}


text:
curl -L http://debian.datastax.com/debian/repo_key | apt-key add -

apt-get update
apt-get -y -f install libjna-java dsc20 python-cql

ln -s /usr/share/java/jna.jar /usr/share/cassandra/lib


text:
"""Test the wallet accounts properly when there are cloned transactions with malleated scriptsigs."""

from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
    assert_equal,
)
from test_framework.messages import (
    COIN,
    tx_from_hex,
)

class TxnMallTest(BitcoinTestFramework):
    def set_test_params(self):
        self.num_nodes = 3
        self.supports_cli = False

    def skip_test_if_missing_module(self):
        self.skip_if_no_wallet()

    def add_options(self, parser):
        parser.add_argument("--mineblock", dest="mine_block", default=False, action="store_true",
                            help="Test double-spend of 1-confirmed transaction")
        parser.add_argument("--segwit", dest="segwit", default=False, action="store_true",
                            help="Test behaviour with SegWit txn (which should fail)")

    def setup_network(self):
        # Start with split network:
        super().setup_network()
        self.disconnect_nodes(1, 2)

    def run_test(self):
        if self.options.segwit:
            output_type = "p2sh-segwit"
        else:
            output_type = "legacy"

        # All nodes should start with 1,250 BTC:
        starting_balance = 1250
        for i in range(3):
            assert_equal(self.nodes[i].getbalance()['bitcoin'], starting_balance)

        self.nodes[0].settxfee(.001)

        node0_address1 = self.nodes[0].getnewaddress(address_type=output_type)
        node0_txid1 = self.nodes[0].sendtoaddress(node0_address1, 1219)
        node0_tx1 = self.nodes[0].gettransaction(node0_txid1)

        node0_address2 = self.nodes[0].getnewaddress(address_type=output_type)
        node0_txid2 = self.nodes[0].sendtoaddress(node0_address2, 29)
        node0_tx2 = self.nodes[0].gettransaction(node0_txid2)

        assert_equal(self.nodes[0].getbalance()['bitcoin'],
                     starting_balance + node0_tx1["fee"]['bitcoin'] + node0_tx2["fee"]['bitcoin'])

        # Coins are sent to node1_address
        node1_address = self.nodes[1].getnewaddress()

        # Send tx1, and another transaction tx2 that won't be cloned
        txid1 = self.nodes[0].sendtoaddress(node1_address, 40)
        txid2 = self.nodes[0].sendtoaddress(node1_address, 20)

        # Construct a clone of tx1, to be malleated
        rawtx1 = self.nodes[0].getrawtransaction(txid1, 1)
        clone_inputs = [{"txid": rawtx1["vin"][0]["txid"], "vout": rawtx1["vin"][0]["vout"], "sequence": rawtx1["vin"][0]["sequence"]}]
        clone_outputs = [
            {rawtx1["vout"][0]["scriptPubKey"]["address"]: rawtx1["vout"][0]["value"]},
            {rawtx1["vout"][1]["scriptPubKey"]["address"]: rawtx1["vout"][1]["value"]},
        ]
        assert_equal(rawtx1["vout"][2]["scriptPubKey"]["type"], "fee")
        clone_outputs.append({"fee": rawtx1["vout"][2]["value"]})
        clone_locktime = rawtx1["locktime"]
        clone_raw = self.nodes[0].createrawtransaction(clone_inputs, clone_outputs, clone_locktime)

        # createrawtransaction randomizes the order of its outputs, so swap them if necessary.
        clone_tx = tx_from_hex(clone_raw)
        if (rawtx1["vout"][0]["value"] == 40 and clone_tx.vout[0].nValue.getAmount() != 40*COIN or rawtx1["vout"][0]["value"] != 40 and clone_tx.vout[0].nValue.getAmount() == 40*COIN):
            (clone_tx.vout[0], clone_tx.vout[1]) = (clone_tx.vout[1], clone_tx.vout[0])

        # Use a different signature hash type to sign.  This creates an equivalent but malleated clone.
        # Don't send the clone anywhere yet
        tx1_clone = self.nodes[0].signrawtransactionwithwallet(clone_tx.serialize().hex(), None, "ALL|ANYONECANPAY")
        assert_equal(tx1_clone["complete"], True)

        # Have node0 mine a block, if requested:
        if (self.options.mine_block):
            self.nodes[0].generate(1)
            self.sync_blocks(self.nodes[0:2])

        tx1 = self.nodes[0].gettransaction(txid1)
        tx2 = self.nodes[0].gettransaction(txid2)

        # Node0's balance should be starting balance, plus 50BTC for another
        # matured block, minus tx1 and tx2 amounts, and minus transaction fees:
        expected = starting_balance + node0_tx1["fee"]['bitcoin'] + node0_tx2["fee"]['bitcoin']
        if self.options.mine_block:
            expected += 50
        expected += tx1["amount"]['bitcoin'] + tx1["fee"]['bitcoin']
        expected += tx2["amount"]['bitcoin'] + tx2["fee"]['bitcoin']
        assert_equal(self.nodes[0].getbalance()['bitcoin'], expected)

        if self.options.mine_block:
            assert_equal(tx1["confirmations"], 1)
            assert_equal(tx2["confirmations"], 1)
        else:
            assert_equal(tx1["confirmations"], 0)
            assert_equal(tx2["confirmations"], 0)

        # Send clone and its parent to miner
        self.nodes[2].sendrawtransaction(node0_tx1["hex"])
        txid1_clone = self.nodes[2].sendrawtransaction(tx1_clone["hex"])
        if self.options.segwit:
            assert_equal(txid1, txid1_clone)
            return

        # ... mine a block...
        self.nodes[2].generate(1)

        # Reconnect the split network, and sync chain:
        self.connect_nodes(1, 2)
        self.nodes[2].sendrawtransaction(node0_tx2["hex"])
        self.nodes[2].sendrawtransaction(tx2["hex"])
        self.nodes[2].generate(1)  # Mine another block to make sure we sync
        self.sync_blocks()

        # Re-fetch transaction info:
        tx1 = self.nodes[0].gettransaction(txid1)
        tx1_clone = self.nodes[0].gettransaction(txid1_clone)
        tx2 = self.nodes[0].gettransaction(txid2)

        # Verify expected confirmations
        assert_equal(tx1["confirmations"], -2)
        assert_equal(tx1_clone["confirmations"], 2)
        assert_equal(tx2["confirmations"], 1)

        # Check node0's total balance; should be same as before the clone, + 100 BTC for 2 matured,
        # less possible orphaned matured subsidy
        expected += 100
        if (self.options.mine_block):
            expected -= 50
        assert_equal(self.nodes[0].getbalance()['bitcoin'], expected)

if __name__ == '__main__':
    TxnMallTest().main()


text:
package com.lbibera.tradebutler.datacore.historicalprice.repository;

import com.lbibera.tradebutler.datacore.historicalprice.model.HistoricalPrice;
import org.springframework.data.repository.PagingAndSortingRepository;

public interface HistoricalPriceRestRepository extends PagingAndSortingRepository<HistoricalPrice, Long> {
}


text:
/* Name: Thomas White
 * Class: ITSE 1430
 * Project: 4th Programming Assignment
 * Class Time: 5:00 pm
 * Date: 11/19/2017
 */

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

namespace MovieLib
{
    /// Provides a database of <see cref="Movie"/> items.
    public interface IMovieDatabase
    {
        /// Adds a movie.
        /// <param name="movie">The movie to add.</param>
        /// <returns>The added movie.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="movie"/> is null.</exception>
        /// <exception cref="ValidationException"><paramref name="movie"/> is invalid.</exception>
        /// <exception cref="ValidationException"><paramref name="movie"/> already exists.</exception>
        Movie Add(Movie movie);

        /// Get a specific movie.
        /// <returns>The movie, if it exists.</returns>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="id"/> must be greater than or equal to 0.</exception>
        Movie Get(int id);

        /// Gets all movies.
        /// <returns>The movies.</returns>
        IEnumerable<Movie> GetAll();

        /// Removes the movie.
        /// <param name="id">The movie to remove.</param>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="id"/> must be greater than or equal to 0.</exception>
        void Remove(int id);

        /// Updates a movie.
        /// <param name="movie">The movie to update.</param>
        /// <returns>The updated movie.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="movie"/> is null.</exception>
        /// <exception cref="ValidationException"><paramref name="movie"/> is invalid.</exception>
        /// <exception cref="ValidationException"><paramref name="movie"/> already exists.</exception>
        /// <exception cref="Exception">Movie not found.</exception>
        Movie Update(Movie movie);
    }
}


text: Generated by [ansible-docgen](https://www.github.com/starboarder2001/ansible-docgen)


text:
package w2.p2;

/**
 * Handles a rental of a car.
 */
public class AutoHuur {
  /** Amount of days the rental is for. */
  private int rentalLength = 0;
  /** The tenant of the car. */
  private Klant tenant;
  /** The rented car. */
  private Auto car;

  /** Constructor. */
  public AutoHuur() { };

  /**
   * Set the length of the rental.
   * @param rentalLength Length of the rental.
   */
  public void setAantalDagen(int rentalLength) {
    this.rentalLength = rentalLength;
  };

  /**
   * Set the rented car.
   * @param car Rented car.
   */
  public void setGehuurdeAuto(Auto car) {
    this.car = car;
  };

  /**
   * Get the rented car.
   * @return the rented car.
   */
  public Auto getGehuurdeAuto() {
    return this.car;
  };

  /**
   * Set the tenant of the car.
   * @param tenant The tenant.
   */
  public void setHuurder(Klant tenant) {
    this.tenant = tenant;
  };

  /**
   * Get the tenant.
   * @return the tenant.
   */
  public Klant getHuurder() {
    return this.tenant;
  };

  /**
   * Calculate the total price of the rental.
   * Returns 0.0 if a required value was missing.
   * @return The total price.
   */
  public double totaalPrijs() {
    if(this.rentalLength == 0 || this.tenant == null || this.car == null) {
      return 0.0;
    };
    return this.rentalLength * this.car.getPrijsPerDag() * ((100.0 - this.tenant.getKorting()) / 100);
  };

  /**
   * Returns a human readable representation of the class.
   * @return Human readable string.
   */
  public String toString() {
    String returnText;
    if (this.car == null) {
      returnText = "er is geen auto bekent\n";
    } else {
      returnText = "autoType: " + this.car.toString() + "\n";
    }

    if (this.tenant == null) {
      returnText = returnText + "er is geen huurder bekent\n";
    } else {
      returnText = returnText + "op naam van: " + this.tenant.toString() + "\n";
    }

    returnText = returnText + "aantal dagen: " + this.rentalLength
      + " en dat kost " + this.totaalPrijs();
    return returnText;
  };
};


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <!-- Load jdbc properties from config file -->
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>file:${java_web_app.config.path}/jdbc.properties</value>
                <value>file:${java_web_app.config.path}/mail.properties</value>
            </list>
        </property>
    </bean>

    <!-- Data Source -->
    <bean id="dataSource" class="org.postgresql.ds.PGPoolingDataSource">
        <property name="dataSourceName" value="${jdbc.dataSourceName}" />
        <property name="serverName" value="${jdbc.serverName}" />
        <property name="databaseName" value="${jdbc.databaseName}" />
        <property name="user" value="${jdbc.user}" />
        <property name="password" value="${jdbc.password}" />
        <property name="maxConnections" value="${jdbc.maxConnections}" />
    </bean>

    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="${mail.smtp.host}" />
        <property name="port" value="${mail.smtp.port}" />
        <property name="username" value="${mail.smtp.user}" />
        <property name="password" value="${mail.smtp.password}" />
        <property name="javaMailProperties">
            <props>
                <prop key="mail.transport.protocol">smtp</prop>
                <prop key="mail.smtp.auth">true</prop>
                <prop key="mail.smtp.debug">${mail.smtp.debug}</prop>
                <prop key="mail.smtp.starttls.enable">${mail.smtp.starttls}</prop>
            </props>
        </property>
    </bean>
    <!-- Transaction Manager -->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- Sql Session factory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:com/ipastushenko/core/dao/mybatis/mybatis-config.xml" />
        <property name="mapperLocations" value="classpath:com/ipastushenko/core/dao/mybatis/mapper/*.xml" />
    </bean>

    <!-- DAO -->
    <import resource="dao.xml" />

    <!-- Services -->
    <import resource="services.xml" />

    <!-- Security -->
    <import resource="security.xml" />
</beans>


text:
package org.joda.time.chrono;

import java.util.HashMap;
import java.util.Locale;

import org.joda.time.Chronology;
import org.joda.time.DateTimeConstants;
import org.joda.time.DateTimeField;
import org.joda.time.DateTimeZone;
import org.joda.time.DurationField;
import org.joda.time.IllegalFieldValueException;
import org.joda.time.IllegalInstantException;
import org.joda.time.ReadablePartial;
import org.joda.time.field.BaseDateTimeField;
import org.joda.time.field.BaseDurationField;

/**
 * Wraps another Chronology to add support for time zones.
 *

 * ZonedChronology is thread-safe and immutable.
 *
 * @author Brian S O'Neill
 * @author Stephen Colebourne
 * @since 1.0
 */
public final class ZonedChronology extends AssembledChronology {

    /** Serialization lock */
    private static final long serialVersionUID = -1079258847191166848L;
    /**
     * Avoid calculation errors near zero.
     */
    private static final long NEAR_ZERO = 7L * 24 * 60 * 60 * 1000;

    /**
     * Create a ZonedChronology for any chronology, overriding any time zone it
     * may already have.
     *
     * @param base base chronology to wrap
     * @param zone the time zone
     * @throws IllegalArgumentException if chronology or time zone is null
     */
    public static ZonedChronology getInstance(Chronology base, DateTimeZone zone) {
        if (base == null) {
            throw new IllegalArgumentException("Must supply a chronology");
        }
        base = base.withUTC();
        if (base == null) {
            throw new IllegalArgumentException("UTC chronology must not be null");
        }
        if (zone == null) {
            throw new IllegalArgumentException("DateTimeZone must not be null");
        }
        return new ZonedChronology(base, zone);
    }

    static boolean useTimeArithmetic(DurationField field) {
        // Use time of day arithmetic rules for unit durations less than
        // typical time zone offsets.
        return field != null && field.getUnitMillis() < DateTimeConstants.MILLIS_PER_HOUR * 12;
    }

    /**
     * Restricted constructor
     *
     * @param base base chronology to wrap
     * @param zone the time zone
     */
    private ZonedChronology(Chronology base, DateTimeZone zone) {
        super(base, zone);
    }

    public DateTimeZone getZone() {
        return (DateTimeZone)getParam();
    }

    public Chronology withUTC() {
        return getBase();
    }

    public Chronology withZone(DateTimeZone zone) {
        if (zone == null) {
            zone = DateTimeZone.getDefault();
        }
        if (zone == getParam()) {
            return this;
        }
        if (zone == DateTimeZone.UTC) {
            return getBase();
        }
        return new ZonedChronology(getBase(), zone);
    }

    public long getDateTimeMillis(int year, int monthOfYear, int dayOfMonth,
                                  int millisOfDay)
        throws IllegalArgumentException
    {
        return localToUTC(getBase().getDateTimeMillis
                          (year, monthOfYear, dayOfMonth, millisOfDay));
    }

    public long getDateTimeMillis(int year, int monthOfYear, int dayOfMonth,
                                  int hourOfDay, int minuteOfHour,
                                  int secondOfMinute, int millisOfSecond)
        throws IllegalArgumentException
    {
        return localToUTC(getBase().getDateTimeMillis
                          (year, monthOfYear, dayOfMonth,
                           hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond));
    }

    public long getDateTimeMillis(long instant,
                                  int hourOfDay, int minuteOfHour,
                                  int secondOfMinute, int millisOfSecond)
        throws IllegalArgumentException
    {
        return localToUTC(getBase().getDateTimeMillis
                          (instant + getZone().getOffset(instant),
                           hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond));
    }

    /**
     * @param localInstant  the instant from 1970-01-01T00:00:00 local time
     * @return the instant from 1970-01-01T00:00:00Z
     */
    private long localToUTC(long localInstant) {
        if (localInstant == Long.MAX_VALUE) {
            return Long.MAX_VALUE;
        } else if (localInstant == Long.MIN_VALUE) {
            return Long.MIN_VALUE;
        }
        DateTimeZone zone = getZone();
        int offset = zone.getOffsetFromLocal(localInstant);
        long utcInstant = localInstant - offset;
        if (localInstant > NEAR_ZERO && utcInstant < 0) {
            return Long.MAX_VALUE;
        } else if (localInstant < -NEAR_ZERO && utcInstant > 0) {
            return Long.MIN_VALUE;
        }
        int offsetBasedOnUtc = zone.getOffset(utcInstant);
        if (offset != offsetBasedOnUtc) {
            throw new IllegalInstantException(localInstant, zone.getID());
        }
        return utcInstant;
    }

    protected void assemble(Fields fields) {
        // Keep a local cache of converted fields so as not to create redundant
        // objects.
        HashMap<Object, Object> converted = new HashMap<Object, Object>();

        // Convert duration fields...

        fields.eras = convertField(fields.eras, converted);
        fields.centuries = convertField(fields.centuries, converted);
        fields.years = convertField(fields.years, converted);
        fields.months = convertField(fields.months, converted);
        fields.weekyears = convertField(fields.weekyears, converted);
        fields.weeks = convertField(fields.weeks, converted);
        fields.days = convertField(fields.days, converted);

        fields.halfdays = convertField(fields.halfdays, converted);
        fields.hours = convertField(fields.hours, converted);
        fields.minutes = convertField(fields.minutes, converted);
        fields.seconds = convertField(fields.seconds, converted);
        fields.millis = convertField(fields.millis, converted);

        // Convert datetime fields...

        fields.year = convertField(fields.year, converted);
        fields.yearOfEra = convertField(fields.yearOfEra, converted);
        fields.yearOfCentury = convertField(fields.yearOfCentury, converted);
        fields.centuryOfEra = convertField(fields.centuryOfEra, converted);
        fields.era = convertField(fields.era, converted);
        fields.dayOfWeek = convertField(fields.dayOfWeek, converted);
        fields.dayOfMonth = convertField(fields.dayOfMonth, converted);
        fields.dayOfYear = convertField(fields.dayOfYear, converted);
        fields.monthOfYear = convertField(fields.monthOfYear, converted);
        fields.weekOfWeekyear = convertField(fields.weekOfWeekyear, converted);
        fields.weekyear = convertField(fields.weekyear, converted);
        fields.weekyearOfCentury = convertField(fields.weekyearOfCentury, converted);

        fields.millisOfSecond = convertField(fields.millisOfSecond, converted);
        fields.millisOfDay = convertField(fields.millisOfDay, converted);
        fields.secondOfMinute = convertField(fields.secondOfMinute, converted);
        fields.secondOfDay = convertField(fields.secondOfDay, converted);
        fields.minuteOfHour = convertField(fields.minuteOfHour, converted);
        fields.minuteOfDay = convertField(fields.minuteOfDay, converted);
        fields.hourOfDay = convertField(fields.hourOfDay, converted);
        fields.hourOfHalfday = convertField(fields.hourOfHalfday, converted);
        fields.clockhourOfDay = convertField(fields.clockhourOfDay, converted);
        fields.clockhourOfHalfday = convertField(fields.clockhourOfHalfday, converted);
        fields.halfdayOfDay = convertField(fields.halfdayOfDay, converted);
    }

    private DurationField convertField(DurationField field, HashMap<Object, Object> converted) {
        if (field == null || !field.isSupported()) {
            return field;
        }
        if (converted.containsKey(field)) {
            return (DurationField)converted.get(field);
        }
        ZonedDurationField zonedField = new ZonedDurationField(field, getZone());
        converted.put(field, zonedField);
        return zonedField;
    }

    private DateTimeField convertField(DateTimeField field, HashMap<Object, Object> converted) {
        if (field == null || !field.isSupported()) {
            return field;
        }
        if (converted.containsKey(field)) {
            return (DateTimeField)converted.get(field);
        }
        ZonedDateTimeField zonedField =
            new ZonedDateTimeField(field, getZone(),
                                   convertField(field.getDurationField(), converted),
                                   convertField(field.getRangeDurationField(), converted),
                                   convertField(field.getLeapDurationField(), converted));
        converted.put(field, zonedField);
        return zonedField;
    }

    //-----------------------------------------------------------------------
    /**
     * A zoned chronology is only equal to a zoned chronology with the
     * same base chronology and zone.
     *
     * @param obj  the object to compare to
     * @return true if equal
     * @since 1.4
     */
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj instanceof ZonedChronology == false) {
            return false;
        }
        ZonedChronology chrono = (ZonedChronology) obj;
        return
            getBase().equals(chrono.getBase()) &&
            getZone().equals(chrono.getZone());
    }

    /**
     * A suitable hashcode for the chronology.
     *
     * @return the hashcode
     * @since 1.4
     */
    public int hashCode() {
        return 326565 + getZone().hashCode() * 11 + getBase().hashCode() * 7;
    }

    /**
     * A debugging string for the chronology.
     *
     * @return the debugging string
     */
    public String toString() {
        return "ZonedChronology[" + getBase() + ", " + getZone().getID() + ']';
    }

    //-----------------------------------------------------------------------
    /*
     * Because time durations are typically smaller than time zone offsets, the
     * arithmetic methods subtract the original offset. This produces a more
     * expected behavior when crossing time zone offset transitions. For dates,
     * the new offset is subtracted off. This behavior, if applied to time
     * fields, can nullify or reverse an add when crossing a transition.
     */
    static class ZonedDurationField extends BaseDurationField {
        private static final long serialVersionUID = -485345310999208286L;

        final DurationField iField;
        final boolean iTimeField;
        final DateTimeZone iZone;

        ZonedDurationField(DurationField field, DateTimeZone zone) {
            super(field.getType());
            if (!field.isSupported()) {
                throw new IllegalArgumentException();
            }
            iField = field;
            iTimeField = useTimeArithmetic(field);
            iZone = zone;
        }

        public boolean isPrecise() {
            return iTimeField ? iField.isPrecise() : iField.isPrecise() && this.iZone.isFixed();
        }

        public long getUnitMillis() {
            return iField.getUnitMillis();
        }

        public int getValue(long duration, long instant) {
            return iField.getValue(duration, addOffset(instant));
        }

        public long getValueAsLong(long duration, long instant) {
            return iField.getValueAsLong(duration, addOffset(instant));
        }

        public long getMillis(int value, long instant) {
            return iField.getMillis(value, addOffset(instant));
        }

        public long getMillis(long value, long instant) {
            return iField.getMillis(value, addOffset(instant));
        }

        public long add(long instant, int value) {
            int offset = getOffsetToAdd(instant);
            instant = iField.add(instant + offset, value);
            return instant - (iTimeField ? offset : getOffsetFromLocalToSubtract(instant));
        }

        public long add(long instant, long value) {
            int offset = getOffsetToAdd(instant);
            instant = iField.add(instant + offset, value);
            return instant - (iTimeField ? offset : getOffsetFromLocalToSubtract(instant));
        }

        public int getDifference(long minuendInstant, long subtrahendInstant) {
            int offset = getOffsetToAdd(subtrahendInstant);
            return iField.getDifference
                (minuendInstant + (iTimeField ? offset : getOffsetToAdd(minuendInstant)),
                 subtrahendInstant + offset);
        }

        public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) {
            int offset = getOffsetToAdd(subtrahendInstant);
            return iField.getDifferenceAsLong
                (minuendInstant + (iTimeField ? offset : getOffsetToAdd(minuendInstant)),
                 subtrahendInstant + offset);
        }

        private int getOffsetToAdd(long instant) {
            int offset = this.iZone.getOffset(instant);
            long sum = instant + offset;
            // If there is a sign change, but the two values have the same sign...
            if ((instant ^ sum) < 0 && (instant ^ offset) >= 0) {
                throw new ArithmeticException("Adding time zone offset caused overflow");
            }
            return offset;
        }

        private int getOffsetFromLocalToSubtract(long instant) {
            int offset = this.iZone.getOffsetFromLocal(instant);
            long diff = instant - offset;
            // If there is a sign change, but the two values have different signs...
            if ((instant ^ diff) < 0 && (instant ^ offset) < 0) {
                throw new ArithmeticException("Subtracting time zone offset caused overflow");
            }
            return offset;
        }

        private long addOffset(long instant) {
            return iZone.convertUTCToLocal(instant);
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj) {
                return true;
            } else if (obj instanceof ZonedDurationField) {
                ZonedDurationField other = (ZonedDurationField) obj;
                return iField.equals(other.iField) &&
                       iZone.equals(other.iZone);
            }
            return false;
        }

        @Override
        public int hashCode() {
            return iField.hashCode() ^ iZone.hashCode();
        }
    }

    /**
     * A DateTimeField that decorates another to add timezone behaviour.
     *

     * This class converts passed in instants to local wall time, and vice
     * versa on output.
     */
    static final class ZonedDateTimeField extends BaseDateTimeField {
        @SuppressWarnings("unused")
        private static final long serialVersionUID = -3968986277775529794L;

        final DateTimeField iField;
        final DateTimeZone iZone;
        final DurationField iDurationField;
        final boolean iTimeField;
        final DurationField iRangeDurationField;
        final DurationField iLeapDurationField;

        ZonedDateTimeField(DateTimeField field,
                           DateTimeZone zone,
                           DurationField durationField,
                           DurationField rangeDurationField,
                           DurationField leapDurationField) {
            super(field.getType());
            if (!field.isSupported()) {
                throw new IllegalArgumentException();
            }
            iField = field;
            iZone = zone;
            iDurationField = durationField;
            iTimeField = useTimeArithmetic(durationField);
            iRangeDurationField = rangeDurationField;
            iLeapDurationField = leapDurationField;
        }

        public boolean isLenient() {
            return iField.isLenient();
        }

        public int get(long instant) {
            long localInstant = iZone.convertUTCToLocal(instant);
            return iField.get(localInstant);
        }

        public String getAsText(long instant, Locale locale) {
            long localInstant = iZone.convertUTCToLocal(instant);
            return iField.getAsText(localInstant, locale);
        }

        public String getAsShortText(long instant, Locale locale) {
            long localInstant = iZone.convertUTCToLocal(instant);
            return iField.getAsShortText(localInstant, locale);
        }

        public String getAsText(int fieldValue, Locale locale) {
            return iField.getAsText(fieldValue, locale);
        }

        public String getAsShortText(int fieldValue, Locale locale) {
            return iField.getAsShortText(fieldValue, locale);
        }

        public long add(long instant, int value) {
            if (iTimeField) {
                int offset = getOffsetToAdd(instant);
                long localInstant = iField.add(instant + offset, value);
                return localInstant - offset;
            } else {
               long localInstant = iZone.convertUTCToLocal(instant);
               localInstant = iField.add(localInstant, value);
               return iZone.convertLocalToUTC(localInstant, false, instant);
            }
        }

        public long add(long instant, long value) {
            if (iTimeField) {
                int offset = getOffsetToAdd(instant);
                long localInstant = iField.add(instant + offset, value);
                return localInstant - offset;
            } else {
               long localInstant = iZone.convertUTCToLocal(instant);
               localInstant = iField.add(localInstant, value);
               return iZone.convertLocalToUTC(localInstant, false, instant);
            }
        }

        public long addWrapField(long instant, int value) {
            if (iTimeField) {
                int offset = getOffsetToAdd(instant);
                long localInstant = iField.addWrapField(instant + offset, value);
                return localInstant - offset;
            } else {
                long localInstant = iZone.convertUTCToLocal(instant);
                localInstant = iField.addWrapField(localInstant, value);
                return iZone.convertLocalToUTC(localInstant, false, instant);
            }
        }

        public long set(long instant, int value) {
            long localInstant = iZone.convertUTCToLocal(instant);
            localInstant = iField.set(localInstant, value);
            long result = iZone.convertLocalToUTC(localInstant, false, instant);
            if (get(result) != value) {
                IllegalInstantException cause = new IllegalInstantException(localInstant,  iZone.getID());
                IllegalFieldValueException ex = new IllegalFieldValueException(iField.getType(), Integer.valueOf(value), cause.getMessage());
                ex.initCause(cause);
                throw ex;
            }
            return result;
        }

        public long set(long instant, String text, Locale locale) {
            // cannot verify that new value stuck because set may be lenient
            long localInstant = iZone.convertUTCToLocal(instant);
            localInstant = iField.set(localInstant, text, locale);
            return iZone.convertLocalToUTC(localInstant, false, instant);
        }

        public int getDifference(long minuendInstant, long subtrahendInstant) {
            int offset = getOffsetToAdd(subtrahendInstant);
            return iField.getDifference
                (minuendInstant + (iTimeField ? offset : getOffsetToAdd(minuendInstant)),
                 subtrahendInstant + offset);
        }

        public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) {
            int offset = getOffsetToAdd(subtrahendInstant);
            return iField.getDifferenceAsLong
                (minuendInstant + (iTimeField ? offset : getOffsetToAdd(minuendInstant)),
                 subtrahendInstant + offset);
        }

        public final DurationField getDurationField() {
            return iDurationField;
        }

        public final DurationField getRangeDurationField() {
            return iRangeDurationField;
        }

        public boolean isLeap(long instant) {
            long localInstant = iZone.convertUTCToLocal(instant);
            return iField.isLeap(localInstant);
        }

        public int getLeapAmount(long instant) {
            long localInstant = iZone.convertUTCToLocal(instant);
            return iField.getLeapAmount(localInstant);
        }

        public final DurationField getLeapDurationField() {
            return iLeapDurationField;
        }

        public long roundFloor(long instant) {
            if (iTimeField) {
                int offset = getOffsetToAdd(instant);
                instant = iField.roundFloor(instant + offset);
                return instant - offset;
            } else {
                long localInstant = iZone.convertUTCToLocal(instant);
                localInstant = iField.roundFloor(localInstant);
                return iZone.convertLocalToUTC(localInstant, false, instant);
            }
        }

        public long roundCeiling(long instant) {
            if (iTimeField) {
                int offset = getOffsetToAdd(instant);
                instant = iField.roundCeiling(instant + offset);
                return instant - offset;
            } else {
                long localInstant = iZone.convertUTCToLocal(instant);
                localInstant = iField.roundCeiling(localInstant);
                return iZone.convertLocalToUTC(localInstant, false, instant);
            }
        }

        public long remainder(long instant) {
            long localInstant = iZone.convertUTCToLocal(instant);
            return iField.remainder(localInstant);
        }

        public int getMinimumValue() {
            return iField.getMinimumValue();
        }

        public int getMinimumValue(long instant) {
            long localInstant = iZone.convertUTCToLocal(instant);
            return iField.getMinimumValue(localInstant);
        }

        public int getMinimumValue(ReadablePartial instant) {
            return iField.getMinimumValue(instant);
        }

        public int getMinimumValue(ReadablePartial instant, int[] values) {
            return iField.getMinimumValue(instant, values);
        }

        public int getMaximumValue() {
            return iField.getMaximumValue();
        }

        public int getMaximumValue(long instant) {
            long localInstant = iZone.convertUTCToLocal(instant);
            return iField.getMaximumValue(localInstant);
        }

        public int getMaximumValue(ReadablePartial instant) {
            return iField.getMaximumValue(instant);
        }

        public int getMaximumValue(ReadablePartial instant, int[] values) {
            return iField.getMaximumValue(instant, values);
        }

        public int getMaximumTextLength(Locale locale) {
            return iField.getMaximumTextLength(locale);
        }

        public int getMaximumShortTextLength(Locale locale) {
            return iField.getMaximumShortTextLength(locale);
        }

        private int getOffsetToAdd(long instant) {
            int offset = this.iZone.getOffset(instant);
            long sum = instant + offset;
            // If there is a sign change, but the two values have the same sign...
            if ((instant ^ sum) < 0 && (instant ^ offset) >= 0) {
                throw new ArithmeticException("Adding time zone offset caused overflow");
            }
            return offset;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj) {
                return true;
            } else if (obj instanceof ZonedDateTimeField) {
                ZonedDateTimeField other = (ZonedDateTimeField) obj;
                return iField.equals(other.iField) &&
                       iZone.equals(other.iZone) &&
                       iDurationField.equals(other.iDurationField) &&
                       iRangeDurationField.equals(other.iRangeDurationField);
            }
            return false;
        }

        @Override
        public int hashCode() {
            return iField.hashCode() ^ iZone.hashCode();
        }
    }

}


text:
from django.conf.urls import url
from .views import RegisterUser

urlpatterns = [
    url(r'^usuario/', RegisterUser.as_view(), name='register'),
]


text:
<link rel="import" href="../polymer/polymer.html">

<!--
console-log logs to the browser console.

@element console-log
@blurb element which logs to the console
@status beta
@homepage https://nhnb.github.io/console-log/
@demo https://nhnb.github.io/console-log/console-log/demo.html
-->
<dom-module id="console-log" attributes="log info warn error">

	<template>
		<style>
			::host {
			display: none
		}
		</style>
	</template>
</dom-module>

<script>
	"use strict";
	Polymer({
		is: "console-log",

		properties: {

			/**
			 * Setting the `error` attribute will log an error message to the console.
			 *
			 * @attribute error
			 * @type string
			 */
			error: {
				type: String,
				observer: '_errorChanged'
			},

			/**
			 * Setting the `info` attribute will log an info message to the console.
			 *
			 * @attribute info
			 * @type string
			 */
			info: {
				type: String,
				observer: '_infoChanged'
			},

			/**
			 * Setting the `log` attribute will log a message to the console.
			 *
			 * @attribute log
			 * @type string
			 */
			log: {
				type: String,
				observer: '_logChanged'
			},

			/**
			 * Setting the `warn` attribute will log a warn message to the console.
			 *
			 * @attribute warn
			 * @type string
			 */
			warn: {
				type: String,
				observer: '_warnChanged'
			}
		},

		_errorChanged: function(newValue, oldValue) {
			if (console && console.error) {
				console.error(newValue);
			}
		},

		_infoChanged: function(newValue, oldValue) {
			if (console && console.info) {
				console.info(newValue);
			}
		},

		_logChanged: function(newValue, oldValue) {
			if (console && console.log) {
				console.log(newValue);
			}
		},

		_warnChanged: function(newValue, oldValue) {
			if (console && console.log) {
				console.warn(newValue);
			}
		},
	});
</script>


text:
/* compiled code */
F_HEAP code_heap;

void init_code_heap(CELL size);

bool in_code_heap_p(CELL ptr);

void default_word_code(F_WORD *word, bool relocate);

void set_word_code(F_WORD *word, F_CODE_BLOCK *compiled);

typedef void (*CODE_HEAP_ITERATOR)(F_CODE_BLOCK *compiled);

void iterate_code_heap(CODE_HEAP_ITERATOR iter);

void copy_code_heap_roots(void);

void update_code_heap_roots(void);

void primitive_modify_code_heap(void);

void primitive_code_room(void);

void compact_code_heap(void);


text:
require 'nhk_program/api'
require 'nhk_program/configuration'
require 'nhk_program/connection'
require 'nhk_program/helper'
require 'nhk_program/request'

module NHKProgram
  # Wrapper for the NHK Program REST API
  #
  # @see http://api-portal.nhk.or.jp/ja
  class Client
    include Connection
    include Request
    include API
    include Helper

    # @private
    attr_accessor *Configuration::VALID_OPTIONS_KEYS

    def initialize(options = {})
      options = NHKProgram.options.merge(options)
      Configuration::VALID_OPTIONS_KEYS.each do |key|
        send("#{key}=", options[key])
      end
    end
  end
end


text:
package club.broking.cdn.servlets.shopping.cart;

import club.broking.cdn.models.Product;
import club.broking.cdn.models.ProductAccessor;
import club.broking.cdn.services.CassandraService;
import club.broking.cdn.services.TokenService;
import club.broking.cdn.servlets.AbstractJsonServlet;
import com.datastax.driver.core.*;
import com.datastax.driver.mapping.MappingManager;
import com.datastax.driver.mapping.Result;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

public class ShoppingCartServlet extends AbstractJsonServlet<ShoppingCartRequest, ShoppingCartResponse> {

    private final Session session;
    private final ProductAccessor productAccessor;
    private final TokenService tokenService;

    public ShoppingCartServlet() {
        super(ShoppingCartRequest.class, ShoppingCartResponse.class);

        CassandraService cassandraService = CassandraService.getInstance();
        MappingManager mappingManager = cassandraService.getMappingManager();
        this.session = cassandraService.getSession();
        this.productAccessor = mappingManager.createAccessor(ProductAccessor.class);
        this.tokenService = TokenService.getInstance();
    }

    @Override
    protected void doPost(ShoppingCartRequest request, ShoppingCartResponse response) {
        Map<String, Object> claims = this.tokenService.verify(request.token);

        if(claims == null) {
            return;
        }

        UUID userId = UUID.fromString((String)claims.get("id"));
        ResultSet result = this.session.execute("SELECT id, user_id, product_id FROM shop.shopping_cart;");
        Set<ShoppingCartProduct> products = new HashSet<ShoppingCartProduct>();

        for(Row row:result) {
            if(!row.getUUID("user_id").equals(userId)) {
                continue;
            }

            UUID id = row.getUUID("id");
            UUID productId = row.getUUID("product_id");
            Product product = this.findById(productId);

            if(product == null) {
                return;
            }

            ShoppingCartProduct shoppingCartProduct = new ShoppingCartProduct();
            shoppingCartProduct.id = id.toString();
            shoppingCartProduct.product = product;

            products.add(shoppingCartProduct);
        }

        response.shoppingCartProducts = products.toArray(new ShoppingCartProduct[products.size()]);
    }

    private Product findById(UUID id) {
        Result<Product> Products = this.productAccessor.all();

        for(Product product:Products) {
            if(product.getId().equals(id)) {
                return product;
            }
        }

        return null;
    }

}


text:
package analyzers;

import jsystem.framework.analyzer.AnalyzerParameterImpl;

/**
 * analyze the expected string to verify if it equals to the string found
 * in the test
 * if a TestOption.UnEqual is chosen with ignoreCase = true, then a different
 * String(different chars in the String) are matched.
 * if a TestOption.UnEqual is chosen with ignoreCase = true, then every kind of difference will
 * be matched including case difference.
 * @author Chen n.
 */

public class StringCompareAnalyzer extends AnalyzerParameterImpl{

	private String testString;
	private String expectedString;
	private TestOption option;
	private boolean ignoreCase;

	public static enum TestOption{
		Equals,
		UnEqual,
		Contains,
		startsWith,
		endsWith;
	}

	/**
	 * the default behavior is to test for equals, and ignore case
	 * @param testString
	 */
	public StringCompareAnalyzer(String testString) {
		this(testString, TestOption.Equals);
	}

	/**
	 * takes a String for comparison as test subject and what kind of
	 * comparison you want.
	 * use the StringCompareAnalyzer.TestOption.<type> to pass the option argument.
	 * the direction is always from testAgainst object to testString i.e:
	 * Contains means you want to test if the testAgainst String contains the testString.
	 * will ignore case by default
	 * @param testString
	 * @param option
	 */
	public StringCompareAnalyzer(String testString, TestOption option){
		this(testString, option, true);
	}

	/**
	 * takes a String for comparison as test subject and what kind of
	 * comparison you want.
	 * use the StringCompareAnalyzer.TestOption.<type> to pass the option argument.
	 * the direction is always from testAgainst object to testString i.e:
	 * Contains means you want to test if the testAgainst String contains the testString.
	 * if ignoreCase is true, the match will ignore case(be case insensitive)
	 * if ignore case is false, the match will be exact.
	 * @param testString
	 * @param option
	 * @param ignoreCase
	 */
	public StringCompareAnalyzer(String testString, TestOption option, boolean ignoreCase){
		this.testString = testString;
		this.option = option;
		this.ignoreCase = ignoreCase;
	}

	public void analyze() {
		expectedString = testAgainst.toString().trim();
		switch(option)
		{
			case Equals:
			{
				if(ignoreCase){
					if (!testString.equalsIgnoreCase(expectedString)){
						status = false;
						title = "test String: \""+   testString+ "\" isn't as expected String \"" +expectedString +"\"";
						return;

					}else {
						status = true;
						title = "test String: \""+ testString+ "\" is as expected String \"" + expectedString +"\"";
						return;

					}
				}
				else{
					if (!testString.equals(expectedString)){
						status = false;
						title = "test String: \""+   testString+ "\" isn't as expected String \"" +expectedString +"\"";
						return;

					}else {
						status = true;
						title = "test String: \""+ testString+ "\" is as expected String \"" + expectedString +"\"";
						return;

					}
				}
			}
			case UnEqual:
			{
				if(ignoreCase){
					if(!testString.equalsIgnoreCase(expectedString)){
						status = true;
						title = "test string: \""+   testString+ "\" is not equal to expected String \"" +expectedString +"\"";
						return;
					}
					else{
						status = false;
						title = "test string: \""+   testString+ "\" is equal to expected String \"" +expectedString +"\"";
						return;
					}
				}
				else{
					if(!testString.equals(expectedString)){
						status = true;
						title = "test string: \""+   testString+ "\" is not equal to expected String \"" +expectedString +"\"";
						return;
					}
					else{
						status = false;
						title = "test string: \""+   testString+ "\" is equal to expected String \"" +expectedString +"\"";
						return;
					}
				}
			}
			case Contains:
			{
				if(ignoreCase){
					if(expectedString.toLowerCase().contains(testString.toLowerCase())){
						status = true;
						title = "the testAgainst string \"" + expectedString +"\" contains the testString "+ testString;
						return;
					}
					else{
						status = false;
						title = "the testAgainst string \"" + expectedString +"\"does not contain the testString "+ testString;
						return;
					}
				}
				else{
					if(expectedString.contains(testString)){
						status = true;
						title = "the testAgains string \"" + expectedString +"\" contains the testString "+ testString;
						return;
					}
					else{
						status = false;
						title = "the testAgains string \"" + expectedString +"\"does not contain the testString "+ testString;
						return;
					}
				}
			}
			case startsWith:
			{
				if(ignoreCase){
					if(expectedString.toLowerCase().startsWith(testString.toLowerCase())){
						status = true;
						title = "the testAgains string \"" + expectedString +"\" starts with the testString "+ testString;
						return;
					}
					else{
						status = true;
						title = "the testAgains string \"" + expectedString +"\" does not start with the testString "+ testString;
						return;
					}
				}
				else{
					if(expectedString.startsWith(testString)){
						status = true;
						title = "the testAgains string \"" + expectedString +"\" starts with the testString "+ testString;
						return;
					}
					else{
						status = true;
						title = "the testAgains string \"" + expectedString +"\" does not start with the testString "+ testString;
						return;
					}
				}
			}
			case endsWith:
			{
				if(ignoreCase){
					if(expectedString.toLowerCase().endsWith(testString.toLowerCase())){
						status = true;
						title = "the testAgains string \"" + expectedString +"\" ends with the testString "+ testString;
						return;
					}
					else{
						status = true;
						title = "the testAgains string \"" + expectedString +"\" does not end with the testString "+ testString;
						return;
					}
				}
				else{
					if(expectedString.endsWith(testString)){
						status = true;
						title = "the testAgains string \"" + expectedString +"\" ends with the testString "+ testString;
						return;
					}
					else{
						status = true;
						title = "the testAgains string \"" + expectedString +"\" does not end with the testString "+ testString;
						return;
					}
				}
			}
		}
	}
}


text:
/*
 * $Id: SingletonIterator.java 468651 2006-10-28 07:04:25Z minchau $
 */

package org.apache.xalan.xsltc.dom;

import org.apache.xml.dtm.DTMAxisIterator;
import org.apache.xml.dtm.ref.DTMAxisIteratorBase;

/**
 * @author Jacek Ambroziak
 * @author Santiago Pericas-Geertsen
 */
public class SingletonIterator extends DTMAxisIteratorBase {
    private int _node;
    private final boolean _isConstant;

    public SingletonIterator() {
	this(Integer.MIN_VALUE, false);
    }

    public SingletonIterator(int node) {
	this(node, false);
    }

    public SingletonIterator(int node, boolean constant) {
	_node = _startNode = node;
	_isConstant = constant;
    }

    /**
     * Override the value of <tt>_node</tt> only when this
     * object was constructed using the empty constructor.
     */
    public DTMAxisIterator setStartNode(int node) {
	if (_isConstant) {
	    _node = _startNode;
	    return resetPosition();
	}
	else if (_isRestartable) {
	    if (_node <= 0)
		_node = _startNode = node;
	    return resetPosition();
	}
	return this;
    }

    public DTMAxisIterator reset() {
	if (_isConstant) {
	    _node = _startNode;
	    return resetPosition();
	}
	else {
	    final boolean temp = _isRestartable;
	    _isRestartable = true;
	    setStartNode(_startNode);
	    _isRestartable = temp;
	}
	return this;
    }

    public int next() {
	final int result = _node;
	_node = DTMAxisIterator.END;
	return returnNode(result);
    }

    public void setMark() {
	_markedNode = _node;
    }

    public void gotoMark() {
	_node = _markedNode;
    }
}


text:
from home.models import WhatTorrent

def extract(torrent):
    t = type(torrent)
    if t is dict:
        return torrent['media'], torrent['format']
    elif t is WhatTorrent:
        return torrent.info_media, torrent.info_format

# This should be changed when we support FLAC
def filter_torrent(a):
    _, a_format = extract(a)
    if a_format == 'FLAC':
        return True
    return True

def compare_torrents(a, b):
    a_media, a_format = extract(a)
    b_media, b_format = extract(b)
    if a_format == 'MP3' and b_format != 'MP3':
        return -1
    if a_format != 'MP3' and b_format == 'MP3':
        return 1
    if a_media == 'WEB' and b_media != 'WEB':
        return -1
    if a_media != 'WEB' and b_media == 'WEB':
        return 1
    if a_media == 'CD' and b_media != 'CD':
        return -1
    if a_media != 'CD' and b_media == 'CD':
        return 1
    return 0

def sort_filter_torrents(torrents):
    torrents = [t for t in torrents if filter_torrent(t)]
    torrents.sort(cmp=compare_torrents)
    return torrents


text:
doubleIn
=====

Usage: ```doubleIn([options])```

Specs a 64-bit floating point number.

Options:

- isInfinite
- isNaN
- min
- max

[Source](https://github.com/mrijk/speculaas/blob/master/lib/doubleIn.js)

Example:

```js
const s = require('speculaas');
const {isBoolean, isString} = s.utils;

s.def('::percentage', s.doubleIn({min: 0.0, max: 100.0}));

s.isValid('::percentage', 50.1);
// true

s.isValid('::percentage', 101.0);
// false
```


text:
package es.pcv.core.updater.elements;

import java.awt.geom.Rectangle2D;

import es.pcv.core.render.Point2D;
import es.pcv.core.render.auxiliar.PolygonHelper;
import es.pcv.core.updater.elements.Collisionable;

public abstract class PolygonObstacle extends PolygonCollision {

	public PolygonObstacle(Rectangle2D ply) {
		super(ply);
	}

	/**
	 *
	 * @param p posicion de la esquina superior izquierda
	 * @param s tamaño
	 */
	public PolygonObstacle(Point2D p, Point2D s) {
		super(PolygonHelper.createRectangle(p,s).getBounds2D());
	}

	public void collision(Collisionable c){
		c.collisionObstacle(this);
	}
}


text:
using UnityEngine;
using System.Collections;
using SLua;
using System.IO;

public class test_run_first_main : MonoBehaviour {

	// 需要实现一个framework,有自动下载的功能。

	// lua打为一个整包?
	// 暂时先不要自动下载及其它等功能。

	// Use this for initialization
	// lua service只有一个,那加载的lua呢,按一个写呢,还是按多个写呢,应该尽量只按一个写。
	LuaSvr luaService=null;
	LuaTable mainLua=null;
	LuaFunction mainUpdateFunction=null;
	void Start () {
		LuaState.loaderDelegate=new LuaState.LoaderDelegate(LoaderDelegate);
		luaService=new LuaSvr();
		mainLua=(LuaTable)luaService.start("Lua_src/test_run_first.lua");

		mainUpdateFunction=(LuaFunction)mainLua["update"];
	}

	// Update is called once per frame
	void Update () {
		if(mainUpdateFunction!=null){
			mainUpdateFunction.call ();
		}
	}

	void Destroy(){

	}

	public byte[] LoaderDelegate(string fn){
		// 暂时先只用File读取
		string filePath = System.IO.Path.Combine(Application.dataPath, fn);
		return File.ReadAllBytes(filePath);
	}
}


text:
<?php

use backend\assets\AppAsset;
use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model backend\models\GuestBook */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(); ?>
    <?= $form->field($model, 'on_off')->checkbox() ?>
    <?= $form->field($model, 'email')->textInput(['maxlength' => true]) ?>

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

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

    <?= $form->field($model, 'content')->textarea(['rows' => 6]) ?>

    <?= $form->field($model, 'created_at')->textInput() ?>

        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

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

<?php  $this->registerJsFile('/admin/js/_guest-book.js',['depends' => AppAsset::className()]); ?>


text:
node[:deploy].each do |app_name, deploy_config|
  release_path = ::File.join(deploy_config[:deploy_to], 'current')
  rails_env = deploy_config[:rails_env]

  execute 'clear application cache' do
    cwd release_path
    command 'bundle exec rake memcache:flush'
    environment 'RAILS_ENV' => rails_env
  end
end


text:
import utils
import sqlite3
from PyQt4.QtGui import *
from query_result_window import QueryResultWindow

class QueryWindow:
	def __init__(self):
		self.__create_window_widget()
		self.__create_ui()

	def __create_window_widget(self):
		self.__qt_widget_object = QWidget()
		self.__qt_widget_object.resize(600, 400)
		self.__qt_widget_object.setWindowTitle('Выполнение произвольного запроса')

	def __create_ui(self):
		query_text = QPlainTextEdit('\n'.join([
			'SELECT *',
			'FROM users',
		]))
		execute_button = QPushButton('Запуск запроса...')

		layout = QVBoxLayout()
		self.__qt_widget_object.setLayout(layout)

		layout.addWidget(query_text)
		layout.addWidget(execute_button)

		execute_button.clicked.connect(
			lambda: self.on_execute_button_click()
		)

		self.__query_text = query_text

	def show(self):
		self.__qt_widget_object.show()

	def on_query_error(self):
		box = QMessageBox()
		box.setText('Произошла ошибка при выполнении запроса. Проверьте правильность введённого кода')
		box.exec()

	def execute_query(self):
		db_path = utils.find_file('db.sqlite')

		connection = sqlite3.connect(db_path)
		cursor = connection.cursor()

		text = self.__query_text.toPlainText()

		query_result = cursor.execute(text)

		columns = [
			column[0]
			for column in cursor.description
		]

		rows = [
			row
			for row in query_result
		]

		connection.close()

		return columns, rows

	def on_execute_button_click(self):
		try:
			columns, rows = self.execute_query()

			self.__current_query_result_window = QueryResultWindow()
			self.__current_query_result_window.show()

			self.__current_query_result_window.set_column_names(columns)
			self.__current_query_result_window.set_data(rows)
		except sqlite3.Error:
			self.on_query_error()


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/cloud/compute/v1/compute.proto

namespace Google\Cloud\Compute\V1;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * Time window specified for daily operations.
 *
 * Generated from protobuf message google.cloud.compute.v1.ResourcePolicyDailyCycle
 */
class ResourcePolicyDailyCycle extends \Google\Protobuf\Internal\Message
{
    /**
     * Defines a schedule with units measured in days. The value determines how many days pass between the start of each cycle.
     *
     * Generated from protobuf field optional int32 days_in_cycle = 369790004;
     */
    private $days_in_cycle = null;
    /**
     * [Output only] A predetermined duration for the window, automatically chosen to be the smallest possible in the given scenario.
     *
     * Generated from protobuf field optional string duration = 155471252;
     */
    private $duration = null;
    /**
     * Start time of the window. This must be in UTC format that resolves to one of 00:00, 04:00, 08:00, 12:00, 16:00, or 20:00. For example, both 13:00-5 and 08:00 are valid.
     *
     * Generated from protobuf field optional string start_time = 37467274;
     */
    private $start_time = null;

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type int $days_in_cycle
     *           Defines a schedule with units measured in days. The value determines how many days pass between the start of each cycle.
     *     @type string $duration
     *           [Output only] A predetermined duration for the window, automatically chosen to be the smallest possible in the given scenario.
     *     @type string $start_time
     *           Start time of the window. This must be in UTC format that resolves to one of 00:00, 04:00, 08:00, 12:00, 16:00, or 20:00. For example, both 13:00-5 and 08:00 are valid.
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Cloud\Compute\V1\Compute::initOnce();
        parent::__construct($data);
    }

    /**
     * Defines a schedule with units measured in days. The value determines how many days pass between the start of each cycle.
     *
     * Generated from protobuf field optional int32 days_in_cycle = 369790004;
     * @return int
     */
    public function getDaysInCycle()
    {
        return isset($this->days_in_cycle) ? $this->days_in_cycle : 0;
    }

    public function hasDaysInCycle()
    {
        return isset($this->days_in_cycle);
    }

    public function clearDaysInCycle()
    {
        unset($this->days_in_cycle);
    }

    /**
     * Defines a schedule with units measured in days. The value determines how many days pass between the start of each cycle.
     *
     * Generated from protobuf field optional int32 days_in_cycle = 369790004;
     * @param int $var
     * @return $this
     */
    public function setDaysInCycle($var)
    {
        GPBUtil::checkInt32($var);
        $this->days_in_cycle = $var;

        return $this;
    }

    /**
     * [Output only] A predetermined duration for the window, automatically chosen to be the smallest possible in the given scenario.
     *
     * Generated from protobuf field optional string duration = 155471252;
     * @return string
     */
    public function getDuration()
    {
        return isset($this->duration) ? $this->duration : '';
    }

    public function hasDuration()
    {
        return isset($this->duration);
    }

    public function clearDuration()
    {
        unset($this->duration);
    }

    /**
     * [Output only] A predetermined duration for the window, automatically chosen to be the smallest possible in the given scenario.
     *
     * Generated from protobuf field optional string duration = 155471252;
     * @param string $var
     * @return $this
     */
    public function setDuration($var)
    {
        GPBUtil::checkString($var, True);
        $this->duration = $var;

        return $this;
    }

    /**
     * Start time of the window. This must be in UTC format that resolves to one of 00:00, 04:00, 08:00, 12:00, 16:00, or 20:00. For example, both 13:00-5 and 08:00 are valid.
     *
     * Generated from protobuf field optional string start_time = 37467274;
     * @return string
     */
    public function getStartTime()
    {
        return isset($this->start_time) ? $this->start_time : '';
    }

    public function hasStartTime()
    {
        return isset($this->start_time);
    }

    public function clearStartTime()
    {
        unset($this->start_time);
    }

    /**
     * Start time of the window. This must be in UTC format that resolves to one of 00:00, 04:00, 08:00, 12:00, 16:00, or 20:00. For example, both 13:00-5 and 08:00 are valid.
     *
     * Generated from protobuf field optional string start_time = 37467274;
     * @param string $var
     * @return $this
     */
    public function setStartTime($var)
    {
        GPBUtil::checkString($var, True);
        $this->start_time = $var;

        return $this;
    }

}


text:
/**
 * This is a very simple queue test.  See the BlockQ. c documentation for a more
 * comprehensive version.
 *
 * Creates two tasks that communicate over a single queue.  One task acts as a
 * producer, the other a consumer.
 *
 * The producer loops for three iteration, posting an incrementing number onto the
 * queue each cycle.  It then delays for a fixed period before doing exactly the
 * same again.
 *
 * The consumer loops emptying the queue.  Each item removed from the queue is
 * checked to ensure it contains the expected value.  When the queue is empty it
 * blocks for a fixed period, then does the same again.
 *
 * All queue access is performed without blocking.  The consumer completely empties
 * the queue each time it runs so the producer should never find the queue full.
 *
 * An error is flagged if the consumer obtains an unexpected value or the producer
 * find the queue is full.
 *
 * \page PollQC pollQ.c
 * \ingroup DemoFiles
 * <HR>
 */

/*
Changes from V2.0.0

	+ Delay periods are now specified using variables and constants of
	  TickType_t rather than unsigned long.
*/

#include <stdlib.h>

/* Scheduler include files. */
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "print.h"

/* Demo program include files. */
#include "PollQ.h"

#define pollqSTACK_SIZE		( ( unsigned short ) configMINIMAL_STACK_SIZE )

/* The task that posts the incrementing number onto the queue. */
static void vPolledQueueProducer( void *pvParameters );

/* The task that empties the queue. */
static void vPolledQueueConsumer( void *pvParameters );

/* Variables that are used to check that the tasks are still running with no errors. */
static volatile short sPollingConsumerCount = 0, sPollingProducerCount = 0;
/*-----------------------------------------------------------*/

void vStartPolledQueueTasks( unsigned portBASE_TYPE uxPriority )
{
static QueueHandle_t xPolledQueue;
const unsigned portBASE_TYPE uxQueueSize = 10;

	/* Create the queue used by the producer and consumer. */
	xPolledQueue = xQueueCreate( uxQueueSize, ( unsigned portBASE_TYPE ) sizeof( unsigned short ) );

	/* Spawn the producer and consumer. */
	xTaskCreate( vPolledQueueConsumer, "QConsNB", pollqSTACK_SIZE, ( void * ) &xPolledQueue, uxPriority, NULL );
	xTaskCreate( vPolledQueueProducer, "QProdNB", pollqSTACK_SIZE, ( void * ) &xPolledQueue, uxPriority, NULL );
}
/*-----------------------------------------------------------*/

static void vPolledQueueProducer( void *pvParameters )
{
unsigned short usValue = 0, usLoop;
QueueHandle_t *pxQueue;
const TickType_t xDelay = ( TickType_t ) 200 / portTICK_PERIOD_MS;
const unsigned short usNumToProduce = 3;
const char * const pcTaskStartMsg = "Polled queue producer started.\r\n";
const char * const pcTaskErrorMsg = "Could not post on polled queue.\r\n";
short sError = pdFALSE;

	/* Queue a message for printing to say the task has started. */
	vPrintDisplayMessage( &pcTaskStartMsg );

	/* The queue being used is passed in as the parameter. */
	pxQueue = ( QueueHandle_t * ) pvParameters;

	for( ;; )
	{
		for( usLoop = 0; usLoop < usNumToProduce; ++usLoop )
		{
			/* Send an incrementing number on the queue without blocking. */
			if( xQueueSendToBack( *pxQueue, ( void * ) &usValue, ( TickType_t ) 0 ) != pdPASS )
			{
				/* We should never find the queue full - this is an error. */
				vPrintDisplayMessage( &pcTaskErrorMsg );
				sError = pdTRUE;
			}
			else
			{
				if( sError == pdFALSE )
				{
					/* If an error has ever been recorded we stop incrementing the
					check variable. */
					++sPollingProducerCount;
				}

				/* Update the value we are going to post next time around. */
				++usValue;
			}
		}

		/* Wait before we start posting again to ensure the consumer runs and
		empties the queue. */
		vTaskDelay( xDelay );
	}
}
/*-----------------------------------------------------------*/

static void vPolledQueueConsumer( void *pvParameters )
{
unsigned short usData, usExpectedValue = 0;
QueueHandle_t *pxQueue;
const TickType_t xDelay = ( TickType_t ) 200 / portTICK_PERIOD_MS;
const char * const pcTaskStartMsg = "Polled queue consumer started.\r\n";
const char * const pcTaskErrorMsg = "Incorrect value received on polled queue.\r\n";
short sError = pdFALSE;

	/* Queue a message for printing to say the task has started. */
	vPrintDisplayMessage( &pcTaskStartMsg );

	/* The queue being used is passed in as the parameter. */
	pxQueue = ( QueueHandle_t * ) pvParameters;

	for( ;; )
	{
		/* Loop until the queue is empty. */
		while( uxQueueMessagesWaiting( *pxQueue ) )
		{
			if( xQueueReceive( *pxQueue, &usData, ( TickType_t ) 0 ) == pdPASS )
			{
				if( usData != usExpectedValue )
				{
					/* This is not what we expected to receive so an error has
					occurred. */
					vPrintDisplayMessage( &pcTaskErrorMsg );
					sError = pdTRUE;
					/* Catch-up to the value we received so our next expected value
					should again be correct. */
					usExpectedValue = usData;
				}
				else
				{
					if( sError == pdFALSE )
					{
						/* Only increment the check variable if no errors have
						occurred. */
						++sPollingConsumerCount;
					}
				}
				++usExpectedValue;
			}
		}

		/* Now the queue is empty we block, allowing the producer to place more
		items in the queue. */
		vTaskDelay( xDelay );
	}
}
/*-----------------------------------------------------------*/

/* This is called to check that all the created tasks are still running with no errors. */
portBASE_TYPE xArePollingQueuesStillRunning( void )
{
static short sLastPollingConsumerCount = 0, sLastPollingProducerCount = 0;
portBASE_TYPE xReturn;

	if( ( sLastPollingConsumerCount == sPollingConsumerCount ) ||
		( sLastPollingProducerCount == sPollingProducerCount )
	  )
	{
		xReturn = pdFALSE;
	}
	else
	{
		xReturn = pdTRUE;
	}

	sLastPollingConsumerCount = sPollingConsumerCount;
	sLastPollingProducerCount = sPollingProducerCount;

	return xReturn;
}


text:
import {Mesh} from '../core/mesh';

export class SphereMesh extends Mesh {
  constructor(geometry, material, params = {}) {
    const physParams = params.physics;
    const mass = physParams.mass || params.mass;

    super(geometry, material, mass, physParams);

    if (!geometry.boundingSphere) geometry.computeBoundingSphere();
    this._physijs.type = 'sphere';
    this._physijs.radius = geometry.boundingSphere.radius;

    this._physijs.params = {
      friction: physParams.friction,
      restitution: physParams.restitution,
      damping: physParams.damping,
      margin: physParams.margin
    };

    this._physijs.mass = mass;
  }
}


text:
package org.adridadou.ethereum;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

import com.google.common.collect.Lists;
import org.adridadou.ethereum.values.EthAccount;
import org.adridadou.ethereum.values.EthAddress;
import org.adridadou.ethereum.values.EthData;
import org.adridadou.ethereum.values.EthValue;
import org.adridadou.exception.EthereumApiException;
import org.ethereum.core.CallTransaction;
import org.ethereum.core.CallTransaction.Contract;

import static org.adridadou.ethereum.values.EthValue.wei;

/**
 * Created by davidroon on 20.04.16.
 * This code is released under Apache 2 license
 */
public class SmartContract {
    private final EthAddress address;
    private final EthereumBackend ethereum;
    private final Contract contract;
    private final EthereumProxy proxy;
    private final EthAccount account;

    public SmartContract(Contract contract, EthAccount account, EthAddress address, EthereumProxy proxy, EthereumBackend ethereum) {
        this.contract = contract;
        this.account = account;
        this.proxy = proxy;
        this.address = address;
        this.ethereum = ethereum;
    }

    public List<CallTransaction.Function> getFunctions() {
        return Lists.newArrayList(contract.functions);
    }

    public Object[] callConstFunction(String functionName, EthValue value, Object... args) {
        CallTransaction.Function func = contract.getByName(functionName);
        EthData data = EthData.of(func.encode(args));
        return func.decodeResult(ethereum.constantCall(account,address,value,data).data);
    }

    public CompletableFuture<Object[]> callFunction(String functionName, Object... args) {
        return callFunction(wei(0), functionName, args);
    }

    public CompletableFuture<Object[]> callFunction(String functionName, EthValue value, Object... arguments) {
        return callFunction(value, functionName, arguments);
    }

    public CompletableFuture<Object[]> callFunction(EthValue value, String functionName, Object... args) {
        return Optional.ofNullable(contract.getByName(functionName)).map((func) -> {
            EthData functionCallBytes = EthData.of(func.encode(args));
            return proxy.sendTx(value, functionCallBytes, account, address)
                    .thenApply(receipt -> contract.getByName(functionName).decodeResult(receipt.getResult().data));
        }).orElseThrow(() -> new EthereumApiException("function " + functionName + " cannot be found. available:" + getAvailableFunctions()));
    }

    private String getAvailableFunctions() {
        return Arrays.stream(contract.functions)
                .map(c -> c.name)
                .collect(Collectors.toList()).toString();
    }

    public EthAddress getAddress() {
        return address;
    }
}


text:
#ifndef __nxconstantstring_INCLUDE_GNU
#define __nxconstantstring_INCLUDE_GNU

#include "Object.h"

#ifdef __cplusplus
extern "C" {
#endif

@interface NXConstantString: Object
{
  char *c_string;
  unsigned int len;
}

-(const char *) cString;
-(unsigned int) length;

@end

#ifdef __cplusplus
}
#endif

#endif


text:
//
//  StoreEventHandler.cpp
//  GameOfDrones
//
//  Created by JAFARNEJAD Sasan on 6/1/14.
//
//

#include "StoreEventHandler.h"

#if IS_IOS
#include "Cocos2dxStore.h"
#include "helpers.h"
#include "Purchase.h"

#define TAG "StoreEventHandler >>>"

USING_NS_CC;

void StoreEventHandler::onBillingNotSupported() {
    soomla::CCStoreUtils::logDebug(TAG, "BillingNotSupported");
}

void StoreEventHandler::onBillingSupported() {
    soomla::CCStoreUtils::logDebug(TAG, "BillingSupported");
}

void StoreEventHandler::onCurrencyBalanceChanged(soomla::CCVirtualCurrency *virtualCurrency, int balance, int amountAdded) {
    soomla::CCStoreUtils::logDebug(TAG, "CurrencyBalanceChanged");
    CCNotificationCenter::sharedNotificationCenter()->postNotification
    (EVENT_ON_CURRENCY_BALANCE_CHANGED, CCInteger::create(balance));
}

void StoreEventHandler::onGoodBalanceChanged(soomla::CCVirtualGood *virtualGood, int balance, int amountAdded) {
    soomla::CCStoreUtils::logDebug(TAG, "GoodBalanceChanged");
    CCNotificationCenter::sharedNotificationCenter()->postNotification
    (EVENT_ON_GOOD_BALANCE_CHANGED, CCArray::create(virtualGood, CCInteger::create(balance), NULL));
}

void StoreEventHandler::onGoodEquipped(soomla::CCEquippableVG *equippableVG) {
    soomla::CCStoreUtils::logDebug(TAG, "GoodEquipped");
    CCNotificationCenter::sharedNotificationCenter()->postNotification(EVENT_ON_GOOD_EQUIPPED, equippableVG);
}

void StoreEventHandler::onGoodUnEquipped(soomla::CCEquippableVG *equippableVG) {
    soomla::CCStoreUtils::logDebug(TAG, "GoodUnEquipped");
    CCNotificationCenter::sharedNotificationCenter()->postNotification(EVENT_ON_GOOD_UNEQUIPPED, equippableVG);
}

void StoreEventHandler::onGoodUpgrade(soomla::CCVirtualGood *virtualGood, soomla::CCUpgradeVG *upgradeVG) {
    soomla::CCStoreUtils::logDebug(TAG, "GoodUpgrade");
    CCNotificationCenter::sharedNotificationCenter()->postNotification(EVENT_ON_GOOD_UPGRADE, virtualGood);
}

void StoreEventHandler::onItemPurchased(soomla::CCPurchasableVirtualItem *purchasableVirtualItem) {
    soomla::CCStoreUtils::logDebug(TAG, "ItemPurchased");
    log("ItemPurchased");
    Purchase::BuyPassed(purchasableVirtualItem);
}

void StoreEventHandler::onItemPurchaseStarted(soomla::CCPurchasableVirtualItem *purchasableVirtualItem) {
    soomla::CCStoreUtils::logDebug(TAG, "ItemPurchaseStarted");
}

void StoreEventHandler::onMarketPurchaseCancelled(soomla::CCPurchasableVirtualItem *purchasableVirtualItem) {
    soomla::CCStoreUtils::logDebug(TAG, "MarketPurchaseCancelled");
    log("MarketPurchaseCancelled");
    Purchase::BuyFailed(purchasableVirtualItem);
}

void StoreEventHandler::onMarketPurchase(soomla::CCPurchasableVirtualItem *purchasableVirtualItem, cocos2d::__String *token, cocos2d::__String *payload) {
    soomla::CCStoreUtils::logDebug(TAG, "MarketPurchase");
}

void StoreEventHandler::onMarketPurchaseStarted(soomla::CCPurchasableVirtualItem *purchasableVirtualItem) {
    soomla::CCStoreUtils::logDebug(TAG, "MarketPurchaseStarted");
}

void StoreEventHandler::onMarketPurchaseVerification(soomla::CCPurchasableVirtualItem *purchasableVirtualItem) {
    soomla::CCStoreUtils::logDebug(TAG, "MarketPurchaseVerification");
}

void StoreEventHandler::onRestoreTransactionsStarted() {
    soomla::CCStoreUtils::logDebug(TAG, "RestoreTransactionsStarted");
}

void StoreEventHandler::onRestoreTransactionsFinished(bool success) {
    soomla::CCStoreUtils::logDebug(TAG, "RestoreTransactionsFinished");
    Purchase::RestoreFinished(success);
}

void StoreEventHandler::onUnexpectedErrorInStore() {
    soomla::CCStoreUtils::logDebug(TAG, "UnexpectedErrorInStore");
}

void StoreEventHandler::onStoreControllerInitialized() {
    soomla::CCStoreUtils::logDebug(TAG, "StoreContorllerInitialized");
}

void StoreEventHandler::onMarketItemsRefreshed() {
    soomla::CCStoreUtils::logDebug(TAG, "MarketItemsRefreshed");
    cocos2d::__Array * currencyPacks = soomla::CCStoreInfo::sharedStoreInfo()->getVirtualCurrencyPacks();

    Purchase::AvailablePurchaseItems.clear();
    for (unsigned int i = 0; i < currencyPacks->count(); i++) {

        soomla::CCVirtualCurrencyPack *currencyPack = dynamic_cast<soomla::CCVirtualCurrencyPack*>(currencyPacks->objectAtIndex(i));
        currencyPack->retain();
        Purchase::AvailablePurchaseItems.push_back(currencyPack);
        //log(nToString((int)Purchase::AvailablePurchaseItems.size()));

        log(currencyPack->getName()->getCString());
        //Purchase::AvailablePurchaseItems[i]->retain();
        //log(currencyPack->getDescription());
        //log(currencyPack->getCurrencyAmount());
        //log(currencyPack->getCurrencyItemId());
        /*
        soomla::CCPurchaseWithMarket *purchaseWithMarket = dynamic_cast<soomla::CCPurchaseWithMarket *>(currencyPack->getPurchaseType());
        CC_ASSERT(purchaseWithMarket);
        double price = purchaseWithMarket->getMarketItem()->getPrice()->getValue();
        */
    }
    cocos2d::__Array * nonConsumableItems = soomla::CCStoreInfo::sharedStoreInfo()->getNonConsumableItems();
    for (unsigned int i = 0; i < nonConsumableItems->count(); i++) {

        soomla::CCNonConsumableItem *nonConsumableItem = dynamic_cast<soomla::CCNonConsumableItem*>(nonConsumableItems->objectAtIndex(i));
        soomla::CCSoomlaError *soomlaError = NULL;
        if (!soomla::CCStoreInventory::sharedStoreInventory()->nonConsumableItemExists(nonConsumableItem->getItemId()->getCString(), &soomlaError)){
            nonConsumableItem->retain();
            Purchase::AvailablePurchaseItems.push_back(nonConsumableItem);
        } else {
            //simply skip
            log("skip fast regen");
        }
        if (soomlaError) {
            soomla::CCStoreUtils::logException("Store on refresh items non consumable", soomlaError);
            return;
        }

        log(nonConsumableItem->getName()->getCString());
    }

}

#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)

void StoreEventHandler::onMarketRefund(soomla::CCPurchasableVirtualItem *purchasableVirtualItem) {
    soomla::CCStoreUtils::logDebug(TAG, "MarketRefund");
}

void StoreEventHandler::onIabServiceStarted() {
    soomla::CCStoreUtils::logDebug(TAG, "IabServiceStarted");
}

void StoreEventHandler::onIabServiceStopped() {
    soomla::CCStoreUtils::logDebug(TAG, "IabServiceStopped");
}
#endif
#endif