text:
from collections import deque, OrderedDict

import numpy as np

from rlkit.core.eval_util import create_stats_ordered_dict
from rlkit.data_management.path_builder import PathBuilder
from rlkit.samplers.data_collector.base import StepCollector

class MdpStepCollector(StepCollector):
    def __init__(
            self,
            env,
            policy,
            max_num_epoch_paths_saved=None,
            render=False,
            render_kwargs=None,
    ):
        if render_kwargs is None:
            render_kwargs = {}
        self._env = env
        self._policy = policy
        self._max_num_epoch_paths_saved = max_num_epoch_paths_saved
        self._epoch_paths = deque(maxlen=self._max_num_epoch_paths_saved)
        self._render = render
        self._render_kwargs = render_kwargs

        self._num_steps_total = 0
        self._num_paths_total = 0
        self._obs = None  # cache variable

    def get_epoch_paths(self):
        return self._epoch_paths

    def end_epoch(self, epoch):
        self._epoch_paths = deque(maxlen=self._max_num_epoch_paths_saved)
        self._obs = None

    def get_diagnostics(self):
        path_lens = [len(path['actions']) for path in self._epoch_paths]
        stats = OrderedDict([
            ('num steps total', self._num_steps_total),
            ('num paths total', self._num_paths_total),
        ])
        stats.update(create_stats_ordered_dict(
            "path length",
            path_lens,
            always_show_all_stats=True,
        ))
        return stats

    def get_snapshot(self):
        return dict(
            env=self._env,
            policy=self._policy,
        )

    def collect_new_steps(
            self,
            max_path_length,
            num_steps,
            discard_incomplete_paths,
    ):
        for _ in range(num_steps):
            self.collect_one_step(max_path_length, discard_incomplete_paths)

    def collect_one_step(
            self,
            max_path_length,
            discard_incomplete_paths,
    ):
        if self._obs is None:
            self._start_new_rollout()

        action, agent_info = self._policy.get_action(self._obs)
        next_ob, reward, terminal, env_info = (
            self._env.step(action)
        )
        if self._render:
            self._env.render(**self._render_kwargs)
        terminal = np.array([terminal])
        reward = np.array([reward])
        # store path obs
        self._current_path_builder.add_all(
            observations=self._obs,
            actions=action,
            rewards=reward,
            next_observations=next_ob,
            terminals=terminal,
            agent_infos=agent_info,
            env_infos=env_info,
        )
        if terminal or len(self._current_path_builder) >= max_path_length:
            self._handle_rollout_ending(max_path_length,
                                        discard_incomplete_paths)
            self._start_new_rollout()
        else:
            self._obs = next_ob

    def _start_new_rollout(self):
        self._current_path_builder = PathBuilder()
        self._obs = self._env.reset()

    def _handle_rollout_ending(
            self,
            max_path_length,
            discard_incomplete_paths
    ):
        if len(self._current_path_builder) > 0:
            path = self._current_path_builder.get_all_stacked()
            path_len = len(path['actions'])
            if (
                    path_len != max_path_length
                    and not path['terminals'][-1]
                    and discard_incomplete_paths
            ):
                return
            self._epoch_paths.append(path)
            self._num_paths_total += 1
            self._num_steps_total += path_len

class GoalConditionedStepCollector(StepCollector):
    def __init__(
            self,
            env,
            policy,
            max_num_epoch_paths_saved=None,
            render=False,
            render_kwargs=None,
            observation_key='observation',
            desired_goal_key='desired_goal',
    ):
        if render_kwargs is None:
            render_kwargs = {}
        self._env = env
        self._policy = policy
        self._max_num_epoch_paths_saved = max_num_epoch_paths_saved
        self._epoch_paths = deque(maxlen=self._max_num_epoch_paths_saved)
        self._render = render
        self._render_kwargs = render_kwargs
        self._observation_key = observation_key
        self._desired_goal_key = desired_goal_key

        self._num_steps_total = 0
        self._num_paths_total = 0
        self._obs = None  # cache variable

    def get_epoch_paths(self):
        return self._epoch_paths

    def end_epoch(self, epoch):
        self._epoch_paths = deque(maxlen=self._max_num_epoch_paths_saved)
        self._obs = None

    def get_diagnostics(self):
        path_lens = [len(path['actions']) for path in self._epoch_paths]
        stats = OrderedDict([
            ('num steps total', self._num_steps_total),
            ('num paths total', self._num_paths_total),
        ])
        stats.update(create_stats_ordered_dict(
            "path length",
            path_lens,
            always_show_all_stats=True,
        ))
        return stats

    def get_snapshot(self):
        return dict(
            env=self._env,
            policy=self._policy,
            observation_key=self._observation_key,
            desired_goal_key=self._desired_goal_key,
        )

    def start_collection(self):
        self._start_new_rollout()

    def end_collection(self):
        epoch_paths = self.get_epoch_paths()
        return epoch_paths

    def collect_new_steps(
            self,
            max_path_length,
            num_steps,
            discard_incomplete_paths,
    ):
        for _ in range(num_steps):
            self.collect_one_step(max_path_length, discard_incomplete_paths)

    def collect_one_step(
            self,
            max_path_length,
            discard_incomplete_paths,
    ):
        if self._obs is None:
            self._start_new_rollout()

        new_obs = np.hstack((
            self._obs[self._observation_key],
            self._obs[self._desired_goal_key],
        ))
        action, agent_info = self._policy.get_action(new_obs)
        next_ob, reward, terminal, env_info = (
            self._env.step(action)
        )
        if self._render:
            self._env.render(**self._render_kwargs)
        terminal = np.array([terminal])
        reward = np.array([reward])
        # store path obs
        self._current_path_builder.add_all(
            observations=self._obs,
            actions=action,
            rewards=reward,
            next_observations=next_ob,
            terminals=terminal,
            agent_infos=agent_info,
            env_infos=env_info,
        )
        if terminal or len(self._current_path_builder) >= max_path_length:
            self._handle_rollout_ending(max_path_length,
                                        discard_incomplete_paths)
            self._start_new_rollout()
        else:
            self._obs = next_ob

    def _start_new_rollout(self):
        self._current_path_builder = PathBuilder()
        self._obs = self._env.reset()

    def _handle_rollout_ending(
            self,
            max_path_length,
            discard_incomplete_paths
    ):
        if len(self._current_path_builder) > 0:
            path = self._current_path_builder.get_all_stacked()
            path_len = len(path['actions'])
            if (
                    path_len != max_path_length
                    and not path['terminals'][-1]
                    and discard_incomplete_paths
            ):
                return
            self._epoch_paths.append(path)
            self._num_paths_total += 1
            self._num_steps_total += path_len

class ObsDictStepCollector(StepCollector):
    def __init__(
            self,
            env,
            policy,
            max_num_epoch_paths_saved=None,
            render=False,
            render_kwargs=None,
            observation_key='observation',
    ):
        if render_kwargs is None:
            render_kwargs = {}
        self._env = env
        self._policy = policy
        self._max_num_epoch_paths_saved = max_num_epoch_paths_saved
        self._epoch_paths = deque(maxlen=self._max_num_epoch_paths_saved)
        self._render = render
        self._render_kwargs = render_kwargs
        self._observation_key = observation_key

        self._num_steps_total = 0
        self._num_paths_total = 0
        self._obs = None  # cache variable

    def get_epoch_paths(self):
        return self._epoch_paths

    def end_epoch(self, epoch):
        self._epoch_paths = deque(maxlen=self._max_num_epoch_paths_saved)
        self._obs = None

    def get_diagnostics(self):
        path_lens = [len(path['actions']) for path in self._epoch_paths]
        stats = OrderedDict([
            ('num steps total', self._num_steps_total),
            ('num paths total', self._num_paths_total),
        ])
        stats.update(create_stats_ordered_dict(
            "path length",
            path_lens,
            always_show_all_stats=True,
        ))
        return stats

    def get_snapshot(self):
        return dict(
            env=self._env,
            policy=self._policy,
            observation_key=self._observation_key,
        )

    def start_collection(self):
        self._start_new_rollout()

    def end_collection(self):
        epoch_paths = self.get_epoch_paths()
        return epoch_paths

    def collect_new_steps(
            self,
            max_path_length,
            num_steps,
            discard_incomplete_paths,
    ):
        for _ in range(num_steps):
            self.collect_one_step(max_path_length, discard_incomplete_paths)

    def collect_one_step(
            self,
            max_path_length,
            discard_incomplete_paths,
    ):
        if self._obs is None:
            self._start_new_rollout()

        new_obs = self._obs[self._observation_key]
        action, agent_info = self._policy.get_action(new_obs)
        next_ob, reward, terminal, env_info = (
            self._env.step(action)
        )
        if self._render:
            self._env.render(**self._render_kwargs)
        terminal = np.array([terminal])
        reward = np.array([reward])
        # store path obs
        self._current_path_builder.add_all(
            observations=self._obs,
            actions=action,
            rewards=reward,
            next_observations=next_ob,
            terminals=terminal,
            agent_infos=agent_info,
            env_infos=env_info,
        )
        if terminal or len(self._current_path_builder) >= max_path_length:
            self._handle_rollout_ending(max_path_length,
                                        discard_incomplete_paths)
            self._start_new_rollout()
        else:
            self._obs = next_ob

    def _start_new_rollout(self):
        self._current_path_builder = PathBuilder()
        self._obs = self._env.reset()

    def _handle_rollout_ending(
            self,
            max_path_length,
            discard_incomplete_paths
    ):
        if len(self._current_path_builder) > 0:
            path = self._current_path_builder.get_all_stacked()
            path_len = len(path['actions'])
            if (
                    path_len != max_path_length
                    and not path['terminals'][-1]
                    and discard_incomplete_paths
            ):
                return
            self._epoch_paths.append(path)
            self._num_paths_total += 1
            self._num_steps_total += path_len


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

var http   = require('http'),
    osenv  = require('osenv'),
    path   = require('path'),
    fs     = require('fs'),
    temp   = path.join(osenv.tmpdir(), 'plugman'),
    shell  = require('shelljs'),
    child_process = require('child_process'),
    plugins = require('../../src/util/plugins'),
    xml_helpers = require('../../src/util/xml-helpers');

describe('plugins utility module', function(){
    describe('clonePluginGitRepo', function(){
        var fake_id = 'VillageDrunkard';
        var execSpy, cp_spy, xml_spy, done;
        beforeEach(function() {
            execSpy = spyOn(child_process, 'exec').andCallFake(function(cmd, opts, cb) {
                if (!cb) cb = opts;
                cb(null, 'git output');
            });
            spyOn(shell, 'which').andReturn(true);
            cp_spy = spyOn(shell, 'cp');
            xml_spy = spyOn(xml_helpers, 'parseElementtreeSync').andReturn({
                getroot:function() {
                    return {
                        attrib:{id:fake_id}
                    };
                }
            });
            done = false;
        });
        it('should shell out to git clone with correct arguments', function(){
            var plugin_git_url = 'https://github.com/imhotep/ChildBrowser';
            var callback = jasmine.createSpy();

            runs(function() {
                plugins.clonePluginGitRepo(plugin_git_url, temp, '.', undefined)
                .then(function(val) { done = val; }, function(err) { done = err; });
            });
            waitsFor(function() { return done; }, 'promise never resolved', 500);
            runs(function() {
                expect(execSpy).toHaveBeenCalled();
                var git_clone_regex = new RegExp('^git clone "' + plugin_git_url + '" ".*"$', 'gi');
                expect(execSpy.mostRecentCall.args[0]).toMatch(git_clone_regex);

                expect(done).toMatch(new RegExp(path.sep + fake_id + '$'));
            });
        });
        it('should take into account subdirectory argument when copying over final repository into plugins+plugin_id directory', function() {
            var plugin_git_url = 'https://github.com/imhotep/ChildBrowser';
            var fake_subdir = 'TheBrainRecoilsInHorror';
            runs(function() {
                plugins.clonePluginGitRepo(plugin_git_url, temp, fake_subdir)
                .then(function(val) { done = val || true; }, function(err) { done = err; });
            });
            waitsFor(function() { return done; }, 'promise never resolved', 500);
            runs(function() {
                var expected_subdir_cp_path = new RegExp(fake_subdir + '[\\\\\\/]\\*$', 'gi');
                expect(cp_spy.mostRecentCall.args[1]).toMatch(expected_subdir_cp_path);
                expect(cp_spy.mostRecentCall.args[2]).toEqual(path.join(temp, fake_id));
            });
        });
    });
});

redpajama_set_name: RedPajamaGithub


text:
package lesson.oop.types;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;

public class FrameEx2 extends JFrame {

    private DrawPanel panel;

    public FrameEx2() {
        setTitle("My app");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(640, 480);

        panel = new DrawPanel() {
            @Override
            public void paint(Graphics g) {
                super.paint(g);
                g.drawRect(0, 0, 10, 50);
            }
        };

        // определить свой класс панели унаследованной от JPanel
        // определить класс Point
        // внутри класса своей панели хранить список List точек

        panel.setBackground(new Color(208, 196, 255));
        add(panel);

        panel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                //JOptionPane.showMessageDialog(null, "Click! : "+e.getPoint());
                //Graphics g = panel.getGraphics();
                //g.fillOval(e.getX(), e.getY(), 10, 10);

                panel.addPoint( new Point(/*e.getX, e.getY*/) );
                panel.repaint();
            }
        });
    }

    public static void main(String[] args) {
        FrameEx2 frameEx2 = new FrameEx2();
        frameEx2.setVisible(true);
    }

}

class Point {
    // x
    // y
}

class DrawPanel extends JPanel {

    private ArrayList<Point> points;

    public void addPoint(Point p) {
        // добавить в список
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);

        // пройти по списку и нарисовать все точки

    }
}


text:
<?php
/**
 * CosmessSessionComponent. Provides to Custome Sessions from the Controller layer
 */

App::uses('SessionComponent', 'Controller/Component');
App::uses('CakeSession', 'Model/Datasource');
App::uses('StrUtil', 'Cosmess.Lib');

class CosmessSessionComponent extends SessionComponent {

	public $controller = false;

	public $components = array('Session');

	public function __construct(ComponentCollection $collection, $settings) {
		parent::__construct($collection, $settings);
	}

	public function startup(Controller $controller) {
		$controller->Session = $this;
	}

/**
 * Custome setFlash with parameters bootstrap / foundation
 *
 * @params['type'] : boolean for success / error class message
 */
	public function setFlash($message, $element = 'default', $params = array(), $key = 'flash') {
		$StrUtil = new StrUtil;
		$flashType = Configure::read('Cosmess.Params.flashType');
		if (!empty($flashType)) {
			switch ($flashType) {
				case 'foundation':
					$success = Configure::read('Cosmess.Class.foundation.success');
					$error = Configure::read('Cosmess.Class.foundation.error');
					$info = Configure::read('Cosmess.Class.foundation.info');
					break;
				case 'bootstrap':
					$success = Configure::read('Cosmess.Class.bootstrap.success');
					$error = Configure::read('Cosmess.Class.bootstrap.error');
					$info = Configure::read('Cosmess.Class.bootstrap.info');
					break;
				default:
					$success = 'success';
					$error = 'error';
					$info = 'info';
					break;
			}
			if (isset($params['class'])) {
				$match = $StrUtil->findMatch($params['class']);
				switch ($match) {
					case 'success':
						$params['class'] = $success;
						break;
					case 'error':
						$params['class'] = $error;
						break;
					case 'info':
						$params['class'] = $info;
						break;
				}
			} else {
				$params = $params;
			}
		} else {
			$params = $params;
		}
		CakeSession::write('Message.' . $key, compact('message', 'element', 'params'));
	}
}


text:
using namespace std;

#define SAFE_RELEASE(x)		if (x) { x->Release(); x = NULL; }

const VideoProcAmpProperty IProp[] = {VideoProcAmp_Brightness,			//Index 0
									VideoProcAmp_Contrast,				//Index 1
									VideoProcAmp_Hue,					//Index 2
								    VideoProcAmp_Saturation,			//Index 3
									VideoProcAmp_Sharpness,				//Index 4
									VideoProcAmp_Gamma,					//Index 5
									VideoProcAmp_ColorEnable,			//Index 6
 									VideoProcAmp_WhiteBalance,			//Index 7
									VideoProcAmp_BacklightCompensation	//Index 8
									//VideoProcAmp_Gain					//Index 9
};

const CameraControlProperty CProp[] = {CameraControl_Pan,		//Index 0
									CameraControl_Tilt,			//Index 1
									CameraControl_Roll,			//Index 2
									CameraControl_Zoom,			//Index 3
									CameraControl_Exposure,		//Index 4
									CameraControl_Iris,			//Index 5
									CameraControl_Focus,		//Index 6
									CameraControl_Flash			//Index 7
};

typedef enum tagPropType
{
	IMG,
	CAM,
	CUS
}PropType;

typedef enum tagCameraCustomProperty
{
	CUS_PROPERTY_AIMING,
	CUS_PROPERTY_TEST
}CameraCustomProperty;

typedef struct tagCameraConfig
{
	wstring sCamID;
	HWND hwndOwnerWnd;
	RECT rc;
    BOOL bIsStillEnb;
	BOOL bIsPrvEnb;
	BOOL bIsCapEnb;
    BOOL bIsAudioEnb;
} CamConfig;

typedef struct tagImgFmt
{
	INT nMaxWidth;
	INT nMaxHeight;
	wstring wsColorFmt;
	LONGLONG qwMaxFrameRate;
}ImgFmt;

typedef struct tagImageProptable
{
	VideoProcAmpProperty vProp;
	LONG plVal;
	LONG plMin;
	LONG plMax;
	LONG plDelta;
	LONG plDef;
	LONG plFlag;
	HRESULT hr;
} ImgPropTbl;

typedef struct tagCamProptable
{
	CameraControlProperty p;
	LONG plVal;
	LONG plMin;
	LONG plMax;
	LONG plDelta;
	LONG plDef;
	LONG plFlag;
	HRESULT hr;
}CamPropTbl;

typedef struct tagCusProptable
{
	CameraCustomProperty p;
	LONG plVal;
	LONG plMin;
	LONG plMax;
	LONG plDelta;
	LONG plDef;
	LONG plFlag;
	HRESULT hr;
}CusPropTbl;

typedef struct tagMEDIA_SUBTYPE_LIST
{
	wstring wsClrName;
	const GUID *pMSubType;
}MEDIA_SUBTYPE_LIST;

typedef struct tagCamCapability
{
	INT nIndex;
	ImageRes tImgRes;
	wstring wsColorFmt;
	LONGLONG qwMaxFrameRate;
}CamCapability;

// This class is exported from the DShowCamModule.dll
typedef class CDShowCamModule
{
public:
	CDShowCamModule(void);
	~CDShowCamModule(void);

	//-----------------------------
	BOOL FindFirstCam(wstring* pwsCamID);
	//BOOL FindNextCam(wstring* pwsCamID);
	HRESULT InitFilterGrp();
	BOOL BuildFilterGrp(CamConfig* ptCamcfg);
	BOOL FreeFilterGrp();
	BOOL ReBuildGrp();
	BOOL RunGrp();
	BOOL ReleaseGrp();
	BOOL ResizePreview(int width, int height);
	BOOL StopGrp();
	BOOL PauseGrp();
	HRESULT Get_PropRng(PropType ePType, HANDLE hPropTbl);
	HRESULT Get_PropVal(PropType ePType, HANDLE hPropTbl);
	HRESULT Set_PropVal(PropType ePType, HANDLE hPropTbl);
	HRESULT CaptureStill(WCHAR *filename);
	HRESULT CaptureStill(wstring wsSFName);
	HRESULT Set_VdoFileName(wstring wsVFName);
	HRESULT ShowPreview();
	HRESULT HidePreview();
	HRESULT ClosePreview();
	HRESULT StartCapture();
	HRESULT StopCapture();
	HRESULT Set_Flip(BOOL bIsHori);
	HRESULT EnumFirstCap(PinType ePType, ImgFmt* ptIFmt, INT* pnNoOfCap);
	HRESULT EnumOtherCap(PinType ePType, ImgFmt* ptIFmt, INT nNoOfCap);
	HRESULT Set_Resolution(ImageRes* ptRes, PinType ePType, BOOL bAutoControlGraph);
	HRESULT Set_ColorFmt(ImageRes* ptRes, wstring* pwsClrFmt, PinType ePType);
	HRESULT Set_FrameRate(LONGLONG qwFrmRate, PinType ePType);

	BOOL Get_LastError(LONG* plErrno);
	BOOL Cleanup();
	CamPropTbl m_tCamTblFlash;
	ImgFmt* m_tStillImgFmtArray;
	ImgPropTbl m_tImgTblBrt;
	int m_nStillResCnt;
	BOOL bAutoFlash;
	CameraSetting m_tImgRes;
	void EnablePowerKeyIAC(BOOL bEnablePowerKey);
	static void RegistryNotifyCallbackFuncIAC(HREGNOTIFY hNotify, DWORD dwUserData, const PBYTE pData, const UINT cbData);
	void EnablePowerKeyMPA(BOOL bEnablePowerKey);
	static void RegistryNotifyCallbackFuncMPA(HREGNOTIFY hNotify, DWORD dwUserData, const PBYTE pData, const UINT cbData);
	BOOL IsIACDEvice();
	//----------------------------

private:
	HRESULT SetupStill();
	HRESULT UndoSetupStill();
	HRESULT SetupPreview(HWND OwnerWnd, RECT rc);
	HRESULT UndoSetupPreview();
	HRESULT Cus_GetRange(CameraCustomProperty eProp, LONG* plMin, LONG* plMax, LONG* plDelta, LONG* plDef);
	HRESULT Cus_Get(CameraCustomProperty eProp, LONG* plVal);
	HRESULT Cus_Set(CameraCustomProperty eProp, LONG plVal);
	HRESULT SetupFlip();

	DWORD GunGet(DWORD* value);
	DWORD GunSet(DWORD value);
	HRESULT InitVdoCapFilter(ImageRes* ptRes, PinType ePType); // MPA3

private:
	//-------------
	//HANDLE	m_hCamHdl;
	LONG m_lErrno;
	CamConfig m_tCamcfg;
	IGraphBuilder* m_pGraphBuilder;
	ICaptureGraphBuilder2* m_pCaptureGraphBuilder;
	IMediaControl* m_pMediaControl;
	//IVideoWindow* m_pViewWindow;
	IMediaEventEx* m_pMediaEventEx;
	IMediaSeeking* m_pMediaSeeking;
	IBaseFilter* m_pVideoCaptureFilter;
	IBaseFilter* m_pAudioCaptureFilter;
	IAMVideoProcAmp* m_pImgCtrl;
	IAMCameraControl* m_pCamCtrl;
	IAMStreamConfig* m_pStrConf;
	IBaseFilter* m_pMux;
	IFileSinkFilter* m_pSink;
	IBaseFilter* m_pVideoEncoder;
	IDMOWrapperFilter* m_pVideoWrapperFilter;
	IBaseFilter* m_pStillSink;
	IAMVideoControl* m_pVideoCtrl;
	IPin* m_pPrvPin;
	wstring m_wsVFName;
	IBaseFilter* m_pVideoRenderer;
	IBaseFilter* m_pColorConverter; // MPA3
	INT m_nFileAutoCnt;
	BOOL m_bInited;
	//CamCapability* m_ptCamCap[3];
	//-------------

}VIDEOPROPERTY, *PVIDEOPROPERTY;

typedef struct _jpegMetadata
{
	LONG ulLatitude[6];
	LONG ulLongitude[6];
	CHAR szDateTime[20];
}JpegMetadata;

//extern DSHOWCAM_API int nDShowCamModule;
int Invoke(HWND hWnd, RECT rc, wstring Cam);
bool UpdateImageFileWithMetaData(LPCTSTR lpszPictureFilePath, JpegMetadata *jmMetadata);
bool ReadImageFileForMetaData(LPCTSTR lpszPictureFilePath, JpegMetadata *jmMetadata);
bool Degrees2DegreesMinutesSeconds(double coordinate, LONG *rationalCoordinate);
bool DegreesMinutesSeconds2Degrees(double *coordinate, LONG *rationalCoordinate);
IStream* CreateStreamByFileName(const CString& strFileName);
void WorkerThread();

extern "C"
{
	DSHOWCAM_API int InitDShow(int hWnd, wchar_t* CamId, RECT& rc);
	DSHOWCAM_API int Pause();
	DSHOWCAM_API int SetBrightness(CameraSetting setting);
	DSHOWCAM_API int GetMetaDataFromImage(WCHAR *filename, double *latitude, double *longitude, LPTSTR datetime);
	DSHOWCAM_API int SetMetaDataToImage(double latitude, double longitude, LPTSTR filename);
}


text:
from otp.ai.AIBaseGlobal import *
import random
from toontown.suit import SuitDNA
from direct.directnotify import DirectNotifyGlobal
from toontown.suit import DistributedSuitAI
import SuitBuildingGlobals
import types

class SuitPlannerInteriorAI:
    notify = DirectNotifyGlobal.directNotify.newCategory('SuitPlannerInteriorAI')

    def __init__(self, numFloors, bldgLevel, bldgTrack, zone):
        self.dbg_4SuitsPerFloor = config.GetBool('4-suits-per-floor', 0)
        self.dbg_1SuitPerFloor = config.GetBool('1-suit-per-floor', 0)
        self.zoneId = zone
        self.numFloors = numFloors
        self.respectInvasions = 1
        dbg_defaultSuitName = config.GetString('suit-type', 'random')
        if dbg_defaultSuitName == 'random':
            self.dbg_defaultSuitType = None
        else:
            self.dbg_defaultSuitType = SuitDNA.getSuitType(dbg_defaultSuitName)
        if isinstance(bldgLevel, types.StringType):
            self.notify.warning('bldgLevel is a string!')
            bldgLevel = int(bldgLevel)
        self._genSuitInfos(numFloors, bldgLevel, bldgTrack)
        return

    def __genJoinChances(self, num):
        joinChances = []
        for currChance in range(num):
            joinChances.append(random.randint(1, 100))

        joinChances.sort(cmp)
        return joinChances

    def _genSuitInfos(self, numFloors, bldgLevel, bldgTrack):
        self.suitInfos = []
        self.notify.debug('\n\ngenerating suitsInfos with numFloors (' + str(numFloors) + ') bldgLevel (' + str(bldgLevel) + '+1) and bldgTrack (' + str(bldgTrack) + ')')
        for currFloor in range(numFloors):
            infoDict = {}
            lvls = self.__genLevelList(bldgLevel, currFloor, numFloors)
            activeDicts = []
            if self.dbg_4SuitsPerFloor:
                numActive = 4
            else:
                numActive = random.randint(1, min(4, len(lvls)))
            if currFloor + 1 == numFloors and len(lvls) > 1:
                origBossSpot = len(lvls) - 1
                if numActive == 1:
                    newBossSpot = numActive - 1
                else:
                    newBossSpot = numActive - 2
                tmp = lvls[newBossSpot]
                lvls[newBossSpot] = lvls[origBossSpot]
                lvls[origBossSpot] = tmp
            bldgInfo = SuitBuildingGlobals.SuitBuildingInfo[bldgLevel]
            if len(bldgInfo) > SuitBuildingGlobals.SUIT_BLDG_INFO_REVIVES:
                revives = bldgInfo[SuitBuildingGlobals.SUIT_BLDG_INFO_REVIVES][0]
            else:
                revives = 0
            for currActive in range(numActive - 1, -1, -1):
                level = lvls[currActive]
                type = self.__genNormalSuitType(level)
                activeDict = {}
                activeDict['type'] = type
                activeDict['track'] = bldgTrack
                activeDict['level'] = level
                activeDict['revives'] = revives
                activeDicts.append(activeDict)

            infoDict['activeSuits'] = activeDicts
            reserveDicts = []
            numReserve = len(lvls) - numActive
            joinChances = self.__genJoinChances(numReserve)
            for currReserve in range(numReserve):
                level = lvls[currReserve + numActive]
                type = self.__genNormalSuitType(level)
                reserveDict = {}
                reserveDict['type'] = type
                reserveDict['track'] = bldgTrack
                reserveDict['level'] = level
                reserveDict['revives'] = revives
                reserveDict['joinChance'] = joinChances[currReserve]
                reserveDicts.append(reserveDict)

            infoDict['reserveSuits'] = reserveDicts
            self.suitInfos.append(infoDict)

    def __genNormalSuitType(self, lvl):
        if self.dbg_defaultSuitType != None:
            return self.dbg_defaultSuitType
        return SuitDNA.getRandomSuitType(lvl)

    def __genLevelList(self, bldgLevel, currFloor, numFloors):
        bldgInfo = SuitBuildingGlobals.SuitBuildingInfo[bldgLevel]
        if self.dbg_1SuitPerFloor:
            return [1]
        elif self.dbg_4SuitsPerFloor:
            return [5,
             6,
             7,
             10]
        lvlPoolRange = bldgInfo[SuitBuildingGlobals.SUIT_BLDG_INFO_LVL_POOL]
        maxFloors = bldgInfo[SuitBuildingGlobals.SUIT_BLDG_INFO_FLOORS][1]
        lvlPoolMults = bldgInfo[SuitBuildingGlobals.SUIT_BLDG_INFO_LVL_POOL_MULTS]
        floorIdx = min(currFloor, maxFloors - 1)
        lvlPoolMin = lvlPoolRange[0] * lvlPoolMults[floorIdx]
        lvlPoolMax = lvlPoolRange[1] * lvlPoolMults[floorIdx]
        lvlPool = random.randint(int(lvlPoolMin), int(lvlPoolMax))
        lvlMin = bldgInfo[SuitBuildingGlobals.SUIT_BLDG_INFO_SUIT_LVLS][0]
        lvlMax = bldgInfo[SuitBuildingGlobals.SUIT_BLDG_INFO_SUIT_LVLS][1]
        self.notify.debug('Level Pool: ' + str(lvlPool))
        lvlList = []
        while lvlPool >= lvlMin:
            newLvl = random.randint(lvlMin, min(lvlPool, lvlMax))
            lvlList.append(newLvl)
            lvlPool -= newLvl

        if currFloor + 1 == numFloors:
            bossLvlRange = bldgInfo[SuitBuildingGlobals.SUIT_BLDG_INFO_BOSS_LVLS]
            newLvl = random.randint(bossLvlRange[0], bossLvlRange[1])
            lvlList.append(newLvl)
        lvlList.sort(cmp)
        self.notify.debug('LevelList: ' + repr(lvlList))
        return lvlList

    def __setupSuitInfo(self, suit, bldgTrack, suitLevel, suitType):
        suitName, specialSuit = simbase.air.suitInvasionManager.getInvadingCog()
        if suitName and self.respectInvasions:
            suitType = SuitDNA.getSuitType(suitName)
            bldgTrack = SuitDNA.getSuitDept(suitName)
            suitLevel = min(max(suitLevel, suitType), suitType + 4)
        if not self.respectInvasions:
            specialSuit = 0
        dna = SuitDNA.SuitDNA()
        dna.newSuitRandom(suitType, bldgTrack)
        suit.dna = dna
        self.notify.debug('Creating suit type ' + suit.dna.name + ' of level ' + str(suitLevel) + ' from type ' + str(suitType) + ' and track ' + str(bldgTrack))
        suit.setLevel(suitLevel)
        return specialSuit

    def __genSuitObject(self, suitZone, suitType, bldgTrack, suitLevel, revives = 0):
        newSuit = DistributedSuitAI.DistributedSuitAI(simbase.air, None)
        skel = self.__setupSuitInfo(newSuit, bldgTrack, suitLevel, suitType)
        if skel == 1:
            newSuit.setSkelecog(1)
        elif skel == 2:
            newSuit.setSkeleRevives(1)
        newSuit.generateWithRequired(suitZone)
        newSuit.node().setName('suit-%s' % newSuit.doId)
        return newSuit

    def myPrint(self):
        self.notify.info('Generated suits for building: ')
        for currInfo in suitInfos:
            whichSuitInfo = suitInfos.index(currInfo) + 1
            self.notify.debug(' Floor ' + str(whichSuitInfo) + ' has ' + str(len(currInfo[0])) + ' active suits.')
            for currActive in range(len(currInfo[0])):
                self.notify.debug('  Active suit ' + str(currActive + 1) + ' is of type ' + str(currInfo[0][currActive][0]) + ' and of track ' + str(currInfo[0][currActive][1]) + ' and of level ' + str(currInfo[0][currActive][2]))

            self.notify.debug(' Floor ' + str(whichSuitInfo) + ' has ' + str(len(currInfo[1])) + ' reserve suits.')
            for currReserve in range(len(currInfo[1])):
                self.notify.debug('  Reserve suit ' + str(currReserve + 1) + ' is of type ' + str(currInfo[1][currReserve][0]) + ' and of track ' + str(currInfo[1][currReserve][1]) + ' and of lvel ' + str(currInfo[1][currReserve][2]) + ' and has ' + str(currInfo[1][currReserve][3]) + '% join restriction.')

    def genFloorSuits(self, floor):
        suitHandles = {}
        floorInfo = self.suitInfos[floor]
        activeSuits = []
        for activeSuitInfo in floorInfo['activeSuits']:
            suit = self.__genSuitObject(self.zoneId, activeSuitInfo['type'], activeSuitInfo['track'], activeSuitInfo['level'], activeSuitInfo['revives'])
            activeSuits.append(suit)

        suitHandles['activeSuits'] = activeSuits
        reserveSuits = []
        for reserveSuitInfo in floorInfo['reserveSuits']:
            suit = self.__genSuitObject(self.zoneId, reserveSuitInfo['type'], reserveSuitInfo['track'], reserveSuitInfo['level'], reserveSuitInfo['revives'])
            reserveSuits.append((suit, reserveSuitInfo['joinChance']))

        suitHandles['reserveSuits'] = reserveSuits
        return suitHandles

    def genSuits(self):
        suitHandles = []
        for floor in range(len(self.suitInfos)):
            floorSuitHandles = self.genFloorSuits(floor)
            suitHandles.append(floorSuitHandles)

        return suitHandles


text:
"""Òarge-sized Model Hyperparameter configuration."""
from pegasus.flax.configs import pegasus_large as pegasus_large_config

def get_config():
  """Get large-sized PEGASUS-X hyperparameter configuration."""

  # Load base config
  config = pegasus_large_config.get_config()

  config.encoder.encoder_type = "global_local"
  config.encoder.global_local.num_global_tokens = 128
  config.encoder.global_local.block_size = 512
  config.decoder.decoder_type = "extended"
  config.pegasus_decoder_shift_after_embed = False
  config.encoder.global_local.stagger_local_blocks = True
  config.max_input_length = 16384

  return config


text:
/* Authors: Darby Lim, Hye-Jong KIM, Ryan Shim, Yong-Ho Na */

#ifndef LINEAR_CUSTOM_TRAJECTORY_H_
#define LINEAR_CUSTOM_TRAJECTORY_H_

#if defined(__OPENCR__)
  #include <RobotisManipulator.h>
#else
  #include <robotis_manipulator/robotis_manipulator.h>
#endif

using namespace robotis_manipulator;
using namespace Eigen;

namespace linear_custom_trajectory
{

enum AXIS{
	X_AXIS,
	Y_AXIS,
	Z_AXIS,
};

/*****************************************************************************
** Line
*****************************************************************************/
class Line : public robotis_manipulator::CustomTaskTrajectory
{
private:
  TaskWaypoint start_pose_;
  TaskWaypoint goal_pose_;

  double acc_dec_time_;
  double move_time_;
  std::vector<double> vel_max_;

public:
	Line() {}
	virtual ~Line() {}

  void initLine(double move_time, TaskWaypoint start, TaskWaypoint delta);
  TaskWaypoint drawLine(double time_var);

  virtual void setOption(const void *arg);
  virtual void makeTaskTrajectory(double move_time, TaskWaypoint start, const void *arg);
  virtual TaskWaypoint getTaskWaypoint(double tick);
};

/*****************************************************************************
** Circle
*****************************************************************************/
class Circle : public robotis_manipulator::CustomTaskTrajectory
{
private:
  robotis_manipulator::MinimumJerk path_generator_;
  VectorXd coefficient_;

  TaskWaypoint start_pose_;
  TaskWaypoint goal_pose_;

  double radius_;
  double start_angular_position_;
  double revolution_;

public:
	Circle() {}
	virtual ~Circle() {}

  void initCircle(double move_time, TaskWaypoint start, double radius, double revolution, double start_angular_position);
  TaskWaypoint drawCircle(double time_var);

  virtual void setOption(const void *arg);
  virtual void makeTaskTrajectory(double move_time, TaskWaypoint start, const void *arg);
  virtual TaskWaypoint getTaskWaypoint(double tick);
};

/*****************************************************************************
** Rhombus
*****************************************************************************/
class Rhombus : public robotis_manipulator::CustomTaskTrajectory
{
private:
  robotis_manipulator::MinimumJerk path_generator_;
  VectorXd coefficient_;

  TaskWaypoint start_pose_;
  TaskWaypoint goal_pose_;

  double radius_;
  double start_angular_position_;
  double revolution_;

public:
	Rhombus() {}
	virtual ~Rhombus() {}

  void initRhombus(double move_time, TaskWaypoint start, double radius, double revolution, double start_angular_position);
  TaskWaypoint drawRhombus(double time_var);

  virtual void setOption(const void *arg);
  virtual void makeTaskTrajectory(double move_time, TaskWaypoint start, const void *arg);
  virtual TaskWaypoint getTaskWaypoint(double tick);
};

/*****************************************************************************
** Heart
*****************************************************************************/
class Heart : public robotis_manipulator::CustomTaskTrajectory
{
private:
  robotis_manipulator::MinimumJerk path_generator_;
  VectorXd coefficient_;

  TaskWaypoint start_pose_;
  TaskWaypoint goal_pose_;

  double radius_;
  double start_angular_position_;
  double revolution_;

public:
	Heart() {}
	virtual ~Heart() {}

  void initHeart(double move_time, TaskWaypoint start, double radius, double revolution, double start_angular_position);
  TaskWaypoint drawHeart(double tick);

  virtual void setOption(const void *arg);
  virtual void makeTaskTrajectory(double move_time, TaskWaypoint start, const void *arg);
  virtual TaskWaypoint getTaskWaypoint(double tick);
};

} // namespace linear_custom_trajectory
#endif // LINEAR_CUSTOM_TRAJECTORY_H_


text:
<?php

/**
 * Invocation matcher which checks if a method has been invoked at least
 * N times.
 *
 * @package    PHPUnit_MockObject
 * @author     Sebastian Bergmann <sebastian@phpunit.de>
 * @copyright  2010-2014 Sebastian Bergmann <sebastian@phpunit.de>
 * @license    http://www.opensource.org/licenses/BSD-3-Clause  The BSD 3-Clause License
 * @version    Release: @package_version@
 * @link       http://github.com/sebastianbergmann/phpunit-mock-objects
 * @since      Class available since Release 2.2.0
 */
class PHPUnit_Framework_MockObject_Matcher_InvokedAtMostCount extends PHPUnit_Framework_MockObject_Matcher_InvokedRecorder
{
    /**
     * @var integer
     */
    private $allowedInvocations;

    /**
     * @param integer $allowedInvocations
     */
    public function __construct($allowedInvocations)
    {
        $this->allowedInvocations = $allowedInvocations;
    }

    /**
     * @return string
     */
    public function toString()
    {
        return 'invoked at most ' . $this->allowedInvocations . ' times';
    }

    /**
     * Verifies that the current expectation is valid. If everything is OK the
     * code should just return, if not it must throw an exception.
     *
     * @throws PHPUnit_Framework_ExpectationFailedException
     */
    public function verify()
    {
        $count = $this->getInvocationCount();

        if ($count > $this->allowedInvocations) {
            throw new PHPUnit_Framework_ExpectationFailedException(
                'Expected invocation at most ' . $this->allowedInvocations .
                ' times but it occured ' . $count . ' time(s).'
            );
        }
    }
}


text:
"use strict";

const expect = require("chai").expect;
const os = require("os");
const moment = require("moment");
const Helper = require("../../src/helper");
const log = require("../../src/log");

describe("Helper", function() {
	describe("#expandHome", function() {
		it("should correctly expand a Unix path", function() {
			expect([`${os.homedir()}/tmp`, `${os.homedir()}\\tmp`])
				.to.include(Helper.expandHome("~/tmp"));
		});

		it("should correctly expand a Windows path", function() {
			expect(Helper.expandHome("~\\tmp")).to.equal(`${os.homedir()}\\tmp`);
		});

		it("should correctly expand when not given a specific path", function() {
			expect(Helper.expandHome("~")).to.equal(os.homedir());
		});

		it("should not expand paths not starting with tilde", function() {
			expect(Helper.expandHome("/tmp")).to.match(/^\/tmp|[A-Z]:\\tmp$/);
		});

		it("should not expand a tilde in the middle of a string", function() {
			expect(Helper.expandHome("/tmp/~foo"))
				.to.match(/^\/tmp\/~foo|[A-Z]:\\tmp\\~foo$/);
		});

		it("should return an empty string when given an empty string", function() {
			expect(Helper.expandHome("")).to.equal("");
		});

		it("should return an empty string when given undefined", function() {
			expect(Helper.expandHome(undefined)).to.equal("");
		});
	});

	describe("#getVersion()", function() {
		const version = Helper.getVersion();

		it("should mention it is served from source code", function() {
			expect(version).to.include("source");
		});

		it("should include a short Git SHA", function() {
			expect(version).to.match(/\([0-9a-f]{7,11} /);
		});

		it("should include a valid semver version", function() {
			expect(version).to.match(/v[0-9]+\.[0-9]+\.[0-9]+/);
		});
	});

	describe("#getHumanDate()", function() {
		expect(log.getHumanDate()).to.equal(moment().format("YYYY-MM-DD HH:mm:ss"));
	});
});


text:
require 'bundler'
Bundler.setup(:default, :development)

require 'heroku-commander'

logger = Logger.new($stdout)
logger.level = Logger::DEBUG
commander = Heroku::Commander.new({ :logger => logger })
config = commander.config
config.each_pair do |name, value|
  logger.info "#{name}: #{value}"
end


text:
(function(){
    angular.module('myApp').factory('newsFeedApi', newsFeedApi);

    //newsFeedApi.$inject[$resource];

    function newsFeedApi($resource) {
        var serviceUrl = 'http://localhost:3000/';
        var service = $resource(serviceUrl,{},{
            getByActionStart:{
                method:'GET',
                url:serviceUrl+'users',
                params:{action:'@action',start:'@start'}
            },
            get:{
                method:'GET',
                url:serviceUrl+'news-feed',
                params:{}
            }
        });
        return service;
    }
})();


text:
package com.github.davidmoten.rx.jdbc;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.github.davidmoten.rx.jdbc.exceptions.SQLRuntimeException;

/**
 * Provides database connections from a {@link DataSource}.
 */
public class ConnectionProviderFromDataSource implements ConnectionProvider {

    private final DataSource dataSource;

    /**
     * Constructor.
     *
     * @param dataSource
     *            database connection source
     */
    public ConnectionProviderFromDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Override
    public Connection get() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            throw new SQLRuntimeException(e);
        }
    }

    @Override
    public void close() {
        // do nothing
    }

}


text:
@charset "utf-8";
/* CSS Document by jacy use in 抽奖活动 */
html,body{ background:#fbf4c1;}
.prize_content{ margin:15px;}
.content_item{ background:#fed524; border-radius:5px; margin:30px 0 20px;}
.content_item .title{ text-align:center; position:relative; top:-10px;}
.content_item .title span{ padding:8px 30px; color:#fff; background:url(title.png) no-repeat; background-size:100% 100%;}
.content_item .content{ padding:10px; color:#f6600e; font-size:14px;}
.prizes{ overflow:hidden;}
.prizes li{ width:33.333%; text-align:center; margin:0 0 15px; float:left;}
.prizes li p{ line-height:16px; font-size:12px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis}
.prizes li .p_title{ font-size:14px; color:#F30}
.prizes li .count{ color:#888}
.prizes li img{ width:70px; height:70px; margin:5px auto; display:block;}
.content_item .log_btn,.content_item .log_btn:visited{ display:block; padding:3px ; text-align:center; background:#F60; color:#fff; border-radius:5px; margin:15px 0;}
.tips_div{ text-align:center;}
.tips_div .unget_btn{ padding:4px 30px;background:#d43b06; color:#fff; border-radius:20px; }
.tips_div .left_count{ line-height:30px; font-size:12px;}
.prize_log li{ overflow:hidden; padding:5px 0; border-bottom:1px dotted #FF9}
.prize_log li:last-child{ border:none}
.prize_log span{ display:inline-block; text-align:center}
.prize_log .head{ width:10%;}
.prize_log .head img{ width:100%; border-radius:100%; vertical-align:middle;}
.prize_log .name{ width:20%;}
.prize_log .award{ width:20%;}
.prize_log .award_name{ width:40%;}
/* 领取奖品 */
.my_prizes{ margin:15px; font-size:12px;}
.my_prizes li{background:#fff; border-radius:5px; margin-bottom:15px; position:relative; min-height:90px; padding:10px 10px 10px 110px; border:1px solid #ddd;}
.my_prizes li img{ position:absolute; top:10px; left:10px; width:90px; height:90px;}
.my_prizes li p{ line-height:15px; margin:0 0 5px;}
.my_prizes li .btn_p{ margin-top:5px;}
.my_prizes li .get_btn,.my_prizes li .get_btn:visited{ margin-top:5px; padding:5px 15px; color:#fff; font-size:12px;background:#F60; border-radius:5px; }
.get_info{ margin:15px;}
.goods_get{ margin-bottom:10px; background:#FFF; border:1px solid #ddd; border-radius:5px; overflow:hidden;}
.goods_get .addr_t{ overflow:hidden; padding:7px; border-bottom:1px dotted #ddd;}
.goods_get .addr_t a{ color:#888; font-size:12px;}
.goods_get .addr_t a img{ vertical-align:-2px;}
.goods_get ul{ margin-bottom:15px;}
.address_list label{ display:block; line-height:20px; padding:10px 10px 10px 30px; position:relative; border-bottom:1px solid #ddd; margin:0}
.address_list label input{ position:absolute; left:10px; top:50%; margin-top:-8px;}
/* 大转盘 */
.dzp {
	width: 280px;
	height: 280px;
	position: relative;
	margin: 50px auto
}
.disk {
	width: 280px;
	height: 280px;
	background: url(zpbg.png) no-repeat 1px 1px;
	background-size:100% 100%;
	padding:20px;
}
#outer-cont {
	top: 16px;
	width: 100%;
	margin-bottom: 50px;
	position: relative;
}
#inner-cont {
	top:90px;
	width: 100%;
	position: absolute;
}
#outer {
	margin: 0px auto;
	width: 250px;
	height: 250px;
	max-width: 247px;
}
#inner {
	margin: 0px auto;
	width: 80px;
	height: 110px;
	cursor: pointer;
	max-width: 90px;
}
#outer img {
	margin: 0px auto;
	display: block;
}
#inner img {
	margin: 0px auto;
	display: block;
}
/* 刮刮乐 */
.guagua_area{ margin:15px auto;position: relative;}
.guagua_area span{width: 300px;height: 62px; display: block;position: absolute;top: 0;left: 0;background: url(gua_pic_top.png) no-repeat;background-size: 100%;}
/* 砸金蛋 */
#zjd{ background:#9fd2ed}
#zjd .prize_content .content_item{ background:#fff}
.zjd_top{width: 100%;
-webkit-perspective:400;
-webkit-perspective-origin:50% 35%;
perspective:400;
perspective-origin:50% 35%;
position:relative;
}
.zjd_top>img{ width:100%;}
.cube{
  width:0px;
  height:0px;
  border-radius:300px;
  margin:auto;
  position:absolute;
  left:50%;
  bottom:30%;
  z-index:100;
  -webkit-transform-style: preserve-3d;
  -webkit-backface-visibility:visible;
  -webkit-transform: rotateX(0deg) rotateZ(0deg);
  transform-style: preserve-3d;
  backface-visibility:visible;
  transform: rotateX(0deg) rotateZ(0deg);
}

.plane{
  width:0px;
  height:0px;
  position: absolute;
  z-index:200;
  left:50%;
  top:50%;
  -webkit-transform-style: preserve-3d;
  -webkit-backface-visibility:visible;
   transform-style: preserve-3d;
  backface-visibility:visible;
}

.plane>span{
  position: relative;
  width: 75px;
  height: 120px;
  margin-left:-35px;
  margin-top:-86px;
  display:block;
}
/* on 金蛋未中奖,yes中奖*/
.plane>span.yes{

  background: url(gift.png) no-repeat center 28px;
  -webkit-background-size: 70% auto;
  -webkit-transition:background-position .5s ease-in;
  background-size: 70% auto;
  transition:background-position .5s ease-in;
}
.plane>span.yes{ background-position:center -5px;}
.plane>span>figure{
  width: 100%;
  height: 100%;
  display:block;
  background:url(egg.png) no-repeat center -8px;
  -webkit-background-size: 160% auto;
  background-size: 160% auto;
  pointer-events:none;
}

.cube.on, .cube.on .plane>span{-webkit-animation: spin 10s infinite linear;animation: spin 10s infinite linear; }
.plane>span.on.luck{
  background-position: center 3px;
}
.plane>span:after{
  content: "";
  position: absolute;
  z-index:360;
  display: block;
  width:100px;
  height:100px;
  bottom:30px;
  left:-10px;
  background:url(hua.png) no-repeat center center;
  -webkit-background-size:10px auto;
  -webkit-transition:-webkit-background-size .3s ease-in;
  background-size:10px auto;
  transition:-webkit-background-size .3s ease-in;
  position-events:none;
}
.plane>span.on:after,.plane>span.yes:after{
  -webkit-background-size: 120px auto;
  background-size: 120px auto;
}
.plane>span.on>figure,.plane>span.yes>figure{
  background-position: center -121px;
}
.cube.pause, .cube.pause span{
  -webkit-animation-play-state:paused!important;
  animation-play-state:paused!important;
}

.plane.one{-webkit-transform:rotateZ(90deg) translateX(80px) rotateX(-90deg);transform:rotateZ(90deg) translateX(80px) rotateX(-90deg);}
.plane.two{-webkit-transform:rotateZ(162deg) translateX(80px) rotateX(-90deg);transform:rotateZ(162deg) translateX(80px) rotateX(-90deg);}
.plane.three{-webkit-transform:rotateZ(234deg) translateX(80px) rotateX(-90deg);transform:rotateZ(234deg) translateX(80px) rotateX(-90deg);}
.plane.four{-webkit-transform:rotateZ(306deg) translateX(80px) rotateX(-90deg);transform:rotateZ(306deg) translateX(80px) rotateX(-90deg);}
.plane.five{-webkit-transform:rotateZ(378deg) translateX(80px) rotateX(-90deg);transform:rotateZ(378deg) translateX(80px) rotateX(-90deg);}

.cube.on>.one>span,.cube.yes>.one>span {-webkit-animation-name:spin1;-webkit-transform:rotateY(90deg);animation-name:spin1;transform:rotateY(90deg);z-index:203;}
.cube.on>.two>span,.cube.yes>.two>span {-webkit-animation-name:spin2;-webkit-transform:rotateY(160deg);animation-name:spin2;transform:rotateY(160deg);}
.cube.on>.three>span,.cube.yes>.three>span {-webkit-animation-name:spin3;-webkit-transform:rotateY(234deg);animation-name:spin3;transform:rotateY(234deg);}
.cube.on>.four>span,.cube.yes>.four>span {-webkit-animation-name:spin4;-webkit-transform:rotateY(306deg);animation-name:spin4;transform:rotateY(306deg);}
.cube.on>.five>span,.cube.yes>.five>span {-webkit-animation-name:spin5;-webkit-transform:rotateY(378deg);animation-name:spin5;transform:rotateY(378deg);}
@-webkit-keyframes spin5 {
  0% { -webkit-transform:rotateY(378deg); transform:rotateY(378deg);}
  100% { -webkit-transform: rotateY(738deg);transform: rotateY(738deg);}
}
@-webkit-keyframes spin4 {
  0% { -webkit-transform:rotateY(306deg);transform:rotateY(306deg);}
  100% { -webkit-transform: rotateY(666deg);transform: rotateY(666deg);}
}
@-webkit-keyframes spin3 {
  0% { -webkit-transform:rotateY(234deg);transform:rotateY(234deg);}
  100% { -webkit-transform: rotateY(594deg);transform: rotateY(594deg);}
}
@-webkit-keyframes spin2 {
  0% {-webkit-transform:rotateY(162deg);transform:rotateY(162deg);}
  100% {-webkit-transform:rotateY(522deg);transform:rotateY(522deg);}
}
@-webkit-keyframes spin1 {
  0% { -webkit-transform:rotateY(90deg);transform:rotateY(90deg);}
  100% { -webkit-transform:rotateY(450deg);transform:rotateY(450deg);}
}
@-webkit-keyframes spin{
  0% {-webkit-transform: rotateX(90deg) rotateZ(0deg);transform: rotateX(90deg) rotateZ(0deg); }
  100% { -webkit-transform: rotateX(90deg) rotateZ(360deg);transform: rotateX(90deg) rotateZ(360deg);}
}
/* 九宫格 */
.get_prize{ margin:30px 20px;}
.get_prize .prize_list{ position:relative; height:210px;}
.get_prize .prize_list .item{ position:absolute; top:0; left:0; background:#fff; border-radius:5px; box-shadow:0 3px #da6303; text-align:center; -webkit- transition:all 200ms; transition:all 200ms; border:2px solid #da6303}
.get_prize .prize_list img{ width:80%; height:80%; margin-top:10%;}
.get_prize .prize_list .geted_item{ background:#ffea00}
.get_prize .prize_list .geted_item{ -webkit-transform:scale(1.1,1.1);transform:scale(1.1,1.1)}
.get_prize .get_prize_btn{ position:absolute; background:#f42d30; border-radius:10px; box-shadow:0 3px #a71e21; color:#fff; font-size:15px; text-align:center;}
.get_prize .get_prize_btn img{ width:30px; height:30px; margin-top:auto; vertical-align:middle; margin-left:3px;}


text:
@implementation XFPictureService

- (RACSignal *)pullPictureDataWithMainCategory:(NSString *)mainCategory secondCategory:(NSString *)secondCategory startIndex:(NSUInteger)startIndex
{
    // http://image.baidu.com/search/acjson?tn=resultjson_com&ipn=rj&word=beyond&step_word=beyond&pn=90&rn=30
    return [[XFRACHttpTool getWithURL:@"http://image.baidu.com/search/acjson"
                       params:@{
                                @"tn": @"resultjson_com",
                                @"ipn": @"rj",
                                @"word":mainCategory,
                                @"step_word":secondCategory,
                                @"pn": @(startIndex), // 第几条开始
                                @"rn": @5, // 返回多少条
                                }]
            map:^id(RACTuple *tuple) {
        return [XFPictureListModel mj_objectWithKeyValues:tuple.first];
    }];
}
@end


text:
alfRepl.directive('resize', function ($window) {
  return function (scope,element) {
    function applyResizing() {
      element.css("height", parseInt($window.innerHeight) - 150);
    }
    angular.element($window).bind('resize', function(){
      scope.$apply(function() { applyResizing(); });
    });
    applyResizing();
  }
});


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

namespace GRA.Domain.Model
{
    public class ActivityLogResult
    {
        public int UserLogId { get; set; }
        public int? BookId { get; set; }
    }
}


text:
atChar::atChar(char val)
{
   // Set the value
   char_value = val;
}

atChar::~atChar()
{
}

void atChar::setValue(char val)
{
   // Set the value
   char_value = val;
}

char atChar::getValue()
{
   // Return the value
   return char_value;
}

bool atChar::equals(atItem * otherItem)
{
   atChar *   charItem;

   // Try to cast the other item to an atChar
   charItem = dynamic_cast<atChar *>(otherItem);

   // See if the other item is valid
   if (charItem != NULL)
   {
      // Return the char comparison of the values
      return char_value == charItem->getValue();
   }
   else
   {
      // The types of items didn't match so it has to be different char
      // values
      return false;
   }
}

int atChar::compare(atItem * otherItem)
{
   atChar *   charItem;

   // Try to cast the other item to an atChar
   charItem = dynamic_cast<atChar *>(otherItem);

   // See if the other item is valid
   if (charItem != NULL)
   {
      // Return the difference between the char values
      return char_value - charItem->getValue();
   }
   else
   {
      // Return the default atItem comparison
      return atItem::compare(otherItem);
   }
}


text:
package com.temple.util.json;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;

/**
 * TODOC
 *
 * @author Florent Pallaver
 * @version 1.0
 */
// TODO add TYPE support
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface JsonField {

	/**
	 * TODOC
	 *
	 * @return
	 */
	Class<? extends Handler> handler() default Handler.class;

	/**
	 * @return true if this property can be overwritten,
	 *         false if it cannot. Default to true.
	 */
	boolean inputable() default true;

	/**
	 * @return true if this property can be sent,
	 *         false if it cannot. Default to true.
	 */
	boolean outputable() default true;

	/**
	 * TODOC {@link Handler}s implementation must be public
	 *
	 * @author Florent Pallaver
	 * @version 1.0
	 */
	public static interface Handler {

		/**
		 * TODOC
		 *
		 * @param job
		 * @param name
		 * @param value
		 */
		void add(JsonObjectBuilder job, String name, Object value);

		/**
		 * TODOC
		 *
		 * @param job
		 * @param name
		 * @param value
		 */
		void add(JsonArrayBuilder jab, Object value);

		/**
		 * TODOC
		 *
		 * @param jo
		 * @param name
		 * @return
		 */
		Object getValue(JsonObject jo, String name);
	}
}


text:
@interface METMethodInvocation ()

@property (assign, nonatomic, readwrite) BOOL messageSent;
@property (assign, nonatomic, readwrite) BOOL resultReceived;
@property (assign, nonatomic, readwrite) BOOL updatesDone;
@property (assign, nonatomic, readwrite) BOOL updatesFlushed;

@end

@implementation METMethodInvocation {
  BOOL _executing;
  BOOL _finished;
  BOOL _completionHandlerInvoked;
}

- (BOOL)isAsynchronous {
  return YES;
}

- (BOOL)isExecuting {
  return _executing;
}

- (BOOL)isFinished {
  return _finished;
}

- (void)beginOperation {
  [self willChangeValueForKey:@"isExecuting"];
  _executing = YES;
  [self didChangeValueForKey:@"isExecuting"];
}

- (void)finishOperation {
  [self willChangeValueForKey:@"isFinished"];
  [self willChangeValueForKey:@"isExecuting"];
  _executing = NO;
  _finished = YES;
  [self didChangeValueForKey:@"isExecuting"];
  [self didChangeValueForKey:@"isFinished"];
}

- (void)start {
  if (self.cancelled) {
    [self willChangeValueForKey:@"isFinished"];
    _finished = YES;
    [self didChangeValueForKey:@"isFinished"];
    return;
  }

  [self beginOperation];

  [_client sendMethodMessageForMethodInvocation:self];
  self.messageSent = YES;
}

- (void)cancel {
  [super cancel];

  if (_executing) {
    [self finishOperation];
  }
}

- (void)didReceiveResult:(id)result error:(NSError *)error {
  self.resultReceived = YES;
  _result = result;
  _error = error;

  if (_receivedResultHandler) {
    _receivedResultHandler(_result, _error);
  }

  [self maybeInvokeCompletionHandler];
}

- (void)didReceiveUpdatesDone {
  self.updatesDone = YES;
}

- (void)didFlushUpdates {
  self.updatesFlushed = YES;
  [self maybeInvokeCompletionHandler];
}

- (void)maybeInvokeCompletionHandler {
  // Could be called from different threads because didFlushUpdates is called from a background queue
  @synchronized(self) {
    if (_completionHandlerInvoked) return;
    if (!(_resultReceived && _updatesFlushed)) return;

    if (_completionHandler) {
      _completionHandlerInvoked = YES;
      _completionHandler(_result, _error);
    }

    if (_executing) {
      [self finishOperation];
    }
  }
}

#pragma mark - NSCopying

- (id)copyWithZone:(NSZone *)zone {
  METMethodInvocation *copy = [[[self class] allocWithZone:zone] init];
  copy.name = self.name;
  copy.client = _client;
  copy.methodID = _methodID;
  copy.methodName = _methodName;
  copy.parameters = _parameters;
  copy.randomSeed = _randomSeed;
  copy.barrier = _barrier;
  copy.receivedResultHandler = _receivedResultHandler;
  copy.completionHandler = _completionHandler;
  return copy;
}

@end


text:
"use strict";

function TabContentDirective() {
  return {
    restrict: "E",
    scope: {
      project: "="
    },
    templateUrl: "static/components/tabContent/templates/content.html"
  };
}

angular.module("TabContent")
  .directive("tabcontent", [
    TabContentDirective
  ]);


text:
<?php

namespace garethp\ews\API\Type;

/**
 * Class representing DeleteRuleOperationType
 *
 *
 * XSD Type: DeleteRuleOperationType
 *
 * @method string getRuleId()
 * @method DeleteRuleOperationType setRuleId(string $ruleId)
 */
class DeleteRuleOperationType extends RuleOperationType
{

    /**
     * @var string
     */
    protected $ruleId = null;
}


text:
var mkdirp = require('mkdirp')
var osenv = require('osenv')
var path = require('path')
var rimraf = require('rimraf')
var test = require('tap').test
var writeFileSync = require('fs').writeFileSync

var common = require('../common-tap.js')

var link = path.join(__dirname, 'rmlinked')
var linkDep = path.join(link, 'node_modules', 'baz')
var linkInstall = path.join(__dirname, 'rmlinked-install')
var linkRoot = path.join(__dirname, 'rmlinked-root')

var config = 'prefix = ' + linkRoot
var configPath = path.join(link, '_npmrc')

var OPTS = {
  env: {
    'npm_config_userconfig': configPath
  }
}

var linkedJSON = {
  name: 'foo',
  version: '1.0.0',
  description: '',
  main: 'index.js',
  scripts: {
    test: 'echo \"Error: no test specified\" && exit 1'
  },
  dependencies: {
    'baz': '1.0.0'
  },
  author: '',
  license: 'ISC'
}

var linkedDepJSON = {
  name: 'baz',
  version: '1.0.0',
  description: '',
  main: 'index.js',
  scripts: {
    test: 'echo \"Error: no test specified\" && exit 1'
  },
  author: '',
  license: 'ISC'
}

var installJSON = {
  name: 'bar',
  version: '1.0.0',
  description: '',
  main: 'index.js',
  scripts: {
    test: 'echo \"Error: no test specified\" && exit 1'
  },
  dependencies: {
    'foo': '1.0.0'
  },
  author: '',
  license: 'ISC'
}

test('setup', function (t) {
  setup()
  common.npm(['ls', '-g', '--depth=0'], OPTS, function (err, c, out) {
    t.ifError(err)
    t.equal(c, 0, 'set up ok')
    t.notOk(out.match(/UNMET DEPENDENCY foo@/), "foo isn't in global")
    t.end()
  })
})

test('creates global link', function (t) {
  process.chdir(link)
  common.npm(['link'], OPTS, function (err, c, out) {
    t.ifError(err, 'link has no error')
    common.npm(['ls', '-g'], OPTS, function (err, c, out, stderr) {
      t.ifError(err)
      t.equal(c, 0)
      t.equal(stderr, '', 'got expected stderr')
      t.has(out, /foo@1.0.0/, 'creates global link ok')
      t.end()
    })
  })
})

test('uninstall the global linked package', function (t) {
  process.chdir(osenv.tmpdir())
  common.npm(['uninstall', '-g', 'foo'], OPTS, function (err) {
    t.ifError(err, 'uninstall has no error')
    process.chdir(link)
    common.npm(['ls'], OPTS, function (err, c, out) {
      t.ifError(err)
      t.equal(c, 0)
      t.has(out, /baz@1.0.0/, "uninstall didn't remove dep")
      t.end()
    })
  })
})

test('cleanup', function (t) {
  cleanup()
  t.end()
})

function cleanup () {
  process.chdir(osenv.tmpdir())
  try { rimraf.sync(linkRoot) } catch (e) { }
  try { rimraf.sync(linkDep) } catch (e) { }
  try { rimraf.sync(link) } catch (e) { }
  try { rimraf.sync(linkInstall) } catch (e) { }
}

function setup () {
  cleanup()
  mkdirp.sync(linkRoot)
  mkdirp.sync(link)
  writeFileSync(
    path.join(link, 'package.json'),
    JSON.stringify(linkedJSON, null, 2)
  )
  mkdirp.sync(linkDep)
  writeFileSync(
    path.join(linkDep, 'package.json'),
    JSON.stringify(linkedDepJSON, null, 2)
  )
  mkdirp.sync(linkInstall)
  writeFileSync(
    path.join(linkInstall, 'package.json'),
    JSON.stringify(installJSON, null, 2)
  )
  writeFileSync(configPath, config)
}


text:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/api/declarative_webrequest/webrequest_action.h"

#include <limits>

#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/stringprintf.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/extensions/api/declarative_webrequest/request_stage.h"
#include "chrome/browser/extensions/api/declarative_webrequest/webrequest_constants.h"
#include "chrome/browser/extensions/api/web_request/web_request_api_helpers.h"
#include "chrome/browser/extensions/api/web_request/web_request_permissions.h"
#include "chrome/browser/extensions/extension_info_map.h"
#include "chrome/common/extensions/extension.h"
#include "net/url_request/url_request.h"

namespace extensions {

namespace helpers = extension_web_request_api_helpers;
namespace keys = declarative_webrequest_constants;

namespace {
// Error messages.
const char kInvalidInstanceTypeError[] =
    "An action has an invalid instanceType: %s";

const char kTransparentImageUrl[] = "data:image/png;base64,iVBORw0KGgoAAAANSUh"
    "EUgAAAAEAAAABCAYAAAAfFcSJAAAACklEQVR4nGMAAQAABQABDQottAAAAABJRU5ErkJggg==";
const char kEmptyDocumentUrl[] = "data:text/html,";

#define INPUT_FORMAT_VALIDATE(test) do { \
    if (!(test)) { \
      *bad_message = true; \
      return scoped_ptr<WebRequestAction>(NULL); \
    } \
  } while (0)

scoped_ptr<helpers::RequestCookie> ParseRequestCookie(
    const DictionaryValue* dict) {
  scoped_ptr<helpers::RequestCookie> result(new helpers::RequestCookie);
  std::string tmp;
  if (dict->GetString(keys::kNameKey, &tmp))
    result->name.reset(new std::string(tmp));
  if (dict->GetString(keys::kValueKey, &tmp))
    result->value.reset(new std::string(tmp));
  return result.Pass();
}

scoped_ptr<helpers::ResponseCookie> ParseResponseCookie(
    const DictionaryValue* dict) {
  scoped_ptr<helpers::ResponseCookie> result(new helpers::ResponseCookie);
  std::string string_tmp;
  int int_tmp = 0;
  bool bool_tmp = false;
  if (dict->GetString(keys::kNameKey, &string_tmp))
    result->name.reset(new std::string(string_tmp));
  if (dict->GetString(keys::kValueKey, &string_tmp))
    result->value.reset(new std::string(string_tmp));
  if (dict->GetString(keys::kExpiresKey, &string_tmp))
    result->expires.reset(new std::string(string_tmp));
  if (dict->GetInteger(keys::kMaxAgeKey, &int_tmp))
    result->max_age.reset(new int(int_tmp));
  if (dict->GetString(keys::kDomainKey, &string_tmp))
    result->domain.reset(new std::string(string_tmp));
  if (dict->GetString(keys::kPathKey, &string_tmp))
    result->path.reset(new std::string(string_tmp));
  if (dict->GetBoolean(keys::kSecureKey, &bool_tmp))
    result->secure.reset(new bool(bool_tmp));
  if (dict->GetBoolean(keys::kHttpOnlyKey, &bool_tmp))
    result->http_only.reset(new bool(bool_tmp));
  return result.Pass();
}

// Helper function for WebRequestActions that can be instantiated by just
// calling the constructor.
template <class T>
scoped_ptr<WebRequestAction> CallConstructorFactoryMethod(
    const base::DictionaryValue* dict,
    std::string* error,
    bool* bad_message) {
  return scoped_ptr<WebRequestAction>(new T);
}

scoped_ptr<WebRequestAction> CreateRedirectRequestAction(
    const base::DictionaryValue* dict,
    std::string* error,
    bool* bad_message) {
  std::string redirect_url_string;
  INPUT_FORMAT_VALIDATE(
      dict->GetString(keys::kRedirectUrlKey, &redirect_url_string));
  GURL redirect_url(redirect_url_string);
  return scoped_ptr<WebRequestAction>(
      new WebRequestRedirectAction(redirect_url));
}

scoped_ptr<WebRequestAction> CreateRedirectRequestByRegExAction(
    const base::DictionaryValue* dict,
    std::string* error,
    bool* bad_message) {
  std::string from;
  std::string to;
  INPUT_FORMAT_VALIDATE(dict->GetString(keys::kFromKey, &from));
  INPUT_FORMAT_VALIDATE(dict->GetString(keys::kToKey, &to));

  // TODO(battre): Add this line once we migrate from ICU RegEx to RE2 RegEx.s
  // to = WebRequestRedirectByRegExAction::PerlToRe2Style(to);

  UParseError parse_error;
  UErrorCode status = U_ZERO_ERROR;
  scoped_ptr<icu::RegexPattern> pattern(
      icu::RegexPattern::compile(icu::UnicodeString(from.data(), from.size()),
                                 0, parse_error, status));
  if (U_FAILURE(status) || !pattern.get()) {
    *error = "Invalid pattern '" + from + "' -> '" + to + "'";
    return scoped_ptr<WebRequestAction>(NULL);
  }
  return scoped_ptr<WebRequestAction>(
      new WebRequestRedirectByRegExAction(pattern.Pass(), to));
}

scoped_ptr<WebRequestAction> CreateSetRequestHeaderAction(
    const base::DictionaryValue* dict,
    std::string* error,
    bool* bad_message) {
  std::string name;
  std::string value;
  INPUT_FORMAT_VALIDATE(dict->GetString(keys::kNameKey, &name));
  INPUT_FORMAT_VALIDATE(dict->GetString(keys::kValueKey, &value));
  return scoped_ptr<WebRequestAction>(
      new WebRequestSetRequestHeaderAction(name, value));
}

scoped_ptr<WebRequestAction> CreateRemoveRequestHeaderAction(
    const base::DictionaryValue* dict,
    std::string* error,
    bool* bad_message) {
  std::string name;
  INPUT_FORMAT_VALIDATE(dict->GetString(keys::kNameKey, &name));
  return scoped_ptr<WebRequestAction>(
      new WebRequestRemoveRequestHeaderAction(name));
}

scoped_ptr<WebRequestAction> CreateAddResponseHeaderAction(
    const base::DictionaryValue* dict,
    std::string* error,
    bool* bad_message) {
  std::string name;
  std::string value;
  INPUT_FORMAT_VALIDATE(dict->GetString(keys::kNameKey, &name));
  INPUT_FORMAT_VALIDATE(dict->GetString(keys::kValueKey, &value));
  return scoped_ptr<WebRequestAction>(
      new WebRequestAddResponseHeaderAction(name, value));
}

scoped_ptr<WebRequestAction> CreateRemoveResponseHeaderAction(
    const base::DictionaryValue* dict,
    std::string* error,
    bool* bad_message) {
  std::string name;
  std::string value;
  INPUT_FORMAT_VALIDATE(dict->GetString(keys::kNameKey, &name));
  bool has_value = dict->GetString(keys::kValueKey, &value);
  return scoped_ptr<WebRequestAction>(
      new WebRequestRemoveResponseHeaderAction(name, value, has_value));
}

scoped_ptr<WebRequestAction> CreateIgnoreRulesAction(
    const base::DictionaryValue* dict,
    std::string* error,
    bool* bad_message) {
  int minium_priority;
  INPUT_FORMAT_VALIDATE(
      dict->GetInteger(keys::kLowerPriorityThanKey, &minium_priority));
  return scoped_ptr<WebRequestAction>(
      new WebRequestIgnoreRulesAction(minium_priority));
}

scoped_ptr<WebRequestAction> CreateRequestCookieAction(
    const base::DictionaryValue* dict,
    std::string* error,
    bool* bad_message) {
  using extension_web_request_api_helpers::RequestCookieModification;

  linked_ptr<RequestCookieModification> modification(
      new RequestCookieModification);

  // Get modification type.
  std::string instance_type;
  INPUT_FORMAT_VALIDATE(
      dict->GetString(keys::kInstanceTypeKey, &instance_type));
  if (instance_type == keys::kAddRequestCookieType)
    modification->type = helpers::ADD;
  else if (instance_type == keys::kEditRequestCookieType)
    modification->type = helpers::EDIT;
  else if (instance_type == keys::kRemoveRequestCookieType)
    modification->type = helpers::REMOVE;
  else
    INPUT_FORMAT_VALIDATE(false);

  // Get filter.
  if (modification->type == helpers::EDIT ||
      modification->type == helpers::REMOVE) {
    const DictionaryValue* filter = NULL;
    INPUT_FORMAT_VALIDATE(dict->GetDictionary(keys::kFilterKey, &filter));
    modification->filter = ParseRequestCookie(filter);
  }

  // Get new value.
  if (modification->type == helpers::ADD) {
    const DictionaryValue* value = NULL;
    INPUT_FORMAT_VALIDATE(dict->GetDictionary(keys::kCookieKey, &value));
    modification->modification = ParseRequestCookie(value);
  } else if (modification->type == helpers::EDIT) {
    const DictionaryValue* value = NULL;
    INPUT_FORMAT_VALIDATE(dict->GetDictionary(keys::kModificationKey, &value));
    modification->modification = ParseRequestCookie(value);
  }

  return scoped_ptr<WebRequestAction>(
      new WebRequestRequestCookieAction(modification));
}

scoped_ptr<WebRequestAction> CreateResponseCookieAction(
    const base::DictionaryValue* dict,
    std::string* error,
    bool* bad_message) {
  using extension_web_request_api_helpers::ResponseCookieModification;

  linked_ptr<ResponseCookieModification> modification(
      new ResponseCookieModification);

  // Get modification type.
  std::string instance_type;
  INPUT_FORMAT_VALIDATE(
      dict->GetString(keys::kInstanceTypeKey, &instance_type));
  if (instance_type == keys::kAddResponseCookieType)
    modification->type = helpers::ADD;
  else if (instance_type == keys::kEditResponseCookieType)
    modification->type = helpers::EDIT;
  else if (instance_type == keys::kRemoveResponseCookieType)
    modification->type = helpers::REMOVE;
  else
    INPUT_FORMAT_VALIDATE(false);

  // Get filter.
  if (modification->type == helpers::EDIT ||
      modification->type == helpers::REMOVE) {
    const DictionaryValue* filter = NULL;
    INPUT_FORMAT_VALIDATE(dict->GetDictionary(keys::kFilterKey, &filter));
    modification->filter = ParseResponseCookie(filter);
  }

  // Get new value.
  if (modification->type == helpers::ADD) {
    const DictionaryValue* value = NULL;
    INPUT_FORMAT_VALIDATE(dict->GetDictionary(keys::kCookieKey, &value));
    modification->modification = ParseResponseCookie(value);
  } else if (modification->type == helpers::EDIT) {
    const DictionaryValue* value = NULL;
    INPUT_FORMAT_VALIDATE(dict->GetDictionary(keys::kModificationKey, &value));
    modification->modification = ParseResponseCookie(value);
  }

  return scoped_ptr<WebRequestAction>(
      new WebRequestResponseCookieAction(modification));
}

struct WebRequestActionFactory {
  // Factory methods for WebRequestAction instances. |dict| contains the json
  // dictionary that describes the action. |error| is used to return error
  // messages in case the extension passed an action that was syntactically
  // correct but semantically incorrect. |bad_message| is set to true in case
  // |dict| does not confirm to the validated JSON specification.
  typedef scoped_ptr<WebRequestAction>
      (* FactoryMethod)(const base::DictionaryValue* /* dict */ ,
                        std::string* /* error */,
                        bool* /* bad_message */);
  std::map<std::string, FactoryMethod> factory_methods;

  WebRequestActionFactory() {
    factory_methods[keys::kAddRequestCookieType] =
        &CreateRequestCookieAction;
    factory_methods[keys::kAddResponseCookieType] =
        &CreateResponseCookieAction;
    factory_methods[keys::kAddResponseHeaderType] =
        &CreateAddResponseHeaderAction;
    factory_methods[keys::kCancelRequestType] =
        &CallConstructorFactoryMethod<WebRequestCancelAction>;
    factory_methods[keys::kEditRequestCookieType] =
        &CreateRequestCookieAction;
    factory_methods[keys::kEditResponseCookieType] =
        &CreateResponseCookieAction;
    factory_methods[keys::kRedirectByRegExType] =
        &CreateRedirectRequestByRegExAction;
    factory_methods[keys::kRedirectRequestType] =
        &CreateRedirectRequestAction;
    factory_methods[keys::kRedirectToTransparentImageType] =
        &CallConstructorFactoryMethod<
            WebRequestRedirectToTransparentImageAction>;
    factory_methods[keys::kRedirectToEmptyDocumentType] =
        &CallConstructorFactoryMethod<WebRequestRedirectToEmptyDocumentAction>;
    factory_methods[keys::kRemoveRequestCookieType] =
        &CreateRequestCookieAction;
    factory_methods[keys::kRemoveResponseCookieType] =
        &CreateResponseCookieAction;
    factory_methods[keys::kSetRequestHeaderType] =
        &CreateSetRequestHeaderAction;
    factory_methods[keys::kRemoveRequestHeaderType] =
        &CreateRemoveRequestHeaderAction;
    factory_methods[keys::kRemoveResponseHeaderType] =
        &CreateRemoveResponseHeaderAction;
    factory_methods[keys::kIgnoreRulesType] =
        &CreateIgnoreRulesAction;
  }
};

base::LazyInstance<WebRequestActionFactory>::Leaky
    g_web_request_action_factory = LAZY_INSTANCE_INITIALIZER;

}  // namespace

//
// WebRequestAction
//

WebRequestAction::WebRequestAction() {}

WebRequestAction::~WebRequestAction() {}

int WebRequestAction::GetMinimumPriority() const {
  return std::numeric_limits<int>::min();
}

bool WebRequestAction::HasPermission(const ExtensionInfoMap* extension_info_map,
                                     const std::string& extension_id,
                                     const net::URLRequest* request,
                                     bool crosses_incognito) const {
  if (WebRequestPermissions::HideRequest(request))
    return false;

  // In unit tests we don't have an extension_info_map object here and skip host
  // permission checks.
  if (!extension_info_map)
    return true;

  return WebRequestPermissions::CanExtensionAccessURL(
      extension_info_map, extension_id, request->url(), crosses_incognito,
      ShouldEnforceHostPermissions());
}

bool WebRequestAction::ShouldEnforceHostPermissions() const {
  return true;
}

// static
scoped_ptr<WebRequestAction> WebRequestAction::Create(
    const base::Value& json_action,
    std::string* error,
    bool* bad_message) {
  *error = "";
  *bad_message = false;

  const base::DictionaryValue* action_dict = NULL;
  INPUT_FORMAT_VALIDATE(json_action.GetAsDictionary(&action_dict));

  std::string instance_type;
  INPUT_FORMAT_VALIDATE(
      action_dict->GetString(keys::kInstanceTypeKey, &instance_type));

  WebRequestActionFactory& factory = g_web_request_action_factory.Get();
  std::map<std::string, WebRequestActionFactory::FactoryMethod>::iterator
      factory_method_iter = factory.factory_methods.find(instance_type);
  if (factory_method_iter != factory.factory_methods.end())
    return (*factory_method_iter->second)(action_dict, error, bad_message);

  *error = base::StringPrintf(kInvalidInstanceTypeError, instance_type.c_str());
  return scoped_ptr<WebRequestAction>();
}

//
// WebRequestActionSet
//

WebRequestActionSet::WebRequestActionSet(const Actions& actions)
    : actions_(actions) {}

WebRequestActionSet::~WebRequestActionSet() {}

// static
scoped_ptr<WebRequestActionSet> WebRequestActionSet::Create(
    const AnyVector& actions,
    std::string* error,
    bool* bad_message) {
  *error = "";
  *bad_message = false;
  Actions result;

  for (AnyVector::const_iterator i = actions.begin();
       i != actions.end(); ++i) {
    CHECK(i->get());
    scoped_ptr<WebRequestAction> action =
        WebRequestAction::Create((*i)->value(), error, bad_message);
    if (!error->empty() || *bad_message)
      return scoped_ptr<WebRequestActionSet>(NULL);
    result.push_back(make_linked_ptr(action.release()));
  }

  return scoped_ptr<WebRequestActionSet>(new WebRequestActionSet(result));
}

std::list<LinkedPtrEventResponseDelta> WebRequestActionSet::CreateDeltas(
    const ExtensionInfoMap* extension_info_map,
    const std::string& extension_id,
    const WebRequestRule::RequestData& request_data,
    bool crosses_incognito,
    const base::Time& extension_install_time) const {
  std::list<LinkedPtrEventResponseDelta> result;
  for (Actions::const_iterator i = actions_.begin(); i != actions_.end(); ++i) {
    if (!(*i)->HasPermission(extension_info_map, extension_id,
                             request_data.request, crosses_incognito))
      continue;
    if ((*i)->GetStages() & request_data.stage) {
      LinkedPtrEventResponseDelta delta = (*i)->CreateDelta(
          request_data, extension_id, extension_install_time);
      if (delta.get())
        result.push_back(delta);
    }
  }
  return result;
}

int WebRequestActionSet::GetMinimumPriority() const {
  int minimum_priority = std::numeric_limits<int>::min();
  for (Actions::const_iterator i = actions_.begin(); i != actions_.end(); ++i) {
    minimum_priority = std::max(minimum_priority, (*i)->GetMinimumPriority());
  }
  return minimum_priority;
}

//
// WebRequestCancelAction
//

WebRequestCancelAction::WebRequestCancelAction() {}

WebRequestCancelAction::~WebRequestCancelAction() {}

int WebRequestCancelAction::GetStages() const {
  return ON_BEFORE_REQUEST | ON_BEFORE_SEND_HEADERS | ON_HEADERS_RECEIVED |
      ON_AUTH_REQUIRED;
}

WebRequestAction::Type WebRequestCancelAction::GetType() const {
  return WebRequestAction::ACTION_CANCEL_REQUEST;
}

LinkedPtrEventResponseDelta WebRequestCancelAction::CreateDelta(
    const WebRequestRule::RequestData& request_data,
    const std::string& extension_id,
    const base::Time& extension_install_time) const {
  CHECK(request_data.stage & GetStages());
  LinkedPtrEventResponseDelta result(
      new helpers::EventResponseDelta(extension_id, extension_install_time));
  result->cancel = true;
  return result;
}

//
// WebRequestRedirectAction
//

WebRequestRedirectAction::WebRequestRedirectAction(const GURL& redirect_url)
    : redirect_url_(redirect_url) {}

WebRequestRedirectAction::~WebRequestRedirectAction() {}

int WebRequestRedirectAction::GetStages() const {
  return ON_BEFORE_REQUEST;
}

WebRequestAction::Type WebRequestRedirectAction::GetType() const {
  return WebRequestAction::ACTION_REDIRECT_REQUEST;
}

LinkedPtrEventResponseDelta WebRequestRedirectAction::CreateDelta(
    const WebRequestRule::RequestData& request_data,
    const std::string& extension_id,
    const base::Time& extension_install_time) const {
  CHECK(request_data.stage & GetStages());
  if (request_data.request->url() == redirect_url_)
    return LinkedPtrEventResponseDelta(NULL);
  LinkedPtrEventResponseDelta result(
      new helpers::EventResponseDelta(extension_id, extension_install_time));
  result->new_url = redirect_url_;
  return result;
}

//
// WebRequestRedirectToTransparentImageAction
//

WebRequestRedirectToTransparentImageAction::
WebRequestRedirectToTransparentImageAction() {}

WebRequestRedirectToTransparentImageAction::
~WebRequestRedirectToTransparentImageAction() {}

int WebRequestRedirectToTransparentImageAction::GetStages() const {
  return ON_BEFORE_REQUEST;
}

WebRequestAction::Type
WebRequestRedirectToTransparentImageAction::GetType() const {
  return WebRequestAction::ACTION_REDIRECT_TO_TRANSPARENT_IMAGE;
}

bool WebRequestRedirectToTransparentImageAction::ShouldEnforceHostPermissions()
    const {
  return false;
}

LinkedPtrEventResponseDelta
WebRequestRedirectToTransparentImageAction::CreateDelta(
    const WebRequestRule::RequestData& request_data,
    const std::string& extension_id,
    const base::Time& extension_install_time) const {
  CHECK(request_data.stage & GetStages());
  LinkedPtrEventResponseDelta result(
      new helpers::EventResponseDelta(extension_id, extension_install_time));
  result->new_url = GURL(kTransparentImageUrl);
  return result;
}

//
// WebRequestRedirectToEmptyDocumentAction
//

WebRequestRedirectToEmptyDocumentAction::
WebRequestRedirectToEmptyDocumentAction() {}

WebRequestRedirectToEmptyDocumentAction::
~WebRequestRedirectToEmptyDocumentAction() {}

int WebRequestRedirectToEmptyDocumentAction::GetStages() const {
  return ON_BEFORE_REQUEST;
}

WebRequestAction::Type
WebRequestRedirectToEmptyDocumentAction::GetType() const {
  return WebRequestAction::ACTION_REDIRECT_TO_EMPTY_DOCUMENT;
}

bool
WebRequestRedirectToEmptyDocumentAction::ShouldEnforceHostPermissions() const {
  return false;
}

LinkedPtrEventResponseDelta
WebRequestRedirectToEmptyDocumentAction::CreateDelta(
    const WebRequestRule::RequestData& request_data,
    const std::string& extension_id,
    const base::Time& extension_install_time) const {
  CHECK(request_data.stage & GetStages());
  LinkedPtrEventResponseDelta result(
      new helpers::EventResponseDelta(extension_id, extension_install_time));
  result->new_url = GURL(kEmptyDocumentUrl);
  return result;
}

//
// WebRequestRedirectByRegExAction
//

WebRequestRedirectByRegExAction::WebRequestRedirectByRegExAction(
    scoped_ptr<icu::RegexPattern> from_pattern,
    const std::string& to_pattern)
    : from_pattern_(from_pattern.Pass()),
      to_pattern_(to_pattern.data(), to_pattern.size()) {}

WebRequestRedirectByRegExAction::~WebRequestRedirectByRegExAction() {}

// About the syntax of the two languages:
//
// ICU (Perl) states:
// $n The text of capture group n will be substituted for $n. n must be >= 0
//    and not greater than the number of capture groups. A $ not followed by a
//    digit has no special meaning, and will appear in the substitution text
//    as itself, a $.
// \  Treat the following character as a literal, suppressing any special
//    meaning. Backslash escaping in substitution text is only required for
//    '$' and '\', but may be used on any other character without bad effects.
//
// RE2, derived from RE2::Rewrite()
// \  May only be followed by a digit or another \. If followed by a single
//    digit, both characters represent the respective capture group. If followed
//    by another \, it is used as an escape sequence.

// static
std::string WebRequestRedirectByRegExAction::PerlToRe2Style(
    const std::string& perl) {
  std::string::const_iterator i = perl.begin();
  std::string result;
  while (i != perl.end()) {
    if (*i == '$') {
      ++i;
      if (i == perl.end()) {
        result += '$';
        return result;
      } else if (isdigit(*i)) {
        result += '\\';
        result += *i;
      } else {
        result += '$';
        result += *i;
      }
    } else if (*i == '\\') {
      ++i;
      if (i == perl.end()) {
        result += '\\';
      } else if (*i == '$') {
        result += '$';
      } else if (*i == '\\') {
        result += "\\\\";
      } else {
        result += *i;
      }
    } else {
      result += *i;
    }
    ++i;
  }
  return result;
}

int WebRequestRedirectByRegExAction::GetStages() const {
  return ON_BEFORE_REQUEST;
}

WebRequestAction::Type WebRequestRedirectByRegExAction::GetType() const {
  return WebRequestAction::ACTION_REDIRECT_BY_REGEX_DOCUMENT;
}

LinkedPtrEventResponseDelta WebRequestRedirectByRegExAction::CreateDelta(
    const WebRequestRule::RequestData& request_data,
    const std::string& extension_id,
    const base::Time& extension_install_time) const {
  CHECK(request_data.stage & GetStages());
  CHECK(from_pattern_.get());

  UErrorCode status = U_ZERO_ERROR;
  const std::string& old_url = request_data.request->url().spec();
  icu::UnicodeString old_url_unicode(old_url.data(), old_url.size());

  scoped_ptr<icu::RegexMatcher> matcher(
      from_pattern_->matcher(old_url_unicode, status));
  if (U_FAILURE(status) || !matcher.get())
    return LinkedPtrEventResponseDelta(NULL);

  icu::UnicodeString new_url = matcher->replaceAll(to_pattern_, status);
  if (U_FAILURE(status))
    return LinkedPtrEventResponseDelta(NULL);

  std::string new_url_utf8;
  UTF16ToUTF8(new_url.getBuffer(), new_url.length(), &new_url_utf8);

  if (new_url_utf8 == request_data.request->url().spec())
    return LinkedPtrEventResponseDelta(NULL);

  LinkedPtrEventResponseDelta result(
      new extension_web_request_api_helpers::EventResponseDelta(
          extension_id, extension_install_time));
  result->new_url = GURL(new_url_utf8);
  return result;
}

//
// WebRequestSetRequestHeaderAction
//

WebRequestSetRequestHeaderAction::WebRequestSetRequestHeaderAction(
    const std::string& name,
    const std::string& value)
    : name_(name),
      value_(value) {
}

WebRequestSetRequestHeaderAction::~WebRequestSetRequestHeaderAction() {}

int WebRequestSetRequestHeaderAction::GetStages() const {
  return ON_BEFORE_SEND_HEADERS;
}

WebRequestAction::Type
WebRequestSetRequestHeaderAction::GetType() const {
  return WebRequestAction::ACTION_SET_REQUEST_HEADER;
}

LinkedPtrEventResponseDelta
WebRequestSetRequestHeaderAction::CreateDelta(
    const WebRequestRule::RequestData& request_data,
    const std::string& extension_id,
    const base::Time& extension_install_time) const {
  CHECK(request_data.stage & GetStages());
  LinkedPtrEventResponseDelta result(
      new helpers::EventResponseDelta(extension_id, extension_install_time));
  result->modified_request_headers.SetHeader(name_, value_);
  return result;
}

//
// WebRequestRemoveRequestHeaderAction
//

WebRequestRemoveRequestHeaderAction::WebRequestRemoveRequestHeaderAction(
    const std::string& name)
    : name_(name) {
}

WebRequestRemoveRequestHeaderAction::~WebRequestRemoveRequestHeaderAction() {}

int WebRequestRemoveRequestHeaderAction::GetStages() const {
  return ON_BEFORE_SEND_HEADERS;
}

WebRequestAction::Type
WebRequestRemoveRequestHeaderAction::GetType() const {
  return WebRequestAction::ACTION_REMOVE_REQUEST_HEADER;
}

LinkedPtrEventResponseDelta
WebRequestRemoveRequestHeaderAction::CreateDelta(
    const WebRequestRule::RequestData& request_data,
    const std::string& extension_id,
    const base::Time& extension_install_time) const {
  CHECK(request_data.stage & GetStages());
  LinkedPtrEventResponseDelta result(
      new helpers::EventResponseDelta(extension_id, extension_install_time));
  result->deleted_request_headers.push_back(name_);
  return result;
}

//
// WebRequestAddResponseHeaderAction
//

WebRequestAddResponseHeaderAction::WebRequestAddResponseHeaderAction(
    const std::string& name,
    const std::string& value)
    : name_(name),
      value_(value) {
}

WebRequestAddResponseHeaderAction::~WebRequestAddResponseHeaderAction() {}

int WebRequestAddResponseHeaderAction::GetStages() const {
  return ON_HEADERS_RECEIVED;
}

WebRequestAction::Type
WebRequestAddResponseHeaderAction::GetType() const {
  return WebRequestAction::ACTION_ADD_RESPONSE_HEADER;
}

LinkedPtrEventResponseDelta
WebRequestAddResponseHeaderAction::CreateDelta(
    const WebRequestRule::RequestData& request_data,
    const std::string& extension_id,
    const base::Time& extension_install_time) const {
  CHECK(request_data.stage & GetStages());
  net::HttpResponseHeaders* headers =
      request_data.original_response_headers;
  if (!headers)
    return LinkedPtrEventResponseDelta(NULL);

  // Don't generate the header if it exists already.
  if (headers->HasHeaderValue(name_, value_))
    return LinkedPtrEventResponseDelta(NULL);

  LinkedPtrEventResponseDelta result(
      new helpers::EventResponseDelta(extension_id, extension_install_time));
  result->added_response_headers.push_back(make_pair(name_, value_));
  return result;
}

//
// WebRequestRemoveResponseHeaderAction
//

WebRequestRemoveResponseHeaderAction::WebRequestRemoveResponseHeaderAction(
    const std::string& name,
    const std::string& value,
    bool has_value)
    : name_(name),
      value_(value),
      has_value_(has_value) {
}

WebRequestRemoveResponseHeaderAction::~WebRequestRemoveResponseHeaderAction() {}

int WebRequestRemoveResponseHeaderAction::GetStages() const {
  return ON_HEADERS_RECEIVED;
}

WebRequestAction::Type
WebRequestRemoveResponseHeaderAction::GetType() const {
  return WebRequestAction::ACTION_REMOVE_RESPONSE_HEADER;
}

LinkedPtrEventResponseDelta
WebRequestRemoveResponseHeaderAction::CreateDelta(
    const WebRequestRule::RequestData& request_data,
    const std::string& extension_id,
    const base::Time& extension_install_time) const {
  CHECK(request_data.stage & GetStages());
  net::HttpResponseHeaders* headers =
      request_data.original_response_headers;
  if (!headers)
    return LinkedPtrEventResponseDelta(NULL);

  LinkedPtrEventResponseDelta result(
      new helpers::EventResponseDelta(extension_id, extension_install_time));
  void* iter = NULL;
  std::string current_value;
  while (headers->EnumerateHeader(&iter, name_, &current_value)) {
    if (has_value_ &&
           (current_value.size() != value_.size() ||
            !std::equal(current_value.begin(), current_value.end(),
                        value_.begin(),
                        base::CaseInsensitiveCompare<char>()))) {
      continue;
    }
    result->deleted_response_headers.push_back(make_pair(name_, current_value));
  }
  return result;
}

//
// WebRequestIgnoreRulesAction
//

WebRequestIgnoreRulesAction::WebRequestIgnoreRulesAction(
    int minimum_priority)
    : minimum_priority_(minimum_priority) {
}

WebRequestIgnoreRulesAction::~WebRequestIgnoreRulesAction() {}

int WebRequestIgnoreRulesAction::GetStages() const {
  return ON_BEFORE_REQUEST | ON_BEFORE_SEND_HEADERS | ON_HEADERS_RECEIVED |
      ON_AUTH_REQUIRED;
}

WebRequestAction::Type WebRequestIgnoreRulesAction::GetType() const {
  return WebRequestAction::ACTION_IGNORE_RULES;
}

int WebRequestIgnoreRulesAction::GetMinimumPriority() const {
  return minimum_priority_;
}

bool WebRequestIgnoreRulesAction::ShouldEnforceHostPermissions() const {
  return false;
}

LinkedPtrEventResponseDelta WebRequestIgnoreRulesAction::CreateDelta(
    const WebRequestRule::RequestData& request_data,
    const std::string& extension_id,
    const base::Time& extension_install_time) const {
  CHECK(request_data.stage & GetStages());
  return LinkedPtrEventResponseDelta(NULL);
}

//
// WebRequestRequestCookieAction
//

WebRequestRequestCookieAction::WebRequestRequestCookieAction(
    linked_ptr<RequestCookieModification> request_cookie_modification)
    : request_cookie_modification_(request_cookie_modification) {
  CHECK(request_cookie_modification_.get());
}

WebRequestRequestCookieAction::~WebRequestRequestCookieAction() {}

int WebRequestRequestCookieAction::GetStages() const {
  return ON_BEFORE_SEND_HEADERS;
}

WebRequestAction::Type WebRequestRequestCookieAction::GetType() const {
  return WebRequestAction::ACTION_MODIFY_REQUEST_COOKIE;
}

LinkedPtrEventResponseDelta WebRequestRequestCookieAction::CreateDelta(
    const WebRequestRule::RequestData& request_data,
    const std::string& extension_id,
    const base::Time& extension_install_time) const {
  CHECK(request_data.stage & GetStages());
  LinkedPtrEventResponseDelta result(
      new extension_web_request_api_helpers::EventResponseDelta(
          extension_id, extension_install_time));
  result->request_cookie_modifications.push_back(
      request_cookie_modification_);
  return result;
}

//
// WebRequestResponseCookieAction
//

WebRequestResponseCookieAction::WebRequestResponseCookieAction(
    linked_ptr<ResponseCookieModification> response_cookie_modification)
    : response_cookie_modification_(response_cookie_modification) {
  CHECK(response_cookie_modification_.get());
}

WebRequestResponseCookieAction::~WebRequestResponseCookieAction() {}

int WebRequestResponseCookieAction::GetStages() const {
  return ON_HEADERS_RECEIVED;
}

WebRequestAction::Type WebRequestResponseCookieAction::GetType() const {
  return WebRequestAction::ACTION_MODIFY_RESPONSE_COOKIE;
}

LinkedPtrEventResponseDelta WebRequestResponseCookieAction::CreateDelta(
    const WebRequestRule::RequestData& request_data,
    const std::string& extension_id,
    const base::Time& extension_install_time) const {
  CHECK(request_data.stage & GetStages());
  LinkedPtrEventResponseDelta result(
      new extension_web_request_api_helpers::EventResponseDelta(
          extension_id, extension_install_time));
  result->response_cookie_modifications.push_back(
      response_cookie_modification_);
  return result;
}

}  // namespace extensions


text:
namespace Pomdog {
namespace Concurrency {
namespace {

static std::shared_ptr<Scheduler> ambientScheduler =
    std::make_shared<ImmediateScheduler>();

} // unnamed namespace
//-----------------------------------------------------------------------
std::shared_ptr<Scheduler> GetAmbientScheduler()
{
    return ambientScheduler;
}
//-----------------------------------------------------------------------
void SetAmbientScheduler(const std::shared_ptr<Scheduler>& scheduler)
{
    ambientScheduler = scheduler;
}
//-----------------------------------------------------------------------
void Get(const Task<void>& task)
{
    task.Wait();
    if (auto execption = Detail::TaskImpl::GetExceptionPointer(task)) {
        std::rethrow_exception(execption);
    }
}
//-----------------------------------------------------------------------
Task<void> Delay(
    const Duration& dueTime,
    const std::shared_ptr<Scheduler>& scheduler)
{
    POMDOG_ASSERT(scheduler);
    TaskCompletionSource<void> tcs(scheduler);
    scheduler->Schedule([tcs] { tcs.SetResult(); }, dueTime);
    return CreateTask(tcs);
}
//-----------------------------------------------------------------------
Task<void> FromResult(
    const std::shared_ptr<Scheduler>& scheduler)
{
    POMDOG_ASSERT(scheduler);
    TaskCompletionSource<void> tcs(scheduler);
    tcs.SetResult();
    return CreateTask(tcs);
}
//-----------------------------------------------------------------------
namespace Detail {

Task<void> WhenAllImpl(
    const std::vector<Task<void>>& tasks,
    const std::shared_ptr<Scheduler>& scheduler)
{
    if (tasks.empty()) {
        return FromResult(scheduler);
    }

    POMDOG_ASSERT(!tasks.empty());
    POMDOG_ASSERT(scheduler);

    TaskCompletionSource<void> tcs(scheduler);
    auto whenAllPromise = std::make_shared<Detail::WhenAllPromise<void>>();
    whenAllPromise->count = static_cast<int>(tasks.size());
    whenAllPromise->isRejected = false;

    for (auto & task : tasks) {
        task.ContinueWith([tcs, whenAllPromise](const Task<void>& t) {
            std::lock_guard<std::mutex> lock(whenAllPromise->mutex);
            if (whenAllPromise->isRejected) {
                return;
            }
            if (t.IsRejected()) {
                whenAllPromise->isRejected = true;
                tcs.SetException(TaskImpl::GetExceptionPointer(t));
            }
            else {
                --whenAllPromise->count;
                POMDOG_ASSERT(whenAllPromise->count >= 0);
                if (whenAllPromise->count <= 0) {
                    tcs.SetResult();
                }
            }
        });
    }
    return CreateTask(tcs);
}

} // namespace Detail
//-----------------------------------------------------------------------
} // namespace Concurrency
} // namespace Pomdog


text:
/*
Title: Export CSV Dengan Custom Delimeter
Date: 2014/01/29
Page: post
Labels: php
*/

Microsoft excel memiliki kemampuan untuk meng-expor data menjadi file csv. Standar csv hasil expor excel menggunakan delimeter atau pemisah koma (,). Namun untuk kebutuhan tertentu perlu menggunakan pemisah titik koma (;).

Tidak ada opsi khusus untuk merubah dari koma ke titik koma, kecuali dengan bersusah payah merubah regional setting dicontrol panel windows. Jika sekali atau dua kali tidak menyulitkan. Jika sering, bisa berganti menggunakan fungsi macro ini.

Option Explicit
    Sub save2csv()
    Dim lastColumn As Integer
    Dim lastRow As Integer
    Dim strString As String
    Dim i As Integer, j As Integer
    lastColumn = ActiveSheet.UsedRange.Column - 1 + ActiveSheet.UsedRange.Columns.Count
    lastRow = ActiveSheet.UsedRange.Rows(ActiveSheet.UsedRange.Rows.Count).Row

    Open "output.csv" For Output As #1

    For i = 1 To lastRow
    Cells(i, 1).Select
    strString = ""
    For j = 1 To lastColumn
    If j &lt;&gt; lastColumn Then
    strString = strString &amp; Cells(i, j).Value &amp; ";"
    Else
    strString = strString &amp; Cells(i, j).Value
    End If
    Next j
    Print #1, strString
    Next i

    Close #1

End Sub

Referensi:
superuser.com


text:
ACCEPTED

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

#### Published in
Framm. Lichenogr. 26 (1855)

#### Original name
Psora bischoffii Hepp

### Remarks
null