text:
local os    = require "os"
local util  = require "luci.util"
local table = require "table"

local setmetatable, rawget, rawset = setmetatable, rawget, rawset
local require, getmetatable, assert = require, getmetatable, assert
local error, pairs, ipairs = error, pairs, ipairs
local type, tostring, tonumber, unpack = type, tostring, tonumber, unpack

-- The typical workflow for UCI is:  Get a cursor instance from the
-- cursor factory, modify data (via Cursor.add, Cursor.delete, etc.),
-- save the changes to the staging area via Cursor.save and finally
-- Cursor.commit the data to the actual config files.
-- LuCI then needs to Cursor.apply the changes so deamons etc. are
-- reloaded.
module "luci.model.uci"

local ERRSTR = {
	"Invalid command",
	"Invalid argument",
	"Method not found",
	"Entry not found",
	"No data",
	"Permission denied",
	"Timeout",
	"Not supported",
	"Unknown error",
	"Connection failed"
}

local session_id = nil

local function call(cmd, args)
	if type(args) == "table" and session_id then
		args.ubus_rpc_session = session_id
	end
	return util.ubus("uci", cmd, args)
end

function cursor()
	return _M
end

function cursor_state()
	return _M
end

function substate(self)
	return self
end

function get_confdir(self)
	return "/etc/config"
end

function get_savedir(self)
	return "/tmp/.uci"
end

function get_session_id(self)
	return session_id
end

function set_confdir(self, directory)
	return false
end

function set_savedir(self, directory)
	return false
end

function set_session_id(self, id)
	session_id = id
	return true
end

function load(self, config)
	return true
end

function save(self, config)
	return true
end

function unload(self, config)
	return true
end

function changes(self, config)
	local rv = call("changes", { config = config })
	local res = {}

	if type(rv) == "table" and type(rv.changes) == "table" then
		local package, changes
		for package, changes in pairs(rv.changes) do
			res[package] = {}

			local _, change
			for _, change in ipairs(changes) do
				local operation, section, option, value = unpack(change)
				if option and value and operation ~= "add" then
					res[package][section] = res[package][section] or { }

					if operation == "list-add" then
						local v = res[package][section][option]
						if type(v) == "table" then
							v[#v+1] = value or ""
						elseif v ~= nil then
							res[package][section][option] = { v, value }
						else
							res[package][section][option] = { value }
						end
					else
						res[package][section][option] = value or ""
					end
				else
					res[package][section] = res[package][section] or {}
					res[package][section][".type"] = option or ""
				end
			end
		end
	end

	return res
end

function revert(self, config)
	local _, err = call("revert", { config = config })
	return (err == nil), ERRSTR[err]
end

function commit(self, config)
	local _, err = call("commit", { config = config })
	return (err == nil), ERRSTR[err]
end

--[[
function apply(self, configs, command)
	local _, config

	assert(not command, "Apply command not supported anymore")

	if type(configs) == "table" then
		for _, config in ipairs(configs) do
			call("service", "event", {
				type = "config.change",
				data = { package = config }
			})
		end
	end
end
]]

function foreach(self, config, stype, callback)
	if type(callback) == "function" then
		local rv, err = call("get", {
			config = config,
			type   = stype
		})

		if type(rv) == "table" and type(rv.values) == "table" then
			local sections = { }
			local res = false
			local index = 1

			local _, section
			for _, section in pairs(rv.values) do
				section[".index"] = section[".index"] or index
				sections[index] = section
				index = index + 1
			end

			table.sort(sections, function(a, b)
				return a[".index"] < b[".index"]
			end)

			for _, section in ipairs(sections) do
				local continue = callback(section)
				res = true
				if continue == false then
					break
				end
			end
			return res
		else
			return false, ERRSTR[err] or "No data"
		end
	else
		return false, "Invalid argument"
	end
end

local function _get(self, operation, config, section, option)
	if section == nil then
		return nil
	elseif type(option) == "string" and option:byte(1) ~= 46 then
		local rv, err = call(operation, {
			config  = config,
			section = section,
			option  = option
		})

		if type(rv) == "table" then
			return rv.value or nil
		elseif err then
			return false, ERRSTR[err]
		else
			return nil
		end
	elseif option == nil then
		local values = self:get_all(config, section)
		if values then
			return values[".type"], values[".name"]
		else
			return nil
		end
	else
		return false, "Invalid argument"
	end
end

function get(self, ...)
	return _get(self, "get", ...)
end

function get_state(self, ...)
	return _get(self, "state", ...)
end

function get_all(self, config, section)
	local rv, err = call("get", {
		config  = config,
		section = section
	})

	if type(rv) == "table" and type(rv.values) == "table" then
		return rv.values
	elseif err then
		return false, ERRSTR[err]
	else
		return nil
	end
end

function get_bool(self, ...)
	local val = self:get(...)
	return (val == "1" or val == "true" or val == "yes" or val == "on")
end

function get_first(self, config, stype, option, default)
	local rv = default

	self:foreach(config, stype, function(s)
		local val = not option and s[".name"] or s[option]

		if type(default) == "number" then
			val = tonumber(val)
		elseif type(default) == "boolean" then
			val = (val == "1" or val == "true" or
			       val == "yes" or val == "on")
		end

		if val ~= nil then
			rv = val
			return false
		end
	end)

	return rv
end

function get_list(self, config, section, option)
	if config and section and option then
		local val = self:get(config, section, option)
		return (type(val) == "table" and val or { val })
	end
	return { }
end

function section(self, config, stype, name, values)
	local rv, err = call("add", {
		config = config,
		type   = stype,
		name   = name,
		values = values
	})

	if type(rv) == "table" then
		return rv.section
	elseif err then
		return false, ERRSTR[err]
	else
		return nil
	end
end

function add(self, config, stype)
	return self:section(config, stype)
end

function set(self, config, section, option, value)
	if value == nil then
		local sname, err = self:section(config, option, section)
		return (not not sname), err
	else
		local _, err = call("set", {
			config  = config,
			section = section,
			values  = { [option] = value }
		})
		return (err == nil), ERRSTR[err]
	end
end

function set_list(self, config, section, option, value)
	if section == nil or option == nil then
		return false
	elseif value == nil or (type(value) == "table" and #value == 0) then
		return self:delete(config, section, option)
	elseif type(value) == "table" then
		return self:set(config, section, option, value)
	else
		return self:set(config, section, option, { value })
	end
end

function tset(self, config, section, values)
	local _, err = call("set", {
		config  = config,
		section = section,
		values  = values
	})
	return (err == nil), ERRSTR[err]
end

function reorder(self, config, section, index)
	local sections

	if type(section) == "string" and type(index) == "number" then
		local pos = 0

		sections = { }

		self:foreach(config, nil, function(s)
			if pos == index then
				pos = pos + 1
			end

			if s[".name"] ~= section then
				pos = pos + 1
				sections[pos] = s[".name"]
			else
				sections[index + 1] = section
			end
		end)
	elseif type(section) == "table" then
		sections = section
	else
		return false, "Invalid argument"
	end

	local _, err = call("order", {
		config   = config,
		sections = sections
	})

	return (err == nil), ERRSTR[err]
end

function delete(self, config, section, option)
	local _, err = call("delete", {
		config  = config,
		section = section,
		option  = option
	})
	return (err == nil), ERRSTR[err]
end

function delete_all(self, config, stype, comparator)
	local _, err
	if type(comparator) == "table" then
		_, err = call("delete", {
			config = config,
			type   = stype,
			match  = comparator
		})
	elseif type(comparator) == "function" then
		local rv = call("get", {
			config = config,
			type   = stype
		})

		if type(rv) == "table" and type(rv.values) == "table" then
			local sname, section
			for sname, section in pairs(rv.values) do
				if comparator(section) then
					_, err = call("delete", {
						config  = config,
						section = sname
					})
				end
			end
		end
	elseif comparator == nil then
		_, err = call("delete", {
			config  = config,
			type    = stype
		})
	else
		return false, "Invalid argument"
	end

	return (err == nil), ERRSTR[err]
end

function apply(self, configlist, command)
	configlist = self:_affected(configlist)
	if command then
		return { "/sbin/luci-reload", unpack(configlist) }
	else
		return os.execute("/sbin/luci-reload %s >/dev/null 2>&1"
			% util.shellquote(table.concat(configlist, " ")))
	end
end

-- Return a list of initscripts affected by configuration changes.
function _affected(self, configlist)
	configlist = type(configlist) == "table" and configlist or { configlist }

	-- Resolve dependencies
	local reloadlist = { }

	local function _resolve_deps(name)
		local reload = { name }
		local deps = { }

		self:foreach("ucitrack", name,
			function(section)
				if section.affects then
					for i, aff in ipairs(section.affects) do
						deps[#deps+1] = aff
					end
				end
			end)

		local i, dep
		for i, dep in ipairs(deps) do
			local j, add
			for j, add in ipairs(_resolve_deps(dep)) do
				reload[#reload+1] = add
			end
		end

		return reload
	end

	-- Collect initscripts
	local j, config
	for j, config in ipairs(configlist) do
		local i, e
		for i, e in ipairs(_resolve_deps(config)) do
			if not util.contains(reloadlist, e) then
				reloadlist[#reloadlist+1] = e
			end
		end
	end

	return reloadlist
end


text:
<?php namespace Anomaly\UsersModule\Http\Controller\Admin;

use Anomaly\Streams\Platform\Addon\FieldType\FieldTypeCollection;
use Anomaly\Streams\Platform\Assignment\Table\AssignmentTableBuilder;
use Anomaly\Streams\Platform\Field\Form\FieldAssignmentFormBuilder;
use Anomaly\Streams\Platform\Field\Form\FieldFormBuilder;
use Anomaly\Streams\Platform\Field\Table\FieldTableBuilder;
use Anomaly\Streams\Platform\Http\Controller\AdminController;
use Anomaly\UsersModule\User\UserModel;

/**
 * Class FieldsController
 *
 * @link          http://anomaly.is/streams-platform
 * @author        AnomalyLabs, Inc. <hello@anomaly.is>
 * @author        Ryan Thompson <ryan@anomaly.is>
 * @package       Anomaly\UsersModule\Http\Controller\Admin
 */
class FieldsController extends AdminController
{

    /**
     * Return an index of existing fields.
     *
     * @param FieldTableBuilder $table
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function index(AssignmentTableBuilder $table, UserModel $users)
    {
        $table->setOption('sortable', true)->setStream($users->getStream());

        return $table->render();
    }

    /**
     * Choose a field type for creating a field.
     *
     * @param FieldTypeCollection $fieldTypes
     * @return \Illuminate\View\View
     */
    public function type(FieldTypeCollection $fieldTypes)
    {
        return view('anomaly.module.users::ajax/choose_field_type', ['field_types' => $fieldTypes]);
    }

    /**
     * Return the form for a new field.
     *
     * @param FieldFormBuilder    $form
     * @param UserModel           $users
     * @param FieldTypeCollection $fieldTypes
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function create(FieldFormBuilder $form, UserModel $users, FieldTypeCollection $fieldTypes)
    {
        $form
            ->setStream($users->getStream())
            ->setOption('auto_assign', true)
            ->setFieldType($fieldTypes->get($_GET['field_type']));

        return $form->render();
    }

    /**
     * Return a form to edit the field.
     *
     * @param FieldFormBuilder $form
     * @param UserModel        $model
     * @param                  $id
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function edit(FieldFormBuilder $form, UserModel $model, $id)
    {
        return $form
            ->setStream($model->getStream())
            ->render($id);
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;

namespace string4
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Ohjelma selvittää onko sana palindromi.\nKirjoita sana: ");
            string userInput = Console.ReadLine();

            string reverse = "";
            int i = userInput.Length;

            for (int j = i-1; j >= 0; j--)
            {
                reverse = reverse + userInput[j];
            }

            if (reverse == userInput)
            {
                Console.WriteLine($"{userInput} on palindromi.");
            }
            else
            {
                Console.WriteLine($"{userInput} ei ole palindromi.");
            }

            Console.ReadKey();
        }
    }
}


text:
#ifndef WEBRTC_AUDIO_MOCK_VOICE_ENGINE_H_
#define WEBRTC_AUDIO_MOCK_VOICE_ENGINE_H_

#include <memory>

#include "webrtc/modules/audio_device/include/mock_audio_device.h"
#include "webrtc/modules/audio_device/include/mock_audio_transport.h"
#include "webrtc/modules/audio_processing/include/mock_audio_processing.h"
#include "webrtc/test/gmock.h"
#include "webrtc/test/mock_voe_channel_proxy.h"
#include "webrtc/voice_engine/voice_engine_impl.h"

namespace webrtc {
namespace voe {
class TransmitMixer;
}  // namespace voe

namespace test {

// NOTE: This class inherits from VoiceEngineImpl so that its clients will be
// able to get the various interfaces as usual, via T::GetInterface().
class MockVoiceEngine : public VoiceEngineImpl {
 public:
  // TODO(nisse): Valid overrides commented out, because the gmock
  // methods don't use any override declarations, and we want to avoid
  // warnings from -Winconsistent-missing-override. See
  // http://crbug.com/428099.
  MockVoiceEngine(
      rtc::scoped_refptr<AudioDecoderFactory> decoder_factory = nullptr)
      : decoder_factory_(decoder_factory) {
    // Increase ref count so this object isn't automatically deleted whenever
    // interfaces are Release():d.
    ++_ref_count;
    // We add this default behavior to make the mock easier to use in tests. It
    // will create a NiceMock of a voe::ChannelProxy.
    // TODO(ossu): As long as AudioReceiveStream is implemented as a wrapper
    // around Channel, we need to make sure ChannelProxy returns the same
    // decoder factory as the one passed in when creating an AudioReceiveStream.
    ON_CALL(*this, ChannelProxyFactory(testing::_))
        .WillByDefault(testing::Invoke([this](int channel_id) {
          auto* proxy =
              new testing::NiceMock<webrtc::test::MockVoEChannelProxy>();
          EXPECT_CALL(*proxy, GetAudioDecoderFactory())
              .WillRepeatedly(testing::ReturnRef(decoder_factory_));
          EXPECT_CALL(*proxy, SetReceiveCodecs(testing::_))
              .WillRepeatedly(testing::Invoke(
                  [](const std::map<int, SdpAudioFormat>& codecs) {
                    EXPECT_THAT(codecs, testing::IsEmpty());
                  }));
          return proxy;
        }));

    ON_CALL(mock_audio_device_, TimeUntilNextProcess())
        .WillByDefault(testing::Return(1000));
    ON_CALL(*this, audio_device_module())
        .WillByDefault(testing::Return(&mock_audio_device_));
    ON_CALL(*this, audio_processing())
        .WillByDefault(testing::Return(&mock_audio_processing_));
    ON_CALL(*this, audio_transport())
        .WillByDefault(testing::Return(&mock_audio_transport_));
  }
  virtual ~MockVoiceEngine() /* override */ {
    // Decrease ref count before base class d-tor is called; otherwise it will
    // trigger an assertion.
    --_ref_count;
  }
  // Allows injecting a ChannelProxy factory.
  MOCK_METHOD1(ChannelProxyFactory, voe::ChannelProxy*(int channel_id));

  // VoiceEngineImpl
  virtual std::unique_ptr<voe::ChannelProxy> GetChannelProxy(
      int channel_id) /* override */ {
    return std::unique_ptr<voe::ChannelProxy>(ChannelProxyFactory(channel_id));
  }

  // VoEBase
  MOCK_METHOD1(RegisterVoiceEngineObserver, int(VoiceEngineObserver& observer));
  MOCK_METHOD0(DeRegisterVoiceEngineObserver, int());
  MOCK_METHOD3(
      Init,
      int(AudioDeviceModule* external_adm,
          AudioProcessing* audioproc,
          const rtc::scoped_refptr<AudioDecoderFactory>& decoder_factory));
  MOCK_METHOD0(audio_processing, AudioProcessing*());
  MOCK_METHOD0(audio_device_module, AudioDeviceModule*());
  MOCK_METHOD0(transmit_mixer, voe::TransmitMixer*());
  MOCK_METHOD0(Terminate, int());
  MOCK_METHOD0(CreateChannel, int());
  MOCK_METHOD1(CreateChannel, int(const ChannelConfig& config));
  MOCK_METHOD1(DeleteChannel, int(int channel));
  MOCK_METHOD1(StartReceive, int(int channel));
  MOCK_METHOD1(StopReceive, int(int channel));
  MOCK_METHOD1(StartPlayout, int(int channel));
  MOCK_METHOD1(StopPlayout, int(int channel));
  MOCK_METHOD1(StartSend, int(int channel));
  MOCK_METHOD1(StopSend, int(int channel));
  MOCK_METHOD1(GetVersion, int(char version[1024]));
  MOCK_METHOD0(LastError, int());
  MOCK_METHOD0(audio_transport, AudioTransport*());
  MOCK_METHOD2(AssociateSendChannel,
               int(int channel, int accociate_send_channel));

  // VoECodec
  MOCK_METHOD0(NumOfCodecs, int());
  MOCK_METHOD2(GetCodec, int(int index, CodecInst& codec));
  MOCK_METHOD2(SetSendCodec, int(int channel, const CodecInst& codec));
  MOCK_METHOD2(GetSendCodec, int(int channel, CodecInst& codec));
  MOCK_METHOD2(SetBitRate, int(int channel, int bitrate_bps));
  MOCK_METHOD2(GetRecCodec, int(int channel, CodecInst& codec));
  MOCK_METHOD2(SetRecPayloadType, int(int channel, const CodecInst& codec));
  MOCK_METHOD2(GetRecPayloadType, int(int channel, CodecInst& codec));
  MOCK_METHOD3(SetSendCNPayloadType,
               int(int channel, int type, PayloadFrequencies frequency));
  MOCK_METHOD2(SetFECStatus, int(int channel, bool enable));
  MOCK_METHOD2(GetFECStatus, int(int channel, bool& enabled));
  MOCK_METHOD4(SetVADStatus,
               int(int channel, bool enable, VadModes mode, bool disableDTX));
  MOCK_METHOD4(
      GetVADStatus,
      int(int channel, bool& enabled, VadModes& mode, bool& disabledDTX));
  MOCK_METHOD2(SetOpusMaxPlaybackRate, int(int channel, int frequency_hz));
  MOCK_METHOD2(SetOpusDtx, int(int channel, bool enable_dtx));

  // VoEFile
  MOCK_METHOD7(StartPlayingFileLocally,
               int(int channel,
                   const char fileNameUTF8[1024],
                   bool loop,
                   FileFormats format,
                   float volumeScaling,
                   int startPointMs,
                   int stopPointMs));
  MOCK_METHOD6(StartPlayingFileLocally,
               int(int channel,
                   InStream* stream,
                   FileFormats format,
                   float volumeScaling,
                   int startPointMs,
                   int stopPointMs));
  MOCK_METHOD1(StopPlayingFileLocally, int(int channel));
  MOCK_METHOD1(IsPlayingFileLocally, int(int channel));
  MOCK_METHOD6(StartPlayingFileAsMicrophone,
               int(int channel,
                   const char fileNameUTF8[1024],
                   bool loop,
                   bool mixWithMicrophone,
                   FileFormats format,
                   float volumeScaling));
  MOCK_METHOD5(StartPlayingFileAsMicrophone,
               int(int channel,
                   InStream* stream,
                   bool mixWithMicrophone,
                   FileFormats format,
                   float volumeScaling));
  MOCK_METHOD1(StopPlayingFileAsMicrophone, int(int channel));
  MOCK_METHOD1(IsPlayingFileAsMicrophone, int(int channel));
  MOCK_METHOD4(StartRecordingPlayout,
               int(int channel,
                   const char* fileNameUTF8,
                   CodecInst* compression,
                   int maxSizeBytes));
  MOCK_METHOD1(StopRecordingPlayout, int(int channel));
  MOCK_METHOD3(StartRecordingPlayout,
               int(int channel, OutStream* stream, CodecInst* compression));
  MOCK_METHOD3(StartRecordingMicrophone,
               int(const char* fileNameUTF8,
                   CodecInst* compression,
                   int maxSizeBytes));
  MOCK_METHOD2(StartRecordingMicrophone,
               int(OutStream* stream, CodecInst* compression));
  MOCK_METHOD0(StopRecordingMicrophone, int());

  // VoENetwork
  MOCK_METHOD2(RegisterExternalTransport,
               int(int channel, Transport& transport));
  MOCK_METHOD1(DeRegisterExternalTransport, int(int channel));
  MOCK_METHOD3(ReceivedRTPPacket,
               int(int channel, const void* data, size_t length));
  MOCK_METHOD4(ReceivedRTPPacket,
               int(int channel,
                   const void* data,
                   size_t length,
                   const PacketTime& packet_time));
  MOCK_METHOD3(ReceivedRTCPPacket,
               int(int channel, const void* data, size_t length));

  // VoERTP_RTCP
  MOCK_METHOD2(SetLocalSSRC, int(int channel, unsigned int ssrc));
  MOCK_METHOD2(GetLocalSSRC, int(int channel, unsigned int& ssrc));
  MOCK_METHOD2(GetRemoteSSRC, int(int channel, unsigned int& ssrc));
  MOCK_METHOD3(SetSendAudioLevelIndicationStatus,
               int(int channel, bool enable, unsigned char id));
  MOCK_METHOD3(SetReceiveAudioLevelIndicationStatus,
               int(int channel, bool enable, unsigned char id));
  MOCK_METHOD3(SetSendAbsoluteSenderTimeStatus,
               int(int channel, bool enable, unsigned char id));
  MOCK_METHOD3(SetReceiveAbsoluteSenderTimeStatus,
               int(int channel, bool enable, unsigned char id));
  MOCK_METHOD2(SetRTCPStatus, int(int channel, bool enable));
  MOCK_METHOD2(GetRTCPStatus, int(int channel, bool& enabled));
  MOCK_METHOD2(SetRTCP_CNAME, int(int channel, const char cName[256]));
  MOCK_METHOD2(GetRTCP_CNAME, int(int channel, char cName[256]));
  MOCK_METHOD2(GetRemoteRTCP_CNAME, int(int channel, char cName[256]));
  MOCK_METHOD7(GetRemoteRTCPData,
               int(int channel,
                   unsigned int& NTPHigh,
                   unsigned int& NTPLow,
                   unsigned int& timestamp,
                   unsigned int& playoutTimestamp,
                   unsigned int* jitter,
                   unsigned short* fractionLost));
  MOCK_METHOD4(GetRTPStatistics,
               int(int channel,
                   unsigned int& averageJitterMs,
                   unsigned int& maxJitterMs,
                   unsigned int& discardedPackets));
  MOCK_METHOD2(GetRTCPStatistics, int(int channel, CallStatistics& stats));
  MOCK_METHOD2(GetRemoteRTCPReportBlocks,
               int(int channel, std::vector<ReportBlock>* receive_blocks));
  MOCK_METHOD3(SetREDStatus, int(int channel, bool enable, int redPayloadtype));
  MOCK_METHOD3(GetREDStatus,
               int(int channel, bool& enable, int& redPayloadtype));
  MOCK_METHOD3(SetNACKStatus, int(int channel, bool enable, int maxNoPackets));

 private:
  // TODO(ossu): I'm not particularly happy about keeping the decoder factory
  // here, but due to how gmock is implemented, I cannot just keep it in the
  // functor implementing the default version of ChannelProxyFactory, above.
  // GMock creates an unfortunate copy of the functor, which would cause us to
  // return a dangling reference. Fortunately, this should go away once
  // voe::Channel does.
  rtc::scoped_refptr<AudioDecoderFactory> decoder_factory_;

  MockAudioDeviceModule mock_audio_device_;
  MockAudioProcessing mock_audio_processing_;
  MockAudioTransport mock_audio_transport_;
};
}  // namespace test
}  // namespace webrtc

#endif  // WEBRTC_AUDIO_MOCK_VOICE_ENGINE_H_


text:
layout: post
title:  "Linux Kernel(4.1) API Reference "
date:   2016-09-23 21:22:37 +0800
categories: 嵌入式开发
tags: Linux
topics: Linux内核移植
excerpt: 摘要
---

* menu
{:toc}

### 1 Auxilary Interfaces

#### 1.1 double linked list

```c
static inline void INIT_LIST_HEAD(struct list_head *list);
list_for_each_entry(pos, struct list_head *head, member);
static inline void list_add_tail(struct list_head *new, struct list_head *head);
static inline void list_del(struct list_head *entry);
```

#### 1.2 bit operation

```c
static inline void set_bit(int nr, unsigned long *addr);
static inline void clear_bit(int nr, unsigned long *addr);
static __always_inline int test_bit(int nr, const volatile unsigned long *addr);
```

#### 1.3 communication between user space and kernel space

* memory copy

```c
static inline long copy_to_user(void __user *to, const void *from, unsigned long n);
static inline long copy_from_user(void *to, const void __user *from, unsigned long n);
get_user(x, p)/put_user(x, p)
```

* async signal

```c
int fasync_helper(int fd, struct file *filp, int on, struct fasync_struct **fapp);
void kill_fasync(struct fasync_struct **fp, int sig, int band);
```

### 2 mutex/semaphore/lock

#### 2.1 mutex

```c
mutex_init(struct mutex *lock);
int __sched mutex_lock_interruptible(struct mutex *lock);
void __sched mutex_unlock(struct mutex *lock);
```

#### 2.2 spin lock

```c
spin_lock_init(spinlock_t *lock);
static inline void spin_lock_irqsave(spinlock_t *lock, unsigned long flags);
static inline void spin_unlock_irqrestore(spinlock_t *lock, unsigned long flags);
static inline void spin_lock_irq(spinlock_t *lock);
static inline void spin_unlock_irq(spinlock_t *lock);
```

#### 2.3 read/write lock

```c
static DEFINE_RWLOCK(name);
write_lock(rwlock_t *lock);
write_unlock(rwlock_t *lock);
read_lock(rwlock_t *lock);
read_unlock(rwlock_t *lock);
```

### 3 Process Schedule & event deal

#### 3.1 wait queue

```c
DEFINE_WAIT(wait)/DECLARE_WAITQUEUE(wait, task);
init_waitqueue_head(wait_queue_head_t *q);

void add_wait_queue(wait_queue_head_t *q, wait_queue_t *wait);
void remove_wait_queue(wait_queue_head_t *q, wait_queue_t *wait);

void prepare_to_wait(wait_queue_head_t *q, wait_queue_t *wait, int state);
void schedule();
wake_up_interruptible(wait_queue_head_t *q);
void finish_wait(wait_queue_head_t *q, wait_queue_t *wait);
set_current_state(state);
```

#### 3.2 work queue

```c
alloc_workqueue(name, flags, max_active, args...);
destroy_workqueue(struct workqueue_struct *hub_wq);

static inline bool queue_work(struct workqueue_struct *wq, struct work_struct *work);
```

#### 3.3 completion

```c
DECLARE_COMPLETION(work)/static inline void init_competion(struct completion *x);
void __sched wait_for_completion(struct completion *x);
unsigned long __sched wait_for_completion_timeout(struct completion *x, unsigned lonf timeout);
void complete(struct completion *x);
void complete_all(struct completion *x);
```

#### 3.4 notifier

```c
BLOCKING_NOTIFIER_HEAD(list_name);
int blocking_notifier_chain_register(struct blocking_notifier_head *nh,
                                     struct notifier_block *n);
int blocking_notifier_chain_unregister(struct blocking_notifier_head *nh,
                                       struct notifier_block *n);
int blocking_notifier_call_chain(struct blocking_notifier_head *nh,
                                 unsigned long val, void *v);
```

### 4 Memory Management

#### 4.1 kzalloc/kmalloc/kfree

```c
static inline void *kzalloc(size_t size, gfp_t flags);
static _always_inline void *kmalloc(size_t size, gfp_t flags);
void kfree(const void *objp);
```

#### 4.2 vzalloc/vfree

```c
void *vzalloc(unsigned long size);
void vfree(const void *addr);
```

#### 4.3 dma pool

```c
struct dma_pool *dma_pool_create(const char *name, struct device *dev,
                                 size_t size, size_t align, size_t boundary);
void dma_pool_destroy(struct dma_pool *pool);

void *dma_pool_alloc(struct dma_pool *pool, gfp_t mem_flags, dma_addr_t *handle);
void dma_pool_free(struct dma_pool *pool, void *vaddr, dma_addr_t dma);
```

#### 4.4 dma coherent memory

```c
int dma_declare_coherent_memory(struct device *dev, phys_addr_t phys_addr,
                                dma_addr_t device_addr, size_t size, int flags);
void dma_release_declared_memory(struct device *dev);

static inline void *dma_alloc_coherent(struct device *dev, size_t size,
                                       dma_addr_t *dma_handle, gfp_t flag);
static inline void dma_free_coherent(struct device *dev, size_t size,
                                     void *cpu_addr, dma_addr_t dma_handle);
```


text:
package proxmox

import (
	"fmt"
	"net/url"
	"strconv"
)

type Node struct {
	Mem      float64 `json:"mem"`
	MaxDisk  float64 `json:"maxdisk"`
	Node     string  `json:"node"`
	MaxCPU   float64 `json:"maxcpu"`
	Uptime   float64 `json:"uptime"`
	Id       string  `json:"id"`
	CPU      float64 `json:"cpu"`
	Level    string  `json:"level"`
	NodeType string  `json:"nodetype"`
	Disk     float64 `json:"disk"`
	MaxMem   float64 `json:"maxmem"`
	Proxmox  ProxMox
}

type NodeList map[string]Node

type NodeListResult struct {
	Data NodeList `json:"data"`
}

func (node Node) Qemu() (QemuList, error) {
	var err error
	var data map[string]interface{}
	var list QemuList
	var vm QemuVM
	var results []interface{}
	var VMIdFloat float64

	//fmt.Println("!Qemu")

	data, err = node.Proxmox.Get("nodes/" + node.Node + "/qemu")
	if err != nil {
		return nil, err
	}

	list = make(QemuList)
	results = data["data"].([]interface{})
	for _, v0 := range results {
		v := v0.(map[string]interface{})
		if _, ok := v["vmid"].(string); ok {
			VMIdFloat, err = strconv.ParseFloat(v["vmid"].(string), 64)
			if err != nil {
				return nil, err
			}
		} else {
			VMIdFloat = v["vmid"].(float64)
		}

		vm = QemuVM{
			Mem:    v["mem"].(float64),
			CPUs:   v["cpus"].(float64),
			NetOut: v["netout"].(float64),
			//			PID:       v["pid"].(string),
			Disk:      v["disk"].(float64),
			MaxMem:    v["maxmem"].(float64),
			Status:    v["status"].(string),
			NetIn:     v["netin"].(float64),
			MaxDisk:   v["maxdisk"].(float64),
			Name:      v["name"].(string),
			DiskWrite: v["diskwrite"].(float64),
			CPU:       v["cpu"].(float64),
			VMId:      VMIdFloat,
			DiskRead:  v["diskread"].(float64),
			Uptime:    v["uptime"].(float64),
			Node:      node,
		}

		switch v["template"].(type) {
		case float64:
			vm.Template = v["template"].(float64)
		default:
			vm.Template = 0
		}

		list[strconv.FormatFloat(vm.VMId, 'f', 0, 64)] = vm
	}

	return list, nil
}

func (node Node) MaxQemuId() (float64, error) {
	var list QemuList
	var vm QemuVM
	var id float64
	var err error

	//fmt.Println("!MaxQemuId")

	id = 1009
	list, err = node.Qemu()
	if err != nil {
		return 0, err
	}

	for _, vm = range list {
		if vm.VMId > id && vm.VMId >= 1010 && vm.VMId < 2000 {
			id = vm.VMId
		}
	}
	return id, nil
}

func (node Node) Storages() (StorageList, error) {
	var err error
	var data map[string]interface{}
	var list StorageList
	var storage Storage
	var results []interface{}

	//fmt.Println("!Storages")

	data, err = node.Proxmox.Get("nodes/" + node.Node + "/storage")
	if err != nil {
		return nil, err
	}
	list = make(StorageList)
	results = data["data"].([]interface{})
	for _, v0 := range results {
		v := v0.(map[string]interface{})
		storage = Storage{
			StorageType: v["type"].(string),
			Active:      v["active"].(float64),
			Total:       v["total"].(float64),
			Content:     v["content"].(string),
			Shared:      v["shared"].(float64),
			Storage:     v["storage"].(string),
			Used:        v["used"].(float64),
			Avail:       v["avail"].(float64),
			Node:        node,
		}
		list[storage.Storage] = storage
	}

	return list, nil
}

func (node Node) CreateQemuVM(Name string, Sockets int, Cores int, MemorySize int, DiskSize string) (string, error) {
	var err error
	var newVmId string
	var storageList StorageList
	//var storage Storage
	var results map[string]interface{}
	var storageId string
	var form url.Values
	var target string

	//fmt.Println("!CreateQemuVM")

	newVmId, err = node.Proxmox.NextVMId()
	if err != nil {
		return "", err
	}
	//fmt.Println("new VM ID: " + newVmId)
	storageList, err = node.Storages()
	results, err = storageList["local"].CreateVolume("vm-"+newVmId+"-disk-0.qcow2", DiskSize, newVmId)
	if err != nil {
		return "", err
	}
	storageId = results["data"].(string)

	//fmt.Println("!CreateVolume")

	form = url.Values{
		"vmid":    {newVmId},
		"memory":  {strconv.Itoa(MemorySize)},
		"sockets": {strconv.Itoa(Sockets)},
		"cores":   {strconv.Itoa(Cores)},
		"net0":    {"virtio,bridge=vmbr0"},
		"virtio0": {storageId},
	}
	if Name != "" {
		form.Set("name", Name)
	}

	target = "nodes/" + node.Node + "/qemu"
	results, err = node.Proxmox.PostForm(target, form)
	if err != nil {
		fmt.Println("Error creating VM!!!")
		return "", err
	}
	//fmt.Println("VM " + newVmId + " created")

	return newVmId, err
}

func (node Node) VZDump(VmId string, BWLimit int, Compress string, IONice int, LockWait int, Mode string) (string, error) {
	var form url.Values
	var target string
	var err error
	var results map[string]interface{}

	form = url.Values{
		"vmid":     {VmId},
		"compress": {Compress},
		"lockwait": {strconv.Itoa(LockWait)},
		"mode":     {Mode},
	}
	if BWLimit > 0 {
		form.Set("bwlimit", strconv.Itoa(BWLimit))
	}
	if IONice > 0 {
		form.Set("ionice", strconv.Itoa(IONice))
	}
	target = "nodes/" + node.Node + "/vzdump"
	results, err = node.Proxmox.PostForm(target, form)
	if err != nil {
		fmt.Println("Error dumping VM!")
		return "", err
	}
	return results["data"].(string), nil
}

func (node Node) Tasks(Limit int, Start int, UserFilter string, VmId string) (TaskList, error) {
	var err error
	var target string
	var data map[string]interface{}
	var list TaskList
	var task Task
	var results []interface{}

	//fmt.Println("!Tasks")
	target = "nodes/" + node.Node + "/tasks?"
	if Limit > 0 {
		target = target + "limit=" + strconv.Itoa(Limit) + "&"
	}
	if Start > 0 {
		target = target + "start=" + strconv.Itoa(Start) + "&"
	}
	if UserFilter != "" {
		target = target + "userfilter=" + UserFilter + "&"
	}
	if VmId != "" {
		target = target + "vmid=" + VmId + "&"
	}
	target = target[0 : len(target)-1]
	data, err = node.Proxmox.Get(target)
	if err != nil {
		return nil, err
	}
	list = make(TaskList)
	results = data["data"].([]interface{})
	for _, v0 := range results {
		v := v0.(map[string]interface{})
		task = Task{
			UPid:      v["upid"].(string),
			Type:      v["type"].(string),
			Status:    v["status"].(string),
			PID:       v["pid"].(float64),
			PStart:    v["pstart"].(float64),
			StartTime: v["starttime"].(float64),
			EndTime:   v["endtime"].(float64),
			ID:        v["id"].(string),
			proxmox:   node.Proxmox,
		}
		list[task.UPid] = task
	}

	return list, nil
}


text:
标签大小

                    小标签
                    缺省
                    大标签

标签圆角

                    标签
                    标签
                    标签

更换背景色

                    <input type="text" class="form-control" data-bind="value:bgColor"></input>

文本颜色

                    <input type="text" class="form-control" data-bind="value:fontColor"></input>


text:
<?php
namespace cms\frontend\tests\acceptance;

use frontend\tests\AcceptanceTester;
use yii\helpers\Url;

class SiteCest
{
    public function checkSignup(AcceptanceTester $I)
    {
        $I->amOnPage(Url::toRoute('/site/signup'));
        $I->see('注册');
        $I->see('请填写下面信息完成注册');
        $I->fillField("#signupform-username", "feep");
        $I->fillField("#signupform-password", "111111");
        $I->fillField("#signupform-email", "test@feehi.com");
        $I->submitForm("button[name=signup-button]", []);
    }

    public function checkLogin(AcceptanceTester $I)
    {
        $I->amOnPage(Url::toRoute('/site/login'));
        $I->see('记住登陆');

        $I->seeLink('重置');

        $I->fillField("#loginform-username", "feep");
        $I->fillField("#loginform-password", "111111");
        $I->submitForm("button[name=login-button]", []);
        $I->see("Welcome");
        $I->see("退出登陆");
    }

    public function checkRequestPasswordReset(AcceptanceTester $I)
    {
        $I->amOnPage(Url::toRoute('/site/request-password-reset'));
        $I->see('重置密码');
    }

    public function checkResetPassword(AcceptanceTester $I)
    {
        $I->amOnPage(Url::toRoute('/site/reset-password'));
        $I->see("Bad Request");
    }

    public function checkLanguage(AcceptanceTester $I)
    {
        $I->setHeader("Referer", Url::toRoute('/article/index'));
        $I->amOnPage(Url::toRoute(['/site/language', 'lang'=>'en-US']));
        $I->see("About us");
    }

    public function checkOffline(AcceptanceTester $I)
    {
        $I->amOnPage(Url::toRoute('/site/offline'));
        $I->see("temporary unserviceable");
    }

    public function checkError(AcceptanceTester $I)
    {
        $I->amOnPage(Url::toRoute('/site/error'));
        $I->see("404");
    }
}


text:
class TwitterData < ActiveRecord::Base
end


text:
When we set up a new Meetup at Meetup.com, you can use the following text parts.

## Field "How can you find us?"

> Subway Station: Golzheimer Platz (U78 or U79). 5min walk to the building (B1). Enter the building, go to the reception desk and sign in to receive your visitor's badge. Take the elevator to the 10th floor and follow the signs.

## Field "Details"

> We would like to invite you to our monthly meetup at the trivago tower in Düsseldorf. In `<MONTH>`, we will `<TOPIC-OR-FORMAT-OF-THE-EVENING>`.
>
> `<DESCRIPTION-OF-TOPIC-OR-FORMAT-WITH-SPEAKERS>`
>
> Agenda
> • 18:30 - 19:00: Arrival, get your first drink, pizza and socializing
> • 19:10 - ~19:40: First talk
> • 19:50 - ~20:20: Second talk
> • 20:20 - Open End: Socialising
>
> Attendance is free. WiFi, beer, and non-alcoholic drinks will be provided (for free as well!) and we would love to see you there :)
>
> • Important to know
>
> • Language of the event: English
> • WiFi: Available
> • Costs: Free
> • Drinks: Available


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

<title>EmbeddedSimpleDataSource (Apache Derby 10.10 API Documentation)</title>
<meta name="date" content="2014-03-27">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Apache Derby 10.10

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.derby.jdbc

Class EmbeddedSimpleDataSource

java.lang.Object

org.apache.derby.jdbc.EmbeddedSimpleDataSource

All Implemented Interfaces:

javax.sql.DataSource

public final class EmbeddedSimpleDataSource
extends java.lang.Object
implements javax.sql.DataSource

This datasource is suitable for an application using embedded Derby,
 running on CDC/Foundation Profile 1.1.

 EmbeddedSimpleDataSource is Derby's DataSource implementation
 for J2ME/CDC/Foundation. It is also supports J2SE platforms.

 Supports the same properties as EmbeddedDataSource, see that class for details.

        EmbeddedSimpleDataSource automatically supports the correct JDBC specification version
        for the Java Virtual Machine's environment.

 JDBC Optional Package for CDC/Foundation Profile(JSR-169) - J2ME - CDC/Foundation

 JDBC 3.0 - Java 2 - JDK 1.4, J2SE 5.0

See Also:

EmbeddedDataSource

Constructor Summary

Constructors

Constructor and Description

EmbeddedSimpleDataSource()

No-arg constructor.

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

java.sql.Connection
getConnection()

Attempt to establish a database connection.

java.sql.Connection
getConnection(java.lang.String username,
             java.lang.String password)

Attempt to establish a database connection with the given username and
 password.

java.lang.String
getConnectionAttributes()

java.lang.String
getCreateDatabase()

java.lang.String
getDatabaseName()

java.lang.String
getDataSourceName()

java.lang.String
getDescription()

int
getLoginTimeout()

Gets the maximum time in seconds that this data source can wait while
 attempting to connect to a database.

java.io.PrintWriter
getLogWriter()

Get the log writer for this data source.

java.lang.String
getPassword()

java.lang.String
getShutdownDatabase()

java.lang.String
getUser()

void
setConnectionAttributes(java.lang.String prop)

Set this property to pass in more Derby specific connection URL
 attributes.

void
setCreateDatabase(java.lang.String create)

Set this property to create a new database.

void
setDatabaseName(java.lang.String databaseName)

Set the database name.

void
setDataSourceName(java.lang.String dsn)

Set the data source name.

void
setDescription(java.lang.String desc)

Set the data source descripton.

void
setLoginTimeout(int seconds)

Sets the maximum time in seconds that this data source will wait while
 attempting to connect to a database.

void
setLogWriter(java.io.PrintWriter out)

Set the log writer for this data source.

void
setPassword(java.lang.String password)

Set the password property for the data source.

void
setShutdownDatabase(java.lang.String shutdown)

Set this property if one wishes to shutdown the database identified by
 databaseName.

void
setUser(java.lang.String user)

Set the user property for the data source.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

EmbeddedSimpleDataSource

public EmbeddedSimpleDataSource()

No-arg constructor.

Method Detail

getLoginTimeout

public int getLoginTimeout()
                    throws java.sql.SQLException

Gets the maximum time in seconds that this data source can wait while
 attempting to connect to a database. A value of zero means that the
 timeout is the default system timeout if there is one; otherwise it means
 that there is no timeout. When a data source object is created, the login
 timeout is initially zero.

Specified by:

getLoginTimeout in interface javax.sql.DataSource

Returns:

the data source login time limit

Throws:

java.sql.SQLException - if a database access error occurs.

setLoginTimeout

public void setLoginTimeout(int seconds)
                     throws java.sql.SQLException

Sets the maximum time in seconds that this data source will wait while
 attempting to connect to a database. A value of zero specifies that the
 timeout is the default system timeout if there is one; otherwise it
 specifies that there is no timeout. When a data source object is created,
 the login timeout is initially zero.

 Derby ignores this property.

Specified by:

setLoginTimeout in interface javax.sql.DataSource

Parameters:

seconds - the data source login time limit

Throws:

java.sql.SQLException - if a database access error occurs.

getLogWriter

public java.io.PrintWriter getLogWriter()
                                 throws java.sql.SQLException

Get the log writer for this data source.

 The log writer is a character output stream to which all logging and
 tracing messages for this data source object instance will be printed.
 This includes messages printed by the methods of this object, messages
 printed by methods of other objects manufactured by this object, and so
 on. Messages printed to a data source specific log writer are not printed
 to the log writer associated with the java.sql.Drivermanager class. When
 a data source object is created the log writer is initially null, in
 other words, logging is disabled.

Specified by:

getLogWriter in interface javax.sql.DataSource

Returns:

the log writer for this data source, null if disabled

Throws:

java.sql.SQLException - if a database-access error occurs.

setLogWriter

public void setLogWriter(java.io.PrintWriter out)
                  throws java.sql.SQLException

Set the log writer for this data source.

 The log writer is a character output stream to which all logging and
 tracing messages for this data source object instance will be printed.
 This includes messages printed by the methods of this object, messages
 printed by methods of other objects manufactured by this object, and so
 on. Messages printed to a data source specific log writer are not printed
 to the log writer associated with the java.sql.Drivermanager class. When
 a data source object is created the log writer is initially null, in
 other words, logging is disabled.

Specified by:

setLogWriter in interface javax.sql.DataSource

Parameters:

out - the new log writer; to disable, set to null

Throws:

java.sql.SQLException - if a database-access error occurs.

setDatabaseName

public final void setDatabaseName(java.lang.String databaseName)

Set the database name. Setting this property is mandatory. If a database
 named wombat at g:/db needs to be accessed, database name should be set
 to "g:/db/wombat". The database will be booted if it is not already
 running in the system.

Parameters:

databaseName - the name of the database

getDatabaseName

public java.lang.String getDatabaseName()

setDataSourceName

public final void setDataSourceName(java.lang.String dsn)

Set the data source name. The property is not mandatory. It is used for
 informational purposes only.

Parameters:

dsn - the name of the data source

getDataSourceName

public final java.lang.String getDataSourceName()

Returns:

data source name

setDescription

public final void setDescription(java.lang.String desc)

Set the data source descripton. This property is not mandatory. It is
 used for informational purposes only.

Parameters:

desc - the description of the data source

getDescription

public final java.lang.String getDescription()

Returns:

description

setUser

public final void setUser(java.lang.String user)

Set the user property for the data source. This is user
 name for any data source getConnection() call that takes no arguments.

getUser

public final java.lang.String getUser()

Returns:

user

setPassword

public final void setPassword(java.lang.String password)

Set the password property for the data source. This is
 user's password for any data source getConnection() call that takes no
 arguments.

getPassword

public final java.lang.String getPassword()

Returns:

password

setCreateDatabase

public final void setCreateDatabase(java.lang.String create)

Set this property to create a new database. If this property is not set,
 the database (identified by databaseName) is assumed to be already
 existing.

Parameters:

create - if set to the string "create", this data source will try to
            create a new database of databaseName, or boot the database if
            one by that name already exists.

getCreateDatabase

public final java.lang.String getCreateDatabase()

Returns:

"create" if create is set, or null if not

setShutdownDatabase

public final void setShutdownDatabase(java.lang.String shutdown)

Set this property if one wishes to shutdown the database identified by
 databaseName.

Parameters:

shutdown - if set to the string "shutdown", this data source will
            shutdown the database if it is running.

getShutdownDatabase

public final java.lang.String getShutdownDatabase()

Returns:

"shutdown" if shutdown is set, or null if not

setConnectionAttributes

public final void setConnectionAttributes(java.lang.String prop)

Set this property to pass in more Derby specific connection URL
 attributes.

   Any attributes that can be set using a property of this DataSource implementation
   (e.g user, password) should not be set in connectionAttributes. Conflicting
   settings in connectionAttributes and properties of the DataSource will lead to
   unexpected behaviour.

Parameters:

prop - set to the list of Derby connection attributes separated
            by semi-colons. E.g., to specify an encryption bootPassword of
            "x8hhk2adf", and set upgrade to true, do the following:

 ds.setConnectionAttributes("bootPassword=x8hhk2adf;upgrade=true");

 See Derby's documentation for complete list.

getConnectionAttributes

public final java.lang.String getConnectionAttributes()

Returns:

Derby specific connection URL attributes

getConnection

public final java.sql.Connection getConnection()
                                        throws java.sql.SQLException

Attempt to establish a database connection.

Specified by:

getConnection in interface javax.sql.DataSource

Returns:

a Connection to the database

Throws:

java.sql.SQLException - if a database-access error occurs.

getConnection

public final java.sql.Connection getConnection(java.lang.String username,
                                               java.lang.String password)
                                        throws java.sql.SQLException

Attempt to establish a database connection with the given username and
 password. If the attributeAsPassword property is set to true then the
 password argument is taken to be a list of connection attributes with the
 same format as the connectionAttributes property.

Specified by:

getConnection in interface javax.sql.DataSource

Parameters:

username - the database user on whose behalf the Connection is being made

password - the user's password

Returns:

a Connection to the database

Throws:

java.sql.SQLException - if a database-access error occurs.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Built on Thu 2014-03-27 12:16:03-0700, from revision 1582446

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Apache Derby 10.10 API Documentation  -  Copyright © 2004,2014 The Apache Software Foundation. All Rights Reserved.


text:
<?php namespace Bedard\Webhooks\Models;

use DB;
use Model;
use Queue;
use Backend;
use Carbon\Carbon;
use Bedard\Webhooks\Models\Log;
use Bedard\Webhooks\Exceptions\ScriptDisabledException;

/**
 * Hook Model
 */
class Hook extends Model
{

    /**
     * @var string The database table used by the model.
     */
    public $table = 'bedard_webhooks_hooks';

    /**
     * @var array Guarded fields
     */
    protected $guarded = ['*'];

    /**
     * @var array Fillable fields
     */
    protected $fillable = [
        'name',
        'script',
        'http_method',
        'is_enabled',
    ];

    /**
     * @var array Attribute casting
     */
    protected $casts = [
        'is_enabled' => 'boolean',
    ];

    /**
     * @var array Datetime fields
     */
    protected $dates = [
        'created_at',
        'updated_at',
        'executed_at',
    ];

    /**
     * @var array Relations
     */
    public $hasMany = [
        'logs' => [
            'Bedard\Webhooks\Models\Log',
        ],
    ];

    /**
     * Generate a unique token
     *
     * @return void
     */
    public function beforeCreate()
    {
        do {
            $this->token = str_random(40);
        } while (self::where('token', $this->token)->exists());
    }

    /**
     * Execute the script and log the output
     *
     * @return boolean
     */
    public function queueScript()
    {
        $id = $this->id;
        Queue::push(function() use ($id) { Hook::findAndExecuteScript($id); });
    }

    /**
     * Execute the shell script and log the output
     *
     * @return string
     */
    public function executeScript()
    {
        // Make sure the script is enabled
        if (!$this->is_enabled) {
            throw new ScriptDisabledException();
        }

        // Run the script and log the output
        $output = shell_exec($this->script);
        Log::create(['hook_id' => $this->id, 'output' => $output]);

        // Update our executed_at timestamp
        $this->executed_at = Carbon::now();
        $this->save();
    }

    /**
     * Returns the script with normalized line endings
     *
     * @return void
     */
    public function getScriptAttribute($script)
    {
        return preg_replace('/\r\n?/', PHP_EOL, $script);
    }

    /**
     * Find a hook by token and HTTP method
     *
     * @param  \October\Rain\Database\Builder   $query
     * @param  string                           $token
     * @param  string                           $httpMethod
     * @return \October\Rain\Database\Builder
     */
    public function scopeFindByTokenAndMethod($query, $token, $httpMethod) {
        return $query->whereIsEnabled(true)
            ->whereHttpMethod($httpMethod)
            ->whereToken($token)
            ->firstOrFail();
    }

    /**
     * Find a hook and execute it's script
     *
     * @param  \October\Rain\Database\Builder   $query
     * @param  integer                          $id
     * @return \October\Rain\Database\Builder
     */
    public function scopeFindAndExecuteScript($query, $id)
    {
        return $query->find($id)->executeScript();
    }

    /**
     * Enables or disables webhooks
     *
     * @param  \October\Rain\Database\Builder   $query
     * @return integer
     */
    public function scopeSetIsEnabled($query, $isEnabled)
    {
        return $query->update([
            'is_enabled' => $isEnabled,
            'updated_at' => Carbon::now(),
        ]);
    }

    public function scopeDisable($query)
    {
        return $query->setIsEnabled(false);
    }

    public function scopeEnable($query)
    {
        return $query->setIsEnabled(true);
    }

    /**
     * Left joins the logs count
     *
     * @param  \October\Rain\Database\Builder   $query
     * @return \October\Rain\Database\Builder
     */
    public function scopeJoinLogsCount($query)
    {
        $subquery = Log::select(DB::raw('id, hook_id, COUNT(*) as logs_count'))
            ->groupBy('hook_id')
            ->getQuery()
            ->toSql();

        return $query
            ->addSelect('bedard_webhooks_hooks.*')
            ->addSelect('logs.logs_count')
            ->leftJoin(DB::raw('(' . $subquery . ') logs'), 'bedard_webhooks_hooks.id', '=', 'logs.hook_id');
    }

    /**
     * Helper for snake_case http method
     *
     * @return string
     */
    public function getHttpMethodAttribute()
    {
        return array_key_exists('http_method', $this->attributes)
            ? $this->attributes['http_method']
            : 'post';
    }

    /**
     * Count the number of logs this hook has
     *
     * @return integer
     */
    public function getLogsCountAttribute($logs)
    {
        return array_key_exists('logs_count', $this->attributes)
            ? (int) $this->attributes['logs_count']
            : 0;
    }

    /**
     * Returns a url to this webhook
     *
     * @return string
     */
    public function getUrlAttribute()
    {
        return url('bedard/webhooks', [ 'token' => $this->token ]);
    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: Ricardo Fiorani
 * Date: 02/03/2016
 * Time: 18:12
 */

namespace App\Action;

use App\Tweet\API\Adapter\TwitterAPIAdapter;
use App\Tweet\Entity\Tweet;
use Doctrine\ORM\EntityManager;
use Interop\Container\ContainerInterface;

class ReadTweetsFactory
{
    /**
     * @param ContainerInterface $container
     * @return ReadTweetsAction
     */
    public function __invoke(ContainerInterface $container)
    {

        $twitterRepository = $container->get(EntityManager::class)->getRepository(Tweet::class);
        $twitterAPIAdapter = $container->get(TwitterAPIAdapter::class);

        return new ReadTweetsAction($twitterRepository, $twitterAPIAdapter);
    }
}


text:
module Meme

  class Info

    VARS = ["avatar_url", "name", "title", "guid", "language", "url", "description"] #:nodoc:

    attr_accessor *VARS

    def initialize(data) #:nodoc:
      unless data.nil?
        VARS.each do |var|
          self.instance_variable_set("@#{var}", data[var])
        end
      end
    end

    # Find user
    #
    #   Example:
    #
    #   # by name
    #   user = Meme::Info.find('jtadeulopes')
    #   user.name
    #   => "jtadeulopes"
    #
    def self.find(name)
      query = "SELECT * FROM meme.info WHERE name='#{name}'"
      parse = Request.parse(query)
      if parse
        results = parse['query']['results']
        results.nil? ? nil : Info.new(results['meme'])
      else
        parse.error!
      end
    end

    # Find user by guid
    #
    #   Example:
    #
    #   user = Meme::Info.find_by_guid('EMREXCV4R5OTM3CZW3HBD5QAGY')
    #
    def self.find_by_guid(name)
      query = "SELECT * FROM meme.info WHERE owner_guid='#{name}'"
      parse = Request.parse(query)
      if parse
        results = parse['query']['results']
        results.nil? ? nil : Info.new(results['meme'])
      else
        parse.error!
      end
    end

    # Return user followers
    #
    #   Example:
    #
    #   # Search user
    #   user = Meme::Info.find('jtadeulopes')
    #
    #   # Default
    #   followers = user.followers
    #   followers.count
    #   => 10
    #
    #   # Specify a count
    #   followers = user.followers(100)
    #   followers.count
    #   => 100
    #
    #   # All followers
    #   followers = user.followers(:all)
    #   followers.count
    #
    #   follower = followers.first
    #   follower.name
    #   => "zigotto"
    #   follower.url
    #   => "http://meme.yahoo.com/zigotto/"
    #
    def followers(count=10)
      count = 0 if count.is_a?(Symbol) && count == :all
      query = "SELECT * FROM meme.followers(#{count}) WHERE owner_guid='#{self.guid}'"
      parse = Request.parse(query)
      if parse
        results = parse['query']['results']
        results.nil? ? nil : results['meme'].map {|m| Info.new(m)}
      else
        parse.error!
      end
    end

    # Return user following
    #
    #   Example:
    #
    #   # Search user
    #   user = Meme::Info.find('jtadeulopes')
    #
    #   # Default
    #   following = user.following
    #   following.count
    #   => 10
    #
    #   # Specify a count
    #   following = user.following(100)
    #   following.count
    #   => 100
    #
    #   # All following
    #   following = user.following(:all)
    #   following.count
    #
    def following(count=10)
      count = 0 if count.is_a?(Symbol) && count == :all
      query = "SELECT * FROM meme.following(#{count}) WHERE owner_guid='#{self.guid}'"
      parse = Request.parse(query)
      if parse
        results = parse['query']['results']
        results.nil? ? nil : results['meme'].map {|m| Info.new(m)}
      else
        parse.error!
      end
    end

    # Retrieves all posts of an user
    #
    def posts(quantity=0)
      query = "SELECT * FROM meme.posts(#{quantity}) WHERE owner_guid='#{self.guid}';"
      parse = Request.parse(query)
      if parse
        results = parse['query']['results']
        results.nil? ? nil : results['post'].map {|m| Post.new(m)}
      else
        parse.error!
      end
    end

  end

end


text:
package org.lirazs.gbackbone.client.core.test.model;

import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONValue;
import org.lirazs.gbackbone.client.core.collection.Collection;
import org.lirazs.gbackbone.client.core.data.Options;
import org.lirazs.gbackbone.client.core.model.Model;

/**
 * Created on 25/09/2015.
 */
public class JobItemModel extends Model {

    private Collection subItems;

    public JobItemModel() {
        super();
    }

    public JobItemModel(JSONObject model) {
        super(model);
    }

    public JobItemModel(Options attributes) {
        super(attributes);
    }

    public Collection getSubItems() {
        return subItems;
    }

    @Override
    protected Options parse(JSONValue resp, Options options) {
        JSONObject object = resp.isObject();

        subItems = new Collection();
        subItems.set(object.get("subItems"));
        object.put("subItems", null);

        return super.parse(resp, options);
    }
}


text:
require File.dirname(__FILE__) + '/test_helper'

class TabTest < Test::Unit::TestCase
  include Widgets

  EXPECTED_INSTANCE_METHODS = %w{highlights link name title html highlighted? highlights_on links_to named titled}

  def setup
    @myname = 'Paolo'
    @mysurname = 'Dona'

    @tab = Tab.new :name => 'tab', :link => {:controller => 'pippo', :action => 'pluto'}
    @simple_tab = Tab.new :name => 'simple_tab', :link => {:controller =>'pippo'}

    @dyntab = Tab.new :name => @myname,
                      :link => {:controller => 'pippo', :action => @myname},
                      :highlights => [{:controller => @mysurname}]

    @distab = Tab.new :name => 'disabled_tab',
                      :link => {:controller => 'pippo'},
                      :disabled_if => proc { 1 == 1 }

    @empty = Tab.new :name => 'empty'
  end

  def test_initialize_with_hash
    tab = Tab.new :name => 'sample'
    assert tab
    assert_equal 'sample', tab.name
  end

  def test_initialize_with_block
    tab = Tab.new do |t|
      t.name = 'sample'
    end
    assert tab
    assert_equal 'sample', tab.name
  end

  def test_initialize_with_highlights_array
    tab = Tab.new :name=>'test', :highlights => [{:action=>'list'}, {:action => 'index'}]
    assert_kind_of Array, tab.highlights
    assert_equal 2, tab.highlights.size
    assert_kind_of Hash, tab.highlights[0]
    assert_kind_of Hash, tab.highlights[1]
  end

  def test_initialize_with_single_highlight
    tab = Tab.new :name=>'test', :highlights => {:action=>'list'}
    assert_kind_of Array, tab.highlights
    assert_equal 1, tab.highlights.size
    assert_kind_of Hash, tab.highlights[0]
  end

  def test_presence_of_instance_methods
    EXPECTED_INSTANCE_METHODS.each do |instance_method|
      assert @tab.respond_to?(instance_method), "#{instance_method} is not defined in #{@tab.inspect} (#{@tab.class})"
    end
  end

  def test_name_dynamic
    assert_equal 'Paolo', @dyntab.name

    @dyntab.name= @mysurname
    assert_equal 'Dona', @dyntab.name
  end

  def test_links_to
    assert_equal({:controller => 'pippo', :action => 'pluto'}, @tab.link)

    @tab.link= {:controller => 'pluto'}
    assert_equal({:controller => 'pluto'}, @tab.link)
  end

  def test_links_to_dynamic
    assert_equal({:controller => 'pippo', :action => 'Paolo'}, @dyntab.link)

    @dyntab.link= {:controller => @mysurname}
    assert_equal({:controller => 'Dona'}, @dyntab.link)
  end

  def test_highlighted?
    t = Tab.new :name => 'cats', :highlights => {:controller => 'cats'}
    assert t.highlighted?({:controller => 'cats'})
  end

  def test_disabled?
    assert @distab.disabled?
    assert !@simple_tab.disabled?
  end

end


text:
import React from 'react';
import PropTypes from 'prop-types';
import { pxToRem } from '@strapi/helper-plugin';
import { Box } from '@strapi/design-system/Box';
import { IS_DONE, IS_ACTIVE, IS_NOT_DONE } from '../constants';

const StepLine = ({ type, ...props }) => {
  return (
    <Box
      width={pxToRem(2)}
      height="100%"
      background={type === IS_NOT_DONE ? 'neutral300' : 'primary500'}
      hasRadius
      {...props}
    />
  );
};

StepLine.defaultProps = {
  type: IS_NOT_DONE,
};

StepLine.propTypes = {
  type: PropTypes.oneOf([IS_ACTIVE, IS_DONE, IS_NOT_DONE]),
};

export default StepLine;


text:
package org.apache.drill.exec.planner.sql.handlers;

import java.math.BigDecimal;

import org.apache.calcite.sql.type.SqlTypeName;
import org.apache.calcite.tools.ValidationException;

import org.apache.calcite.util.NlsString;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.drill.common.exceptions.UserException;
import org.apache.drill.exec.ExecConstants;
import org.apache.drill.exec.ops.QueryContext;
import org.apache.drill.exec.physical.PhysicalPlan;
import org.apache.drill.exec.planner.sql.DirectPlan;
import org.apache.drill.exec.server.options.OptionManager;
import org.apache.drill.exec.server.options.OptionValue;
import org.apache.drill.exec.server.options.OptionValue.OptionScope;
import org.apache.drill.exec.server.options.QueryOptionManager;
import org.apache.drill.exec.util.ImpersonationUtil;
import org.apache.drill.exec.work.foreman.ForemanSetupException;
import org.apache.calcite.sql.SqlLiteral;
import org.apache.calcite.sql.SqlNode;
import org.apache.calcite.sql.SqlSetOption;

/**
 * Converts a {@link SqlNode} representing "ALTER .. SET option = value" and "ALTER ... RESET ..." statements to a
 * {@link PhysicalPlan}. See {@link SqlSetOption}. These statements have side effects i.e. the options within the
 * system context or the session context are modified. The resulting {@link DirectPlan} returns to the client a string
 * that is the name of the option that was updated.
 */
public class SetOptionHandler extends AbstractSqlHandler {
  private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(SetOptionHandler.class);

  private final QueryContext context;

  public SetOptionHandler(QueryContext context) {
    this.context = context;
  }

  @Override
  public PhysicalPlan getPlan(SqlNode sqlNode) throws ValidationException, ForemanSetupException {
    final SqlSetOption option = unwrap(sqlNode, SqlSetOption.class);
    final SqlNode value = option.getValue();
    if (value != null && !(value instanceof SqlLiteral)) {
      throw UserException.validationError()
          .message("Drill does not support assigning non-literal values in SET statements.")
          .build(logger);
    }

    final String scope = option.getScope();
    final OptionValue.OptionScope optionScope;
    if (scope == null) { // No scope mentioned assumed SESSION
      optionScope = OptionScope.SESSION;
    } else {
      switch (scope.toLowerCase()) {
      case "session":
        optionScope = OptionScope.SESSION;
        break;
      case "system":
        optionScope = OptionScope.SYSTEM;
        break;
      default:
        throw UserException.validationError()
            .message("Invalid OPTION scope %s. Scope must be SESSION or SYSTEM.", scope)
            .build(logger);
      }
    }

    final QueryOptionManager options = context.getOptions();
    if (optionScope == OptionScope.SYSTEM) {
      // If the user authentication is enabled, make sure the user who is trying to change the system option has
      // administrative privileges.
      if (context.isUserAuthenticationEnabled() &&
          !ImpersonationUtil.hasAdminPrivileges(
            context.getQueryUserName(),
            ExecConstants.ADMIN_USERS_VALIDATOR.getAdminUsers(options),
            ExecConstants.ADMIN_USER_GROUPS_VALIDATOR.getAdminUserGroups(options))) {
        throw UserException.permissionError()
            .message("Not authorized to change SYSTEM options.")
            .build(logger);
      }
    }

    final String optionName = option.getName().toString();

    // Currently, we convert multi-part identifier to a string.
    final OptionManager chosenOptions = options.getOptionManager(optionScope);

    if (value != null) { // SET option
      final Object literalObj = sqlLiteralToObject((SqlLiteral) value);
      chosenOptions.setLocalOption(optionName, literalObj);
    } else { // RESET option
      if ("ALL".equalsIgnoreCase(optionName)) {
        chosenOptions.deleteAllLocalOptions();
      } else {
        chosenOptions.deleteLocalOption(optionName);
      }
    }

    return DirectPlan.createDirectPlan(context, true, String.format("%s updated.", optionName));
  }

  private static Object sqlLiteralToObject(final SqlLiteral literal) {
    final Object object = literal.getValue();
    final SqlTypeName typeName = literal.getTypeName();
    switch (typeName) {
    case DECIMAL: {
      final BigDecimal bigDecimal = (BigDecimal) object;
      if (bigDecimal.scale() == 0) {
        return bigDecimal.longValue();
      } else {
        return bigDecimal.doubleValue();
      }
    }

    case DOUBLE:
    case FLOAT:
      return ((BigDecimal) object).doubleValue();

    case SMALLINT:
    case TINYINT:
    case BIGINT:
    case INTEGER:
      return ((BigDecimal) object).longValue();

    case VARBINARY:
    case VARCHAR:
    case CHAR:
      return ((NlsString) object).getValue().toString();

    case BOOLEAN:
      return object;

    default:
      throw UserException.validationError()
        .message("Drill doesn't support assigning literals of type %s in SET statements.", typeName)
        .build(logger);
    }
  }
}


text:
  for (AnalyzerContainer::iterator it = analyzers_.begin();                 \
       it != analyzers_.end(); ++it) {                                      \
    (*it)->func(__VA_ARGS__);                                               \
  }

#define CALL_ANALYSIS_FUNC2(type,func,...)                                  \
  for (AnalyzerContainer::iterator it = analyzers_.begin();                 \
       it != analyzers_.end(); ++it) {                                      \
    if ((*it)->desc()->Hook##type())                                        \
      (*it)->func(__VA_ARGS__);                                             \
  }

// Define macros for wrapper handlers.
#define MEMBER_WRAPPER_HANDLER(name) Handle##name
#define STATIC_WRAPPER_HANDLER(name) __##name

#define DECLARE_MEMBER_WRAPPER_HANDLER(name)                                \
 protected:                                                                 \
  virtual void MEMBER_WRAPPER_HANDLER(name)(WRAPPER_CLASS(name) *wrapper)

#define DECLARE_STATIC_WRAPPER_HANDLER(name)                                \
 protected:                                                                 \
  static void STATIC_WRAPPER_HANDLER(name)(WRAPPER_CLASS(name) *wrapper) {  \
    ctrl_->HandleBeforeWrapper(wrapper);                                    \
    ctrl_->MEMBER_WRAPPER_HANDLER(name)(wrapper);                           \
    ctrl_->HandleAfterWrapper(wrapper);                                     \
  }

#define DECLARE_WRAPPER_HANDLER(name)                                       \
  DECLARE_STATIC_WRAPPER_HANDLER(name);                                     \
  DECLARE_MEMBER_WRAPPER_HANDLER(name);

#define IMPLEMENT_WRAPPER_HANDLER(name, cls)                                \
  void cls::MEMBER_WRAPPER_HANDLER(name)(WRAPPER_CLASS(name) *wrapper)

#define ACTIVATE_WRAPPER_HANDLER(name)                                      \
  ACTIVATE_WRAPPER(name, img, STATIC_WRAPPER_HANDLER(name));

// Define macros for the main entry functions.
#define MAIN_ENTRY(controller)                                              \
  static controller *ctrl = new controller;                                 \
  static VOID I_InstrumentTrace(TRACE trace, VOID *v) {                     \
    ctrl->InstrumentTrace(trace, v);                                        \
  }                                                                         \
  static VOID I_ImageLoad(IMG img, VOID *v) {                               \
    ctrl->ImageLoad(img, v);                                                \
  }                                                                         \
  static VOID I_ImageUnload(IMG img, VOID *v) {                             \
    ctrl->ImageUnload(img, v);                                              \
  }                                                                         \
  static VOID I_SyscallEntry(THREADID tid,                                  \
                             CONTEXT *ctxt,                                 \
                             SYSCALL_STANDARD std,                          \
                             VOID *v) {                                     \
    ctrl->SyscallEntry(tid, ctxt, std, v);                                  \
  }                                                                         \
  static VOID I_SyscallExit(THREADID tid,                                   \
                            CONTEXT *ctxt,                                  \
                            SYSCALL_STANDARD std,                           \
                            VOID *v) {                                      \
    ctrl->SyscallExit(tid, ctxt, std, v);                                   \
  }                                                                         \
  static BOOL I_IntSignal(THREADID tid,                                     \
                          INT32 sig,                                        \
                          CONTEXT *ctxt,                                    \
                          BOOL hasHandler,                                  \
                          const EXCEPTION_INFO *pExceptInfo,                \
                          VOID *v) {                                        \
    ctrl->IntSignal(tid, sig, ctxt, hasHandler, pExceptInfo, v);            \
    return FALSE;                                                           \
  }                                                                         \
  static VOID I_ContextChange(THREADID tid,                                 \
                              CONTEXT_CHANGE_REASON reason,                 \
                              const CONTEXT *from,                          \
                              CONTEXT *to,                                  \
                              INT32 info,                                   \
                              VOID *v) {                                    \
    ctrl->ContextChange(tid, reason, from, to, info, v);                    \
  }                                                                         \
  static VOID I_ProgramStart() {                                            \
    ctrl->ProgramStart();                                                   \
  }                                                                         \
  static VOID I_ProgramExit(INT32 code, VOID *v) {                          \
    ctrl->ProgramExit(code, v);                                             \
  }                                                                         \
  static VOID I_ThreadStart(THREADID tid,                                   \
                            CONTEXT *ctxt,                                  \
                            INT32 flags,                                    \
                            VOID *v) {                                      \
    ctrl->ThreadStart(tid, ctxt, flags, v);                                 \
  }                                                                         \
  static VOID I_ThreadExit(THREADID tid,                                    \
                           const CONTEXT *ctxt,                             \
                           INT32 code,                                      \
                           VOID *v) {                                       \
    ctrl->ThreadExit(tid, ctxt, code, v);                                   \
  }                                                                         \
  int main(int argc, char *argv[]) {                                        \
    ctrl->Initialize();                                                     \
    ctrl->PreSetup();                                                       \
    PIN_InitSymbols();                                                      \
    PIN_Init(argc, argv);                                                   \
    ctrl->PostSetup();                                                      \
    TRACE_AddInstrumentFunction(I_InstrumentTrace, NULL);                   \
    IMG_AddInstrumentFunction(I_ImageLoad, NULL);                           \
    IMG_AddUnloadFunction(I_ImageUnload, NULL);                             \
    PIN_AddSyscallEntryFunction(I_SyscallEntry, NULL);                      \
    PIN_AddSyscallExitFunction(I_SyscallExit, NULL);                        \
    PIN_InterceptSignal(SIGUSR2, I_IntSignal, NULL);                        \
    PIN_AddContextChangeFunction(I_ContextChange, NULL);                    \
    PIN_AddFiniFunction(I_ProgramExit, NULL);                               \
    PIN_AddThreadStartFunction(I_ThreadStart, NULL);                        \
    PIN_AddThreadFiniFunction(I_ThreadExit, NULL);                          \
    I_ProgramStart();                                                       \
    PIN_StartProgram();                                                     \
  }

// The main controller for the dynamic program analysis.
class ExecutionControl {
 public:
  ExecutionControl();
  virtual ~ExecutionControl() {}

  void Initialize();
  void PreSetup();
  void PostSetup();
  void InstrumentTrace(TRACE trace, VOID *v);
  void ImageLoad(IMG img, VOID *v);
  void ImageUnload(IMG img, VOID *v);
  void SyscallEntry(THREADID tid, CONTEXT *ctxt, SYSCALL_STANDARD std, VOID *v);
  void SyscallExit(THREADID tid, CONTEXT *ctxt, SYSCALL_STANDARD std, VOID *v);
  void IntSignal(THREADID tid, INT32 sig, CONTEXT *ctxt, BOOL hasHandler,
                 const EXCEPTION_INFO *pExceptInfo, VOID *v);
  void ContextChange(THREADID tid, CONTEXT_CHANGE_REASON reason,
                     const CONTEXT *from, CONTEXT *to, INT32 info, VOID *v);
  void ProgramStart();
  void ProgramExit(INT32 code, VOID *v);
  void ThreadStart(THREADID tid, CONTEXT *ctxt, INT32 flags, VOID *v);
  void ThreadExit(THREADID tid, const CONTEXT *ctxt, INT32 code, VOID *v);

 protected:
  typedef std::list<Analyzer *> AnalyzerContainer;

  virtual Mutex *CreateMutex() { return new PinMutex; }

  virtual Semaphore *CreateSemaphore(unsigned int value) {
    return new SysSemaphore(value);
  }

  virtual void HandlePreSetup();
  virtual void HandlePostSetup();
  virtual bool HandleIgnoreInstCount(IMG img) { return false; }
  virtual bool HandleIgnoreMemAccess(IMG img) { return false; }
  virtual void HandlePreInstrumentTrace(TRACE trace);
  virtual void HandlePostInstrumentTrace(TRACE trace);
  virtual void HandleProgramStart();
  virtual void HandleProgramExit();
  virtual void HandleImageLoad(IMG img, Image *image);
  virtual void HandleImageUnload(IMG img, Image *image);
  virtual void HandleSyscallEntry(THREADID tid, CONTEXT *ctxt,
                                  SYSCALL_STANDARD std);
  virtual void HandleSyscallExit(THREADID tid, CONTEXT *ctxt,
                                 SYSCALL_STANDARD std);
  virtual void HandleSignalReceived(THREADID tid, INT32 sig,
                                    const CONTEXT *ctxt_from, CONTEXT *ctxt_to);
  virtual void HandleThreadStart();
  virtual void HandleThreadExit();
  virtual void HandleMain(THREADID tid, CONTEXT *ctxt);
  virtual void HandleThreadMain(THREADID tid, CONTEXT *ctxt);
  virtual void HandleBeforeMemRead(THREADID tid, Inst *inst, address_t addr,
                                   size_t size);
  virtual void HandleAfterMemRead(THREADID tid, Inst *inst, address_t addr,
                                  size_t size);
  virtual void HandleBeforeMemWrite(THREADID tid, Inst *inst, address_t addr,
                                    size_t size);
  virtual void HandleAfterMemWrite(THREADID tid, Inst *inst, address_t addr,
                                   size_t size);
  virtual void HandleBeforeAtomicInst(THREADID tid, Inst *inst, OPCODE opcode,
                                      address_t addr);
  virtual void HandleAfterAtomicInst(THREADID tid, Inst *inst, OPCODE opcode,
                                     address_t addr);
  virtual void HandleBeforeCall(THREADID tid, Inst *inst, address_t target);
  virtual void HandleAfterCall(THREADID tid, Inst *inst, address_t target,
                               address_t ret);
  virtual void HandleBeforeReturn(THREADID tid, Inst *inst, address_t target);
  virtual void HandleAfterReturn(THREADID tid, Inst *inst, address_t target);
  virtual void HandleBeforeWrapper(WrapperBase *wrapper);
  virtual void HandleAfterWrapper(WrapperBase *wrapper);

  void LockKernel() { kernel_lock_->Lock(); }
  void UnlockKernel() { kernel_lock_->Unlock(); }
  void Abort(const std::string &msg);
  Inst *GetInst(ADDRINT pc);
  void UpdateInstOpcode(Inst *inst, INS ins);
  void UpdateInstDebugInfo(Inst *inst, ADDRINT pc);
  void AddAnalyzer(Analyzer *analyzer);
  thread_id_t GetThdID(pthread_t thread);
  thread_id_t GetParent();
  thread_id_t Self() { return PIN_ThreadUid(); }
  timestamp_t GetThdClk(THREADID tid) { return tls_thd_clock_[tid]; }

  // TODO(jieyu): How to remove the dependency to the pthread_create wrapper.
  thread_id_t WaitForNewChild(WRAPPER_CLASS(PthreadCreate) *wrapper);
  void ReplacePthreadCreateWrapper(IMG img);
  void ReplacePthreadWrappers(IMG img);
  void ReplaceYieldWrappers(IMG img);
  void ReplaceMallocWrappers(IMG img);

  Mutex *kernel_lock_;
  Knob *knob_;
  Descriptor desc_;
  LogFile *debug_file_;
  StaticInfo *sinfo_;
  CallStackInfo *callstack_info_;
  AnalyzerContainer analyzers_;
  DebugAnalyzer *debug_analyzer_;
  volatile bool main_thread_started_;
  timestamp_t tls_thd_clock_[PIN_MAX_THREADS];
  address_t tls_read_addr_[PIN_MAX_THREADS];
  size_t tls_read_size_[PIN_MAX_THREADS];
  address_t tls_write_addr_[PIN_MAX_THREADS];
  size_t tls_write_size_[PIN_MAX_THREADS];
  address_t tls_read2_addr_[PIN_MAX_THREADS];
  address_t tls_atomic_addr_[PIN_MAX_THREADS];
  int tls_syscall_num_[PIN_MAX_THREADS];
  std::map<OS_THREAD_ID, Semaphore *> thd_create_sem_map_; // init = 0
  std::map<OS_THREAD_ID, thread_id_t> child_thd_map_;
  std::map<OS_THREAD_ID, thread_id_t> os_tid_map_;
  std::map<pthread_t, thread_id_t> pthread_handle_map_;
  thread_id_t main_thd_id_;

  static ExecutionControl *ctrl_;

 private:
  void InstrumentStartupFunc(IMG img);

  static void PIN_FAST_ANALYSIS_CALL __InstCount(THREADID tid);
  static void PIN_FAST_ANALYSIS_CALL __InstCount2(THREADID tid, UINT32 c);
  static void __Main(THREADID tid, CONTEXT *ctxt);
  static void __ThreadMain(THREADID tid, CONTEXT *ctxt);
  static void __BeforeMemRead(THREADID tid, Inst *inst, ADDRINT addr,
                              UINT32 size);
  static void __AfterMemRead(THREADID tid, Inst *inst);
  static void __BeforeMemWrite(THREADID tid, Inst *inst, ADDRINT addr,
                               UINT32 size);
  static void __AfterMemWrite(THREADID tid, Inst *inst);
  static void __BeforeMemRead2(THREADID tid, Inst *inst, ADDRINT addr,
                               UINT32 size);
  static void __AfterMemRead2(THREADID tid, Inst *inst);
  static void __BeforeAtomicInst(THREADID tid, Inst *inst, UINT32 opcode,
                                 ADDRINT addr);
  static void __AfterAtomicInst(THREADID tid, Inst *inst, UINT32 opcode);
  static void __BeforeCall(THREADID tid, Inst *inst, ADDRINT target);
  static void __AfterCall(THREADID tid, Inst *inst, ADDRINT target,
                          ADDRINT ret);
  static void __BeforeReturn(THREADID tid, Inst *inst, ADDRINT target);
  static void __AfterReturn(THREADID tid, Inst *inst, ADDRINT target);

  DISALLOW_COPY_CONSTRUCTORS(ExecutionControl);

  // Declare wrapper handlers.
  DECLARE_WRAPPER_HANDLER(PthreadCreate);
  DECLARE_WRAPPER_HANDLER(PthreadJoin);
  DECLARE_WRAPPER_HANDLER(PthreadMutexTryLock);
  DECLARE_WRAPPER_HANDLER(PthreadMutexLock);
  DECLARE_WRAPPER_HANDLER(PthreadMutexUnlock);
  DECLARE_WRAPPER_HANDLER(PthreadCondSignal);
  DECLARE_WRAPPER_HANDLER(PthreadCondBroadcast);
  DECLARE_WRAPPER_HANDLER(PthreadCondWait);
  DECLARE_WRAPPER_HANDLER(PthreadCondTimedwait);
  DECLARE_WRAPPER_HANDLER(PthreadBarrierInit);
  DECLARE_WRAPPER_HANDLER(PthreadBarrierWait);

  DECLARE_WRAPPER_HANDLER(Sleep);
  DECLARE_WRAPPER_HANDLER(Usleep);
  DECLARE_WRAPPER_HANDLER(SchedYield);

  DECLARE_WRAPPER_HANDLER(Malloc);
  DECLARE_WRAPPER_HANDLER(Calloc);
  DECLARE_WRAPPER_HANDLER(Realloc);
  DECLARE_WRAPPER_HANDLER(Free);
  DECLARE_WRAPPER_HANDLER(Valloc);
};

#endif


text:
package Atvaizdavimas;

import Intefaces.IMap;

public interface IDrawer {
    public void setMap(IMap map);
    public void setDrawText(boolean enable);
}


text:
import OMeter from './lib/OMeter';

export OMeter;


text:
package com.buy.tsg.service;

import java.util.List;

public interface AuthService {

	List<String> selectAuthByUsername(String username);

	List<String> selectAuthByRoleNames(List<String> roleNames);

}


text:
/**
 * \file recherche.c
 * \brief Recherche locale et globale d'un lieu
 * \author Amadou SY
 * \version 1.0
 * \date 13 Mars 2016
 */

#include <time.h>
#include <libxml/xpath.h>
#include <libxml/parser.h>
#include "constante.h"
#include "recherche.h"

/**
	* \param s nom du fichier
	* \author Amadou SY
	* \brief Obtient la requete en fonction des paramètres
	* \version 1.0
	* \desc on vérifie que le fichier est bien là
	* on regarde dans l'élement place la référence de boundigbox et on la renvoie
	* \date 13 Mars 2016
*/
void get_bounds( char *s, SDL_Surface *window,TTF_Font *font,SDL_Rect position)
{
	xmlDocPtr doc;
    xmlNodePtr racine,node;
    char* recherche="boundingbox";
	SDL_Color whiteColor;
	const char* bounds;
	char result[128]="le lieu chercher est : ";
	int result_fine=0;
	whiteColor.r =255;
	whiteColor.g =255;
	whiteColor.b =255;
    doc = xmlParseFile(s);
    SDL_BlitSurface(TTF_RenderUTF8_Blended(font,result, whiteColor),NULL,window,&position);
    position.y = position.y+20;
    if (doc == NULL)
    {
    	fprintf(stderr, "Document XML invalide\n");
    	exit(EXIT_FAILURE);
    }

    racine = xmlDocGetRootElement(doc);
    if (racine == NULL)
    {
		 fprintf(stderr, "Document XML vierge\n");
		 exit(EXIT_FAILURE);
	}
		node = racine->xmlChildrenNode;
		while (node != NULL)
		{
			if(node->type == XML_ELEMENT_NODE)
			{
				if(strcmp((const char*)node->name,(const char*)"place")==0)
				{
						 printf("%s",xmlGetProp(node,(const xmlChar*)recherche));
						 result_fine=1;
						 bounds = (const char*)xmlGetProp(node,(const xmlChar*)recherche);
						 SDL_BlitSurface(TTF_RenderUTF8_Blended(font,bounds, whiteColor),NULL,window,&position);

				}
			}
			node = node->next;
		}
	if(result_fine==0)
	  SDL_BlitSurface(TTF_RenderUTF8_Blended(font,"Not find....", whiteColor),NULL,window,&position);

	SDL_Flip(window);
    xmlFreeDoc(doc);

}
 /**
 	* \param param1 Premier paramètre de recherche
 	* \param param2 Deuxième paramètre de recherche
 	* \param param3 Premier paramètre de recherche
 	* \param param3 Premier paramètre de recherche
	* \author Amadou SY
	* \brief Obtient la requete en fonction des paramètres
  * \version 1.0
  * \date 13 Mars 2016
	*/
void get_datasearch_request(char *a, char *b, char *c, char *d, char *e, char *f, SDL_Surface *window,TTF_Font *font,SDL_Rect position)
{
	time_t t = time(NULL);
	char file[256] = "data_place-";
	char ext[10] = ".osm";
	char buffer[256];
	char commande[1024]="wget -O ";
	char nom[514]=" \"http://nominatim.openstreetmap.org/search?q=";
	char nom2[514]="&format=xml&polygon=1&addressdetails=1\"";
	char separate[3]="+";

 	strftime(buffer, sizeof(buffer), "%d-%m-%Y-%X", localtime(&t));
	strcat(file,((const char*)buffer));
	strcat(file,((const char*)ext));

	strcat(commande,((const char*)file));
	strcat(commande,((const char*)nom));
	if(strcmp(a,"")!=0)
	{
		strcat(commande,((const char*)a));
	}
	if(strcmp(b,"")!=0)
	{
		strcat(commande,((const char*)separate));
		strcat(commande,((const char*)b));
	}
	if(strcmp(c,"")!=0)
	{
		strcat(commande,((const char*)separate));
		strcat(commande,((const char*)c));
	}

	if(strcmp(d,"")!=0)
	{
		strcat(commande,((const char*)separate));
		strcat(commande,((const char*)d));
	}
	if(strcmp(e,"")!=0)
	{
		strcat(commande,((const char*)separate));
		strcat(commande,((const char*)e));
	}
	if(strcmp(f,"")!=0)
	{
		strcat(commande,((const char*)separate));
		strcat(commande,((const char*)f));
	}

	strcat(commande,((const char*)nom2));
	system(commande);
	get_bounds(file,window,font,position);
}


text:
(function(exports) {
  'use strict';

  if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
    module.exports = exports;
  } else {
    if (typeof define === 'function' && define.amd) {
      define([], function() {
        return exports;
      });
    } else {
      window.ryoc = exports;
    }
  }
})(
  (function() {
    function throwIt(message) {
      throw new TypeError(message);
    }

    function assertName(n) {
      return (n && (typeof(n) === typeof(''))) ? n : throwIt('Expected a string');
    }

    function assertFunction(fn) {
      return (fn && (fn instanceof Function)) ? fn : throwIt('Expected a function');
    }

    function assertObject(obj) {
      return (obj && (obj instanceof Object)) ? obj : throwIt('Expected an object');
    }

    var superDuperSecretMarker = {
      whoIsCalling: 'ryoc'
    };

    var Ryoc = function() {
      this.inherits = null;
      this.constructor = null;
      this.mixins = [];
      this.methods = {};
      this.properties = {};
    };
    var proto = Ryoc.prototype;
    proto.inherit = function(klass) {
      this.inherits = assertObject(klass);
      return this;
    };
    proto.construct = function(constructor) {
      this.constructor = assertFunction(constructor);
      return this;
    };
    proto.mixin = function() {
      for (var i = 0; i < arguments.length; ++i) {
        var mixin = arguments[i];
        if (mixin instanceof Array) {
          for (var j = 0; j < mixin.length; ++j) {
            this.mixin(mixin[j]);
          }
        } else if (mixin instanceof Object) {
          this.mixins.push(mixin);
        }
      }
      return this;
    };
    proto.method = function(name, method) {
      this.methods[assertName(name)] = assertFunction(method);
      return this;
    };
    proto.abstract = function(name) {
      return this.method(name, function() {
        throw new TypeError('[' + name + '] is abstract and must be overriden');
      });
    };
    proto.property = function(name, value, readonly) {
      name = assertName(name);
      this.properties[name] = {
        enumerable: true,
        configurable: true,
        writable: readonly == undefined ? true : !readonly,
        value: value
      };
      return this;
    };
    proto.getter = function(name, getter) {
      name = assertName(name);
      getter = assertFunction(getter);
      (this.properties[name] || (this.properties[name] = {
        enumerable: true,
        configurable: true
      })).get = getter;
      return this;
    };
    proto.setter = function(name, setter) {
      name = assertName(name);
      setter = assertFunction(setter);
      (this.properties[name] || (this.properties[name] = {
        enumerable: true,
        configurable: true
      })).set = setter;
      return this;
    };
    proto.toClass = function() {
      var self = this;
      var Klass = function() {
        if (!(this instanceof Klass)) {
          return new Klass(superDuperSecretMarker, arguments);
        }
        if (self.constructor) {
          var args = (arguments.length === 2) && (arguments[0] === superDuperSecretMarker) ? arguments[1] : arguments;
          self.constructor.apply(this, Array.prototype.slice.call(args, 0));
        }
      };

      var proto = Klass.prototype;
      if (this.inherits) {
        proto = Object.create(this.inherits instanceof Function ? this.inherits.prototype : this.inherits, {
          constructor: {
            value: Klass,
            enumerable: false,
            writable: true,
            configurable: true
          }
        });
        Klass.prototype = proto;
      }
      for (var i = 0; i < this.mixins.length; ++i) {
        var mixin = this.mixins[i];
        var memberNames = Object.getOwnPropertyNames(mixin);
        for (var j = 0; j < memberNames.length; ++j) {
          var name = memberNames[j];
          proto[name] = mixin[name];
        }
      }
      var methodNames = Object.getOwnPropertyNames(this.methods);
      for (var i = 0; i < methodNames.length; ++i) {
        var name = methodNames[i];
        var method = this.methods[name];
        proto[name] = method;
      }
      var propertyNames = Object.getOwnPropertyNames(this.properties);
      for (var i = 0; i < propertyNames.length; ++i) {
        var name = propertyNames[i];
        var property = this.properties[name];
        Object.defineProperty(proto, name, property);
      }
      return Klass;
    };
    return function() {
      return new Ryoc();
    }
  })()
);


text:
package me.lavecoral.lave.model.entity;

import javax.persistence.Entity;
import javax.persistence.Table;

@Entity
@Table(name = "permission")
public class Permission extends IdEntity {
    /**
     * 名称
     */
    private String name;
    /**
     * 描述
     */
    private String description;
    /**
     * 可访问的链接
     */
    private String url;
    /**
     * 口令
     */
    private String token;

    public String getName() {
        return name;
    }

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

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }
}


text:
namespace Magnesium.OpenGL
{
    public interface IGLImage : IMgImage
    {
        int Width { get; }
        int Height { get; }
        GLImageArraySubresource[] ArrayLayers { get; }
        int Levels { get; }
        int OriginalTextureId { get; }
        MgFormat Format { get; }
    }
}