text:
package com.itheima.zhbj52.base;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.itheima.zhbj52.R;
import com.itheima.zhbj52.activity.NewsDetailActivity;
import com.itheima.zhbj52.domain.NewsData.NewsMenuData.NewsTabData;
import com.itheima.zhbj52.domain.TabData;
import com.itheima.zhbj52.domain.TabData.TabNewsData;
import com.itheima.zhbj52.domain.TabData.TopNewsData;
import com.itheima.zhbj52.global.GlobalConstants;
import com.itheima.zhbj52.utils.CacheUtils;
import com.itheima.zhbj52.utils.PrefUtils;
import com.itheima.zhbj52.view.RefreshListView;
import com.itheima.zhbj52.view.RefreshListView.OnRefreshListener;
import com.itheima.zhbj52.view.TopNewsViewPager;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.viewpagerindicator.CirclePageIndicator;

public class TabDetailPager extends BaseMenuDetailPager implements
		OnPageChangeListener {

	private NewsTabData mNewsTabData;
	private String mUrl;
	private TabData mTabData;

	@ViewInject(R.id.vp_news)
	private TopNewsViewPager mViewPager;
	@ViewInject(R.id.tv_title)
	private TextView tvTitle; // 头条新闻标题
	@ViewInject(R.id.indicator)
	private CirclePageIndicator mIndicator; // 头条新闻指示器
	@ViewInject(R.id.lv_list)
	private RefreshListView lvList; // 新闻列表

	private ArrayList<TopNewsData> mTopNewsList;// 头条新闻数据集合
	private ArrayList<TabNewsData> mTabNewsList; // 新闻列表数据集合
	private NewsAdapter mNewsAdapter;
	private String mMoreUrl; // 更多页面的地址
	private TopNewsAdapter mTopNewsAdapter;

	private Handler mHandler;

	public TabDetailPager(Activity mActivity, NewsTabData newsTabData) {
		super(mActivity);
		mNewsTabData = newsTabData;
		mUrl = GlobalConstants.SERVER_URL + mNewsTabData.url;
	}

	@Override
	public View initView() {
		View view = View.inflate(mActivity, R.layout.tab_detail_pager, null);
		// 加载头布局
		View headerView = View.inflate(mActivity, R.layout.list_header_topnews,
				null);
		ViewUtils.inject(this, view);
		ViewUtils.inject(this, headerView);
		// 将头条新闻以头布局的形式加给ListView
		lvList.addHeaderView(headerView);

		// 设置下拉刷新监听
		lvList.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				getDataFromServer();
			}

			@Override
			public void onLoadMore() {
				if (mMoreUrl != null) {
					getMoreDataFromServer();
				} else {
					Toast.makeText(mActivity, "到底啦~", Toast.LENGTH_SHORT)
							.show();
					lvList.onRefreshComplete(false);// 收起脚布局
				}
			}
		});

		lvList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				System.out.println("被点击:" + position);

				String ids = PrefUtils.getString(mActivity, "read_ids", "");
				String readId = mTabNewsList.get(position).id;
				if (!ids.contains(readId)) {
					ids = ids + readId + ",";
					PrefUtils.setString(mActivity, "read_ids", ids);
				}
				// mNewsAdapter.notifyDataSetChanged();
				changeReadState(view); // 实现局部见面刷新
				// 跳转新闻详情页
				Intent intent = new Intent();
				intent.setClass(mActivity, NewsDetailActivity.class);
				intent.putExtra("url", mTabNewsList.get(position).url);
				mActivity.startActivity(intent);

			}
		});

		return view;
	}

	/**
	 * 改变已读新闻颜色
	 */
	public void changeReadState(View view) {
		TextView tvTitle = (TextView) view.findViewById(R.id.tv_title);
		tvTitle.setTextColor(Color.GRAY);
	}

	@Override
	public void initData() {
		String cache = CacheUtils.getCache(mActivity, mUrl);
		if (!TextUtils.isEmpty(cache)) {
			parseData(cache, false);
		}
		getDataFromServer();

	}

	private void getDataFromServer() {
		HttpUtils utils = new HttpUtils();
		utils.send(HttpMethod.GET, mUrl, new RequestCallBack<String>() {

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				String result = responseInfo.result;
				System.out.println("页签详情页返回结果:" + result);
				parseData(result, false);
				// 设置缓存
				CacheUtils.setCache(mActivity, mUrl, result);
				lvList.onRefreshComplete(true);
			}

			@Override
			public void onFailure(HttpException error, String msg) {
				Toast.makeText(mActivity, msg, Toast.LENGTH_SHORT).show();
				error.printStackTrace();
				lvList.onRefreshComplete(false);
			}
		});
	}

	/**
	 * 加载下一页数据
	 */
	private void getMoreDataFromServer() {
		HttpUtils utils = new HttpUtils();
		utils.send(HttpMethod.GET, mMoreUrl, new RequestCallBack<String>() {

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				String result = responseInfo.result;
				System.out.println("页签详情页返回结果:" + result);
				parseData(result, true);
				lvList.onRefreshComplete(true);
			}

			@Override
			public void onFailure(HttpException error, String msg) {
				Toast.makeText(mActivity, msg, Toast.LENGTH_SHORT).show();
				error.printStackTrace();
				lvList.onRefreshComplete(false);
			}
		});
	}

	protected void parseData(String result, boolean isMore) {
		Gson gson = new Gson();
		mTabData = gson.fromJson(result, TabData.class);
		// 处理下一页的链接
		String more = mTabData.data.more;
		if (!TextUtils.isEmpty(more)) {
			mMoreUrl = GlobalConstants.SERVER_URL + more;
		} else {
			mMoreUrl = null;
		}

		if (!isMore) {
			mTopNewsList = mTabData.data.topnews;
			mTabNewsList = mTabData.data.news;
			if (mTopNewsList != null) {
				mTopNewsAdapter = new TopNewsAdapter();
				mViewPager.setAdapter(mTopNewsAdapter);

				mIndicator.setViewPager(mViewPager);
				mIndicator.setSnap(true); // 支持快照显示
				mIndicator.setOnPageChangeListener(this);

				mIndicator.onPageSelected(0);// 让指示器重新定位到第一个点

				tvTitle.setText(mTopNewsList.get(0).title);
			}
			if (mTabNewsList != null) {
				mNewsAdapter = new NewsAdapter();
				lvList.setAdapter(mNewsAdapter); // 填充新闻列表
			}
			// 自动轮播条显示
			if (mHandler == null) {
				mHandler = new Handler() {
					public void handleMessage(android.os.Message msg) {
						int currentItem = mViewPager.getCurrentItem();
						if (currentItem < mTopNewsList.size() - 1) {
							currentItem++;
						} else {
							currentItem = 0;
						}
						mViewPager.setCurrentItem(currentItem);
						mHandler.sendEmptyMessageDelayed(0, 3000);// 形成循环
					};
				};
				mHandler.sendEmptyMessageDelayed(0, 3000); // 延时3秒发消息
			}
		} else { // 如果是加载下一页,需要将数据追加给原来的集合
			ArrayList<TabNewsData> news = mTabData.data.news;
			mTabNewsList.addAll(news);
			mNewsAdapter.notifyDataSetChanged();
			mTopNewsAdapter.notifyDataSetChanged(); // 必须同时更新头布局!
		}

	}

	/**
	 * 头条新闻适配器
	 */
	class TopNewsAdapter extends PagerAdapter {

		BitmapUtils bitmapUtils;

		public TopNewsAdapter() {
			bitmapUtils = new BitmapUtils(mActivity);
			bitmapUtils
					.configDefaultLoadingImage(R.drawable.topnews_item_default);// 设置默认加载的图片
		}

		@Override
		public int getCount() {
			return mTabData.data.topnews.size();
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view == object;
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			ImageView mImage = new ImageView(mActivity);
			mImage.setScaleType(ScaleType.FIT_XY); // 基于控件大小填充图片
			TopNewsData topNewsData = mTopNewsList.get(position);
			bitmapUtils.display(mImage, topNewsData.topimage); // 传入imageView对象和图片地址
			container.addView(mImage);

			mImage.setOnTouchListener(new TopNewsTouchListener());// 设置触摸监听
			return mImage;
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView((View) object);
		}
	}

	/**
	 * 头条新闻的触摸监听
	 *
	 * @author baoliang.zhao
	 *
	 */
	class TopNewsTouchListener implements OnTouchListener {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				mHandler.removeCallbacksAndMessages(null); // 删除handler中的所有消息
				break;
			case MotionEvent.ACTION_UP:
				mHandler.sendEmptyMessageDelayed(0, 3000); // 延时3秒发消息
				break;
			case MotionEvent.ACTION_CANCEL:
				mHandler.sendEmptyMessageDelayed(0, 3000); // 延时3秒发消息
				break;

			default:
				break;
			}
			return true;
		}

	}

	/**
	 * 新闻列表适配器
	 *
	 * @author baoliang.zhao
	 *
	 */
	class NewsAdapter extends BaseAdapter {
		private BitmapUtils utils;

		public NewsAdapter() {
			utils = new BitmapUtils(mActivity);
			utils.configDefaultLoadingImage(R.drawable.pic_item_list_default);
		}

		@Override
		public int getCount() {
			return mTabNewsList.size();
		}

		@Override
		public TabNewsData getItem(int position) {
			return mTabNewsList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder viewHolder;
			if (convertView == null) {
				convertView = View.inflate(mActivity, R.layout.list_news_item,
						null);
				viewHolder = new ViewHolder();
				viewHolder.tvTitle = (TextView) convertView
						.findViewById(R.id.tv_title);
				viewHolder.tvDate = (TextView) convertView
						.findViewById(R.id.tv_date);
				viewHolder.ivPic = (ImageView) convertView
						.findViewById(R.id.iv_pic);
				convertView.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}
			TabNewsData item = getItem(position);
			viewHolder.tvTitle.setText(item.title);
			viewHolder.tvDate.setText(item.pubdate);
			utils.display(viewHolder.ivPic, item.listimage);

			String ids = PrefUtils.getString(mActivity, "read_ids", "");
			if (ids.contains(item.id)) {
				viewHolder.tvTitle.setTextColor(Color.GRAY);
			} else {
				viewHolder.tvTitle.setTextColor(Color.BLACK);
			}

			return convertView;
		}

	}

	static class ViewHolder {
		public TextView tvTitle;
		public TextView tvDate;
		public ImageView ivPic;
	}

	@Override
	public void onPageScrolled(int position, float positionOffset,
			int positionOffsetPixels) {

	}

	@Override
	public void onPageSelected(int position) {
		tvTitle.setText(mTopNewsList.get(position).title);
	}

	@Override
	public void onPageScrollStateChanged(int state) {

	}
}


text:
/*jshint node:true, mocha:true*/
/**
 * @author pmeijer / https://github.com/pmeijer
 */

var testFixture = require('../_globals');

describe('export CLI tests', function () {
    'use strict';

    var gmeConfig = testFixture.getGmeConfig(),
        expect = testFixture.expect,
        exportCli = require('../../src/bin/export'),
        filename = require('path').normalize('src/bin/export.js'),
        projectName = 'exportCliTest',
        //projectId = testFixture.projectName2Id(projectName),
        outputPath = './test-tmp/exportCliTest.out',
        Q = testFixture.Q,
        logger = testFixture.logger.fork('export.spec'),
        storage,
        gmeAuth,
        oldLogFunction = console.log,
        oldWarnFunction = console.warn,
        oldStdOutFunction = process.stdout.write,
        jsonProject;

    before(function (done) {
        testFixture.clearDBAndGetGMEAuth(gmeConfig, projectName)
            .then(function (gmeAuth_) {
                gmeAuth = gmeAuth_;
                storage = testFixture.getMongoStorage(logger, gmeConfig, gmeAuth);
                return storage.openDatabase();
            })
            .then(function () {
                return testFixture.importProject(storage, {
                    projectName: projectName,
                    logger: logger.fork('import'),
                    gmeConfig: gmeConfig,
                    branchName: 'master',
                    userName: gmeConfig.authentication.guestAccount,
                    projectSeed: './seeds/ActivePanels.json'
                });
            })
            .then(function () {
                jsonProject = JSON.parse(testFixture.fs.readFileSync('./seeds/ActivePanels.json'));
            })
            .nodeify(done);

    });

    after(function (done) {
        Q.allDone([
            gmeAuth.unload(),
            storage.closeDatabase(),
            Q.nfcall(testFixture.rimraf, outputPath)
        ])
            .nodeify(done);
    });

    beforeEach(function () {
        console.log = function () {
        };
        process.stdout.write = function () {
        };
        console.warn = function () {

        };
    });

    afterEach(function () {
        console.log = oldLogFunction;
        console.warn = oldWarnFunction;
        process.stdout.write = oldStdOutFunction;
    });

    it('should have a main', function () {
        exportCli.should.have.property('main');
    });

    it('should fail if mandatory parameters missing', function (done) {
        exportCli.main(['node', filename])
            .then(function () {
                done(new Error('missing error handling'));
            })
            .catch(function (err) {
                expect(err).not.to.equal(null);
                expect(err.message).to.contain('invalid argument');
                done();
            })
            .done();
    });

    it('should fail to export if wrong owner is given', function (done) {
        exportCli.main(['node', filename,
            '-m', gmeConfig.mongo.uri,
            '-p', projectName,
            '-o', 'badOwner',
            '-u', 'badOwner',
            '-s', 'master'
        ])
            .then(function () {
                done(new Error('missing error handling'));
            })
            .catch(function (err) {
                expect(err).not.to.equal(null);
                expect(err.message).to.include('badOwner');
                done();
            })
            .done();
    });

    it('should fail to export from a wrong branch', function (done) {
        exportCli.main(['node', filename,
            '-p', projectName,
            '-u', gmeConfig.authentication.guestAccount,
            '-s', 'badBranch'
        ])
            .then(function () {
                done(new Error('missing error handling'));
            })
            .catch(function (err) {
                expect(err).not.to.equal(null);
                expect(err.message).to.include('badBranch');
                done();
            })
            .done();
    });

    it('should export the project to the console', function (done) {
        exportCli.main(['node', filename,
            '-p', projectName,
            '-u', gmeConfig.authentication.guestAccount,
            '-s', 'master'
        ])
            .then(function () {
                done();
            })
            .catch(done);
    });

    it('should export the project into a file', function (done) {
        exportCli.main(['node', filename,
            '-p', projectName,
            '-s', 'master',
            '-f', outputPath
        ])
            .then(function () {
                var output = JSON.parse(testFixture.fs.readFileSync(outputPath));
                expect(output).to.deep.equal(jsonProject);

                done();
            })
            .catch(done);
    });

    it('should export using the programmatic interface', function (done) {
        exportCli.run({gmeConfig: gmeConfig,
                       projectName: projectName,
                       source: 'master',
                       outFile: outputPath})
            .then(function () {
                var output = JSON.parse(testFixture.fs.readFileSync(outputPath));
                expect(output).to.deep.equal(jsonProject);

                done();
            })
            .catch(done);
    });
});

redpajama_set_name: RedPajamaGithub


text:
from spec import Spec, skip, eq_, raises, ok_
from mock import Mock

from invoke.context import Context
from invoke.tasks import task, Task, Call
from invoke.loader import FilesystemLoader as Loader

from _util import support

#
# NOTE: Most Task tests use @task as it's the primary interface and is a very
# thin wrapper around Task itself. This way we don't have to write 2x tests for
# both Task and @task. Meh :)
#

def _func(ctx):
    pass

class task_(Spec):
    "@task"

    def setup(self):
        self.loader = Loader(start=support)
        self.vanilla = self.loader.load('decorator')

    def allows_access_to_wrapped_object(self):
        def lolcats(ctx):
            pass
        eq_(task(lolcats).body, lolcats)

    def allows_alias_specification(self):
        eq_(self.vanilla['foo'], self.vanilla['bar'])

    def allows_multiple_aliases(self):
        eq_(self.vanilla['foo'], self.vanilla['otherbar'])

    def allows_default_specification(self):
        eq_(self.vanilla[''], self.vanilla['biz'])

    def has_autoprint_option(self):
        ap = self.loader.load('autoprint')
        eq_(ap['nope'].autoprint, False)
        eq_(ap['yup'].autoprint, True)

    @raises(ValueError)
    def raises_ValueError_on_multiple_defaults(self):
        self.loader.load('decorator_multi_default')

    def sets_arg_help(self):
        eq_(self.vanilla['punch'].help['why'], 'Motive')

    def sets_arg_kind(self):
        skip()

    def sets_which_args_are_optional(self):
        eq_(self.vanilla['optional_values'].optional, ('myopt',))

    def allows_annotating_args_as_positional(self):
        eq_(self.vanilla['one_positional'].positional, ['pos'])
        eq_(self.vanilla['two_positionals'].positional, ['pos1', 'pos2'])

    def when_positional_arg_missing_all_non_default_args_are_positional(self):
        eq_(self.vanilla['implicit_positionals'].positional, ['pos1', 'pos2'])

    def context_arguments_should_not_appear_in_implicit_positional_list(self):
        @task
        def mytask(ctx):
            pass
        eq_(len(mytask.positional), 0)

    def pre_tasks_stored_directly(self):
        @task
        def whatever(ctx):
            pass
        @task(pre=[whatever])
        def func(ctx):
            pass
        eq_(func.pre, [whatever])

    def allows_star_args_as_shortcut_for_pre(self):
        @task
        def pre1(ctx):
            pass
        @task
        def pre2(ctx):
            pass
        @task(pre1, pre2)
        def func(ctx):
            pass
        eq_(func.pre, (pre1, pre2))

    @raises(TypeError)
    def disallows_ambiguity_between_star_args_and_pre_kwarg(self):
        @task
        def pre1(ctx):
            pass
        @task
        def pre2(ctx):
            pass
        @task(pre1, pre=[pre2])
        def func(ctx):
            pass

    def sets_name(self):
        @task(name='foo')
        def bar(ctx):
            pass
        eq_(bar.name, 'foo')

class Task_(Spec):
    def has_useful_repr(self):
        i = repr(Task(_func))
        assert '_func' in i, "'func' not found in {0!r}".format(i)
        e = repr(Task(_func, name='funky'))
        assert 'funky' in e, "'funky' not found in {0!r}".format(e)
        assert '_func' not in e, "'_func' unexpectedly seen in {0!r}".format(e)

    def equality_testing(self):
        t1 = Task(_func, name='foo')
        t2 = Task(_func, name='foo')
        eq_(t1, t2)
        t3 = Task(_func, name='bar')
        assert t1 != t3

    class attributes:
        def has_default_flag(self):
            eq_(Task(_func).is_default, False)

        def name_defaults_to_body_name(self):
            eq_(Task(_func).name, '_func')

        def can_override_name(self):
            eq_(Task(_func, name='foo').name, 'foo')

    class callability:
        def setup(self):
            @task
            def foo(ctx):
                "My docstring"
                return 5
            self.task = foo

        def dunder_call_wraps_body_call(self):
            context = Context()
            eq_(self.task(context), 5)

        @raises(TypeError)
        def errors_if_first_arg_not_Context(self):
            @task
            def mytask(ctx):
                pass
            mytask(5)

        @raises(TypeError)
        def errors_if_no_first_arg_at_all(self):
            @task
            def mytask():
                pass

        def tracks_times_called(self):
            context = Context()
            eq_(self.task.called, False)
            self.task(context)
            eq_(self.task.called, True)
            eq_(self.task.times_called, 1)
            self.task(context)
            eq_(self.task.times_called, 2)

        def wraps_body_docstring(self):
            eq_(self.task.__doc__, "My docstring")

        def wraps_body_name(self):
            eq_(self.task.__name__, "foo")

    class get_arguments:
        def setup(self):
            @task(positional=['arg_3', 'arg1'], optional=['arg1'])
            def mytask(ctx, arg1, arg2=False, arg_3=5):
                pass
            self.task = mytask
            self.args = self.task.get_arguments()
            self.argdict = self._arglist_to_dict(self.args)

        def _arglist_to_dict(self, arglist):
            # This kinda duplicates Context.add_arg(x) for x in arglist :(
            ret = {}
            for arg in arglist:
                for name in arg.names:
                    ret[name] = arg
            return ret

        def _task_to_dict(self, task):
            return self._arglist_to_dict(task.get_arguments())

        def positional_args_come_first(self):
            eq_(self.args[0].name, 'arg_3')
            eq_(self.args[1].name, 'arg1')
            eq_(self.args[2].name, 'arg2')

        def kinds_are_preserved(self):
            eq_(
                [x.kind for x in self.args],
                # Remember that the default 'kind' is a string.
                [int, str, bool]
            )

        def positional_flag_is_preserved(self):
            eq_(
                [x.positional for x in self.args],
                [True, True, False]
            )

        def optional_flag_is_preserved(self):
            eq_(
                [x.optional for x in self.args],
                [False, True, False]
            )

        def turns_function_signature_into_Arguments(self):
            eq_(len(self.args), 3, str(self.args))
            assert 'arg2' in self.argdict

        def shortflags_created_by_default(self):
            assert 'a' in self.argdict
            assert self.argdict['a'] is self.argdict['arg1']

        def shortflags_dont_care_about_positionals(self):
            "Positionalness doesn't impact whether shortflags are made"
            for short, long_ in (
                ('a', 'arg1'),
                ('r', 'arg2'),
                ('g', 'arg-3'),
            ):
                assert self.argdict[short] is self.argdict[long_]

        def autocreated_short_flags_can_be_disabled(self):
            @task(auto_shortflags=False)
            def mytask(ctx, arg):
                pass
            args = self._task_to_dict(mytask)
            assert 'a' not in args
            assert 'arg' in args

        def autocreated_shortflags_dont_collide(self):
            "auto-created short flags don't collide"
            @task
            def mytask(ctx, arg1, arg2, barg):
                pass
            args = self._task_to_dict(mytask)
            assert 'a' in args
            assert args['a'] is args['arg1']
            assert 'r' in args
            assert args['r'] is args['arg2']
            assert 'b' in args
            assert args['b'] is args['barg']

        def early_auto_shortflags_shouldnt_lock_out_real_shortflags(self):
            # I.e. "task --foo -f" => --foo should NOT get to pick '-f' for its
            # shortflag or '-f' is totally fucked.
            @task
            def mytask(ctx, longarg, l):
                pass
            args = self._task_to_dict(mytask)
            assert 'longarg' in args
            assert 'o' in args
            assert args['o'] is args['longarg']
            assert 'l' in args

        def context_arguments_are_not_returned(self):
            @task
            def mytask(ctx):
                pass
            eq_(len(mytask.get_arguments()), 0)

        def underscores_become_dashes(self):
            @task
            def mytask(ctx, longer_arg):
                pass
            arg = mytask.get_arguments()[0]
            eq_(arg.names, ('longer-arg', 'l'))
            eq_(arg.attr_name, 'longer_arg')
            eq_(arg.name, 'longer_arg')

class Call_(Spec):
    def setup(self):
        self.task = Task(Mock(__name__='mytask'))

    class stringrep:
        "__str__"

        def includes_task_name(self):
            call = Call(self.task)
            eq_(str(call), "<Call 'mytask', args: (), kwargs: {}>")

        def includes_args_and_kwargs(self):
            call = Call(
                self.task,
                args=('posarg1', 'posarg2'),
                # Single-key dict to avoid dict ordering issues
                kwargs={'kwarg1': 'val1'},
            )
            eq_(str(call), "<Call 'mytask', args: ('posarg1', 'posarg2'), kwargs: {'kwarg1': 'val1'}>") # noqa

        def includes_aka_if_explicit_name_given(self):
            call = Call(self.task, called_as='notmytask')
            eq_(str(call), "<Call 'mytask' (called as: 'notmytask'), args: (), kwargs: {}>") # noqa

        def skips_aka_if_explicit_name_same_as_task_name(self):
            call = Call(self.task, called_as='mytask')
            eq_(str(call), "<Call 'mytask', args: (), kwargs: {}>")

    class clone:
        def returns_new_but_equivalent_object(self):
            orig = Call(self.task)
            clone = orig.clone()
            ok_(clone is not orig)
            ok_(clone == orig)

        def modifications_on_clone_do_not_alter_original(self):
            # Setup
            orig = Call(
                self.task,
                called_as='foo',
                args=[1, 2, 3],
                kwargs={'key': 'val'}
            )
            context = Context()
            context['setting'] = 'value'
            orig.context = context
            # Clone & tweak
            clone = orig.clone()
            newtask = Task(Mock(__name__='meh'))
            clone.task = newtask
            clone.called_as = 'notfoo'
            clone.args[0] = 7
            clone.kwargs['key'] = 'notval'
            clone.context['setting'] = 'notvalue'
            # Compare
            ok_(clone.task is not orig.task)
            eq_(orig.called_as, 'foo')
            eq_(clone.called_as, 'notfoo')
            eq_(orig.args, [1, 2, 3])
            eq_(clone.args, [7, 2, 3])
            eq_(orig.kwargs['key'], 'val')
            eq_(clone.kwargs['key'], 'notval')
            eq_(orig.context['setting'], 'value')
            eq_(clone.context['setting'], 'notvalue')


text:
class Home
end


text:
var geocoder;
var map;
function initialize()
    {
    //'use strict';
    geocoder = new google.maps.Geocoder();

    var latlng = new google.maps.LatLng(43.16103, -77.6109219);
    var mapOptions = {
        zoom: 11,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
        };
    var map_canvas = document.getElementById("map_canvas");
    if (map_canvas === null)
        {
        console.log("Error: failed to find map_canvas element in document!");
        }
    map = new google.maps.Map(map_canvas, mapOptions);
    }

function codeAddress()
    {
    'use strict';
    var address = document.getElementById("address").value;
    geocoder.geocode( {'address': address},
        function(results, status)
            {
            'use strict';
            if (status == google.maps.GeocoderStatus.OK)
                {
                //map.setCenter(results[0].geometry.location);
                //var marker = new google.maps.Marker({
                //    map: map,
                //    position: results[0].geometry.location
                //});
                console.log("Position: "+results[0].geometry.location);
                document.getElementById("points").innerText +=
                            ("\nPosition: "+results[0].geometry.location);
                }
            else
                {
                alert("Geocode was not successful for the following reason: " + status);
                }
            });
    } // codeAddress()

function processSiteList()
    {
    'use strict';
    var sitelist_text = document.getElementById("site-list").value;
    console.log("Site List:", sitelist_text);

    document.getElementById("kml-output").value = '';

    var sitelist = sitelist_text.split("\n");
    console.log("sitelist: ", sitelist);

    processSiteSpec(0, sitelist);
    } // processSiteList()

function processSiteSpec(index, sitelist)
    {
    'use strict';
    // stop the process at the end
    if (index >= sitelist.length)
        {
        return;
        }

    var sitespec = sitelist[index];
    console.log(""+index+": "+sitespec);
    // skip blank lines
    if (sitespec == undefined || sitespec.trim() == '')
        {
        //continue;
        processSiteSpec(index+1, sitelist);
        return;
        }
    var attrs = sitespec.split("|", 3);

    var camp_code = attrs[0].trim();
    var sitenum = attrs[1].trim();
    var address = attrs[2].trim();
    console.log(""+index+"*  ", camp_code, sitenum, address);

    var camp = undefined;
    if (camp_code == 'W')
        { camp = 'west'; }
    if (camp_code == 'E')
        { camp = 'east'; }

    // Only process 10 at a time because that is the limit without
    // an API key
    var start_index = $('input[name="start-index"]:checked').val();
    start_index = parseInt(start_index);
    var end_index = start_index + 10;
    //if (! (0 <= index && index < 10) )
    //if (! (10 <= index && index < 20) )
    //if (! (20 <= index && index < 30) )
    //if (! (30 <= index && index < 40) )
    //if (! (40 <= index && index < 50) )
    //if (! (50 <= index && index < 60) )
    //if (! (60 <= index && index < 70) )
    console.debug("Start index:", start_index, "End index:", end_index);
    if (! (start_index <= index && index < end_index) )
        {
        //continue;
        console.log("Skipping entry not in range:", index);
        processSiteSpec(index+1, sitelist);
        return;
        }

    createMarker(camp, sitenum, address, index+1, sitelist);
    } // processSiteSpec()

function createMarker(camp, sitenum, address, index, sitelist)
    {
    // sw, ne corners of area to search
    var LeRoy = google.maps.LatLng(42.979535,-77.99057);
    var NE = google.maps.LatLng(43.335167,-77.257233);
    var search = address;
    if (address.indexOf("NY") == -1)
        { search += " Rochester, NY"; }
    geocoder.geocode(
            {'address': search,
                // sw, ne corners of area to search
            'bounds': google.maps.LatLngBounds( LeRoy, NE ),
            },
        function(results, status)
            {
            if (status == google.maps.GeocoderStatus.OK)
                {
                var location = results[0].geometry.location;

                console.log("#"+sitenum+" Position: "+location);
                document.getElementById("points").innerText +=
                    ("\n"+
                     camp+" - #"+sitenum+": "+address+"  -> "+location);

                //document.getElementById("kml-output").value +=
                //    ("\n"+
                //     camp+" - #"+sitenum+": "+address+"  -> "+location);

                var template = document.getElementById('placemark-template').value;
                var text = template.replace(/\{sitenum\}/g, sitenum)
                                   .replace(/\{address\}/g, address)
                                   .replace(/\{lat\}/g, location.lat())
                                   .replace(/\{long\}/g, location.lng())
                                   .replace('{camp}', camp)
                                   ;
                document.getElementById("kml-output").value += text;

                //var template = $('#placemark-template').value;
                //var text = $(template).format(

                var marker = new google.maps.Marker({
                    map: map,
                    position: location,
                    icon:
                        camp == 'east'
                            ?  "https://maps-api-ssl.google.com/intl/en_us/mapfiles/ms/micons/lightblue.png"
                            : "https://maps-api-ssl.google.com/intl/en_us/mapfiles/ms/micons/green.png"
                    });

                // process the next site in the list
                processSiteSpec(index, sitelist);
                }
            else
                {
                alert("Geocode was not successful for the following reason: " + status);
                }
            });
    } // createMarker()


text:
const WebWorkerPromise = require('./index');

class WorkerPool {
  constructor({create, maxThreads, terminateAfterDelay, maxConcurrentPerWorker}) {
    this._queue = [];
    this._workers = [];
    this._createWorker = create;
    this._maxThreads = maxThreads;
    this._terminateAfterDelay = terminateAfterDelay;
    this._maxConcurrentPerWorker = maxConcurrentPerWorker;

    const worker = this._createWebWorker();
    this._workers.push(worker);
  }

  /**
   const pool = WorkerPool.create({
    src: 'my-worker.js',
    // or create: () => new Worker()
    maxThreads: 2
   });
   */

  static create(opts) {
    if(!opts.create)
      opts.create = () => new Worker(opts.src);

    if(!opts.terminateAfterDelay)
      opts.terminateAfterDelay = 5000;
    if(!opts.maxThreads)
      opts.maxThreads = 2;
    if(!opts.maxConcurrentPerWorker) {
      opts.maxConcurrentPerWorker = 1;
    }

    if(!Number.isInteger(opts.maxThreads) || !Number.isInteger(opts.maxConcurrentPerWorker)){
      console.warn('WARNING: The maxThreads and maxConcurrentPerWorker parameters should be integers equal or greater than 1');
    }

    return new WorkerPool(opts);
  }

  exec(...args) {
    const worker = this.getFreeWorkerOrCreate();
    if(worker)
      return this._exec(worker, 'exec', args);

    return new Promise(res => this._queue.push(['exec', args, res]));
  }

  postMessage(...args) {
    const worker = this.getFreeWorkerOrCreate();
    if(worker){
      return this._exec(worker, 'postMessage', args);
    }

    return new Promise(res => this._queue.push(['postMessage', args, res]));
  }

  _exec(worker, method, args) {
    return new Promise((res, rej) => {
      worker[method](...args)
        .then((result) => {
          this._onWorkDone(worker);
          res(result);
        })
        .catch(e => {
          this._onWorkDone(worker);
          rej(e);
        });
    });
  }

  // if there is unresolved jobs, run them
  // or remove unused workers

  _onWorkDone() {
    if(this._queue.length) {
      let worker;
      while(this._queue.length && (worker = this.getFreeWorkerOrCreate())) {
        let [method, args, cb] = this._queue.shift();
        cb(this._exec(worker, method, args));
      }
    }

    const freeWorkers = this.getAllFreeWorkers();
    if(freeWorkers.length) {
      this._waitAndRemoveWorkers(freeWorkers);
    }
  }

  // remove workers if its not using after delay
  _waitAndRemoveWorkers(workers) {
    setTimeout(() => {
      // only one worker should be alive always
      workers = workers.filter(w => w.isFree()).slice(0, this._workers.length - 1);
      workers.forEach(worker => this._removeWorker(worker));
    }, this._terminateAfterDelay);
  }

  _removeWorker(worker) {
    this._workers = this._workers.filter(w => w._id !== worker._id);
    worker.terminate();
  }

  getAllFreeWorkers() {
    return this._workers.filter(w => w.jobsLength() < this._maxConcurrentPerWorker);
  }

  getFreeWorkerOrCreate() {
    const freeWorker = this._workers.find(w => w.jobsLength() < this._maxConcurrentPerWorker);

    if(!freeWorker && this._workers.length < this._maxThreads) {
      const worker = this._createWebWorker();
      this._workers.push(worker);
      return worker;
    }

    return freeWorker;
  }

  _createWebWorker(){
    return new WebWorkerPromise(this._createWorker());
  }
}

module.exports = WorkerPool;


text:
/* global QUnit */

import { } from '../../../../editor/js/commands/SetColorCommand';

export default QUnit.module( 'Editor', () => {

	QUnit.module( 'Commands', () => {

		QUnit.module.todo( 'SetColorCommand', () => {

			QUnit.test( 'write me !', ( assert ) => {

				assert.ok( false, "everything's gonna be alright" );

			} );

		} );

	} );

} );


text:
#include "modules/common/math/math_utils.h"

#include <cmath>
#include <utility>

#include "glog/logging.h"

namespace apollo {
namespace common {
namespace math {

double Sqr(const double x) { return x * x; }

double CrossProd(const Vec2d& start_point, const Vec2d& end_point_1,
                 const Vec2d& end_point_2) {
  return (end_point_1 - start_point).CrossProd(end_point_2 - start_point);
}

double InnerProd(const Vec2d& start_point, const Vec2d& end_point_1,
                 const Vec2d& end_point_2) {
  return (end_point_1 - start_point).InnerProd(end_point_2 - start_point);
}

double CrossProd(const double x0, const double y0, const double x1,
                 const double y1) {
  return x0 * y1 - x1 * y0;
}

double InnerProd(const double x0, const double y0, const double x1,
                 const double y1) {
  return x0 * x1 + y0 * y1;
}

double WrapAngle(const double angle) {
  const double new_angle = std::fmod(angle, M_PI * 2.0);
  return new_angle < 0 ? new_angle + M_PI * 2.0 : new_angle;
}

double NormalizeAngle(const double angle) {
  double a = std::fmod(angle + M_PI, 2.0 * M_PI);
  if (a < 0.0) {
    a += (2.0 * M_PI);
  }
  return a - M_PI;
}

double AngleDiff(const double from, const double to) {
  return NormalizeAngle(to - from);
}

int RandomInt(const int s, const int t, unsigned int rand_seed) {
  if (s >= t) {
    return s;
  }
  return s + rand_r(&rand_seed) % (t - s + 1);
}

double RandomDouble(const double s, const double t, unsigned int rand_seed) {
  return s + (t - s) / 16383.0 * (rand_r(&rand_seed) & 16383);
}

// Gaussian
double Gaussian(const double u, const double std, const double x) {
  return (1.0 / std::sqrt(2 * M_PI * std * std)) *
         std::exp(-(x - u) * (x - u) / (2 * std * std));
}

// Sigmoid
double Sigmoid(const double x) { return 1.0 / (1.0 + std::exp(-x)); }

void RotateAxis(const double theta, const double x0, const double y0,
                double* x1, double* y1) {
  CHECK_NOTNULL(x1);
  CHECK_NOTNULL(y1);

  const double cos_theta = std::cos(theta);
  const double sin_theta = std::sin(theta);
  *x1 = x0 * cos_theta + y0 * sin_theta;
  *y1 = -x0 * sin_theta + y0 * cos_theta;
}

}  // namespace math
}  // namespace common
}  // namespace apollo


text:
#pragma once

#include <QtCore/QObject>
#include <QtCore/QVector>
#include <trikKernel/timeVal.h>
#include <trikControl/trikControlDeclSpec.h>
#include "deviceInterface.h"

namespace trikControl {

/// Sensor that returns a vector.
class TRIKCONTROL_EXPORT VectorSensorInterface : public QObject, public DeviceInterface
{
	Q_OBJECT

signals:
	/// Emitted when new sensor reading is ready.
	void newData(QVector<int> reading, const trikKernel::TimeVal &eventTime);

public slots:
	/// Returns current raw reading of a sensor.
	virtual QVector<int> read() const = 0;
};

}

Q_DECLARE_METATYPE(trikControl::VectorSensorInterface *)


text:
'use strict';
import prepareConfig from './prepare_config';
import prepareContainer from './prepare_container';
import createGUI from './create_gui';
import configPickerOpening from './config_picker_opening';
import configDateModify from './config_date_modify';

let datetimepicker = function datetimepicker(params = {}) {
  try {
    let config = prepareConfig(params);
    config.container = prepareContainer(config);
    config.gui = createGUI(config);

    configPickerOpening(config);
    configDateModify(config);

    return {
      remove: config.removeInstance
    };
  } catch (err) {
    console.error('Critical error:', err);
  }
};

export default datetimepicker;


text:
package org.apache.crunch.lib.join;

import static org.apache.crunch.types.avro.Avros.records;
import static org.apache.crunch.types.avro.Avros.strings;
import static org.junit.Assert.assertEquals;

import java.io.File;
import java.util.List;

import org.apache.avro.Schema;
import org.apache.avro.file.DataFileWriter;
import org.apache.avro.io.DatumWriter;
import org.apache.avro.specific.SpecificDatumWriter;
import org.apache.avro.specific.SpecificRecord;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import org.apache.crunch.MapFn;
import org.apache.crunch.PCollection;
import org.apache.crunch.Pair;
import org.apache.crunch.Pipeline;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.io.From;
import org.apache.crunch.test.Employee;
import org.apache.crunch.test.Person;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;

public class MultiAvroSchemaJoinTest {

  private File personFile;
  private File employeeFile;

  @Before
  public void setUp() throws Exception {
    this.personFile = File.createTempFile("person", ".avro");
    this.employeeFile = File.createTempFile("employee", ".avro");

    DatumWriter<Person> pdw = new SpecificDatumWriter<Person>();
    DataFileWriter<Person> pfw = new DataFileWriter<Person>(pdw);
    pfw.create(Person.SCHEMA$, personFile);
    Person p1 = new Person();
    p1.setName("Josh");
    p1.setAge(19);
    p1.setSiblingnames(ImmutableList.<CharSequence>of("Kate", "Mike"));
    pfw.append(p1);
    Person p2 = new Person();
    p2.setName("Kate");
    p2.setAge(17);
    p2.setSiblingnames(ImmutableList.<CharSequence>of("Josh", "Mike"));
    pfw.append(p2);
    Person p3 = new Person();
    p3.setName("Mike");
    p3.setAge(12);
    p3.setSiblingnames(ImmutableList.<CharSequence>of("Josh", "Kate"));
    pfw.append(p3);
    pfw.close();

    DatumWriter<Employee> edw = new SpecificDatumWriter<Employee>();
    DataFileWriter<Employee> efw = new DataFileWriter<Employee>(edw);
    efw.create(Employee.SCHEMA$, employeeFile);
    Employee e1 = new Employee();
    e1.setName("Kate");
    e1.setSalary(100000);
    e1.setDepartment("Marketing");
    efw.append(e1);
    efw.close();
  }

  @After
  public void tearDown() throws Exception {
    personFile.delete();
    employeeFile.delete();
  }

  public static class NameFn<K extends SpecificRecord> extends MapFn<K, String> {
    @Override
    public String map(K input) {
      Schema s = input.getSchema();
      Schema.Field f = s.getField("name");
      return input.get(f.pos()).toString();
    }
  }

  @Test
  public void testJoin() throws Exception {
     Pipeline p = new MRPipeline(MultiAvroSchemaJoinTest.class);
     PCollection<Person> people = p.read(From.avroFile(personFile.getAbsolutePath(), records(Person.class)));
     PCollection<Employee> employees = p.read(From.avroFile(employeeFile.getAbsolutePath(), records(Employee.class)));

     Iterable<Pair<Person, Employee>> result = people.by(new NameFn<Person>(), strings())
         .join(employees.by(new NameFn<Employee>(), strings())).values().materialize();
     List<Pair<Person, Employee>> v = Lists.newArrayList(result);
     assertEquals(1, v.size());
     assertEquals("Kate", v.get(0).first().getName().toString());
     assertEquals("Kate", v.get(0).second().getName().toString());
  }
}


text:
#include <aws/organizations/model/ListHandshakesForOrganizationRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Organizations::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

ListHandshakesForOrganizationRequest::ListHandshakesForOrganizationRequest() :
    m_filterHasBeenSet(false),
    m_nextTokenHasBeenSet(false),
    m_maxResults(0),
    m_maxResultsHasBeenSet(false)
{
}

Aws::String ListHandshakesForOrganizationRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_filterHasBeenSet)
  {
   payload.WithObject("Filter", m_filter.Jsonize());

  }

  if(m_nextTokenHasBeenSet)
  {
   payload.WithString("NextToken", m_nextToken);

  }

  if(m_maxResultsHasBeenSet)
  {
   payload.WithInteger("MaxResults", m_maxResults);

  }

  return payload.View().WriteReadable();
}

Aws::Http::HeaderValueCollection ListHandshakesForOrganizationRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "AWSOrganizationsV20161128.ListHandshakesForOrganization"));
  return headers;

}


text: jQuery.fn.load=function(n){$(window).on("load",n)};


text:
const i = require('i')

export const Inflect = { ...i() }


text:
/**
 * stepper.h - stepper motor driver: executes motion plans of planner.c using the stepper motors
 * Derived from Grbl
 *
 * Copyright (c) 2009-2011 Simen Svale Skogsrud
 *
 * Grbl is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Grbl is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Grbl.  If not, see <http://www.gnu.org/licenses/>.
 */

#ifndef STEPPER_H
#define STEPPER_H

#include "planner.h"
#include "speed_lookuptable.h"
#include "stepper_indirection.h"
#include "language.h"
#include "types.h"

class Stepper;
extern Stepper stepper;

// intRes = intIn1 * intIn2 >> 16
// uses:
// r26 to store 0
// r27 to store the byte 1 of the 24 bit result
#define MultiU16X8toH16(intRes, charIn1, intIn2) \
  asm volatile ( \
                 "clr r26 \n\t" \
                 "mul %A1, %B2 \n\t" \
                 "movw %A0, r0 \n\t" \
                 "mul %A1, %A2 \n\t" \
                 "add %A0, r1 \n\t" \
                 "adc %B0, r26 \n\t" \
                 "lsr r0 \n\t" \
                 "adc %A0, r26 \n\t" \
                 "adc %B0, r26 \n\t" \
                 "clr r1 \n\t" \
                 : \
                 "=&r" (intRes) \
                 : \
                 "d" (charIn1), \
                 "d" (intIn2) \
                 : \
                 "r26" \
               )

class Stepper {

  public:

    static block_t* current_block;  // A pointer to the block currently being traced

    #if ENABLED(ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
      static bool abort_on_endstop_hit;
    #endif

    #if ENABLED(Z_DUAL_ENDSTOPS)
      static bool performing_homing;
    #endif

  private:

    static unsigned char last_direction_bits;        // The next stepping-bits to be output
    static unsigned int cleaning_buffer_counter;

    #if ENABLED(Z_DUAL_ENDSTOPS)
      static bool locked_z_motor, locked_z2_motor;
    #endif

    // Counter variables for the Bresenham line tracer
    static long counter_X, counter_Y, counter_Z, counter_E;
    static volatile unsigned long step_events_completed; // The number of step events executed in the current block

    #if ENABLED(ADVANCE) || ENABLED(LIN_ADVANCE)
      static unsigned char old_OCR0A;
      static volatile unsigned char eISR_Rate;
      #if ENABLED(LIN_ADVANCE)
        static volatile int e_steps[E_STEPPERS];
        static int extruder_advance_k;
        static int final_estep_rate;
        static int current_estep_rate[E_STEPPERS]; // Actual extruder speed [steps/s]
        static int current_adv_steps[E_STEPPERS];  // The amount of current added esteps due to advance.
                                                  // i.e., the current amount of pressure applied
                                                  // to the spring (=filament).
      #else
        static long e_steps[E_STEPPERS];
        static long advance_rate, advance, final_advance;
        static long old_advance;
      #endif
    #endif // ADVANCE or LIN_ADVANCE

    static long acceleration_time, deceleration_time;
    //unsigned long accelerate_until, decelerate_after, acceleration_rate, initial_rate, final_rate, nominal_rate;
    static unsigned short acc_step_rate; // needed for deceleration start point
    static uint8_t step_loops, step_loops_nominal;
    static unsigned short OCR1A_nominal;

    static volatile long endstops_trigsteps[3];
    static volatile long endstops_stepsTotal, endstops_stepsDone;

    #if HAS_MOTOR_CURRENT_PWM
      #ifndef PWM_MOTOR_CURRENT
        #define PWM_MOTOR_CURRENT DEFAULT_PWM_MOTOR_CURRENT
      #endif
      static constexpr int motor_current_setting[3] = PWM_MOTOR_CURRENT;
    #endif

    //
    // Positions of stepper motors, in step units
    //
    static volatile long count_position[NUM_AXIS];

    //
    // Current direction of stepper motors (+1 or -1)
    //
    static volatile signed char count_direction[NUM_AXIS];

    //
    // Mixing extruder mix counters
    //
    #if ENABLED(MIXING_EXTRUDER)
      static long counter_M[MIXING_STEPPERS];
      #define MIXING_STEPPERS_LOOP(VAR) \
        for (uint8_t VAR = 0; VAR < MIXING_STEPPERS; VAR++) \
          if (current_block->mix_event_count[VAR])
    #endif

  public:

    //
    // Constructor / initializer
    //
    Stepper() { };

    //
    // Initialize stepper hardware
    //
    static void init();

    //
    // Interrupt Service Routines
    //

    static void isr();

    #if ENABLED(ADVANCE) || ENABLED(LIN_ADVANCE)
      static void advance_isr();
    #endif

    //
    // Block until all buffered steps are executed
    //
    static void synchronize();

    //
    // Set the current position in steps
    //
    static void set_position(const long& x, const long& y, const long& z, const long& e);
    static void set_e_position(const long& e);

    //
    // Set direction bits for all steppers
    //
    static void set_directions();

    //
    // Get the position of a stepper, in steps
    //
    static long position(AxisEnum axis);

    //
    // Report the positions of the steppers, in steps
    //
    static void report_positions();

    //
    // Get the position (mm) of an axis based on stepper position(s)
    //
    static float get_axis_position_mm(AxisEnum axis);

    //
    // The stepper subsystem goes to sleep when it runs out of things to execute. Call this
    // to notify the subsystem that it is time to go to work.
    //
    static void wake_up();

    //
    // Wait for moves to finish and disable all steppers
    //
    static void finish_and_disable();

    //
    // Quickly stop all steppers and clear the blocks queue
    //
    static void quick_stop();

    //
    // The direction of a single motor
    //
    static FORCE_INLINE bool motor_direction(AxisEnum axis) { return TEST(last_direction_bits, axis); }

    #if HAS_DIGIPOTSS
      static void digitalPotWrite(int address, int value);
    #endif
    static void microstep_ms(uint8_t driver, int8_t ms1, int8_t ms2);
    static void digipot_current(uint8_t driver, int current);
    static void microstep_mode(uint8_t driver, uint8_t stepping);
    static void microstep_readings();

    #if ENABLED(Z_DUAL_ENDSTOPS)
      static FORCE_INLINE void set_homing_flag(bool state) { performing_homing = state; }
      static FORCE_INLINE void set_z_lock(bool state) { locked_z_motor = state; }
      static FORCE_INLINE void set_z2_lock(bool state) { locked_z2_motor = state; }
    #endif

    #if ENABLED(BABYSTEPPING)
      static void babystep(const uint8_t axis, const bool direction); // perform a short step with a single stepper motor, outside of any convention
    #endif

    static inline void kill_current_block() {
      step_events_completed = current_block->step_event_count;
    }

    //
    // Handle a triggered endstop
    //
    static void endstop_triggered(AxisEnum axis);

    //
    // Triggered position of an axis in mm (not core-savvy)
    //
    static FORCE_INLINE float triggered_position_mm(AxisEnum axis) {
      return endstops_trigsteps[axis] * planner.steps_to_mm[axis];
    }

    #if ENABLED(LIN_ADVANCE)
      void advance_M905(const float &k);
      FORCE_INLINE int get_advance_k() { return extruder_advance_k; }
    #endif

  private:

    static FORCE_INLINE unsigned short calc_timer(unsigned short step_rate) {
      unsigned short timer;

      NOMORE(step_rate, MAX_STEP_FREQUENCY);

      if (step_rate > 20000) { // If steprate > 20kHz >> step 4 times
        step_rate >>= 2;
        step_loops = 4;
      }
      else if (step_rate > 10000) { // If steprate > 10kHz >> step 2 times
        step_rate >>= 1;
        step_loops = 2;
      }
      else {
        step_loops = 1;
      }

      NOLESS(step_rate, F_CPU / 500000);
      step_rate -= F_CPU / 500000; // Correct for minimal speed
      if (step_rate >= (8 * 256)) { // higher step rate
        unsigned short table_address = (unsigned short)&speed_lookuptable_fast[(unsigned char)(step_rate >> 8)][0];
        unsigned char tmp_step_rate = (step_rate & 0x00ff);
        unsigned short gain = (unsigned short)pgm_read_word_near(table_address + 2);
        MultiU16X8toH16(timer, tmp_step_rate, gain);
        timer = (unsigned short)pgm_read_word_near(table_address) - timer;
      }
      else { // lower step rates
        unsigned short table_address = (unsigned short)&speed_lookuptable_slow[0][0];
        table_address += ((step_rate) >> 1) & 0xfffc;
        timer = (unsigned short)pgm_read_word_near(table_address);
        timer -= (((unsigned short)pgm_read_word_near(table_address + 2) * (unsigned char)(step_rate & 0x0007)) >> 3);
      }
      if (timer < 100) { // (20kHz - this should never happen)
        timer = 100;
        MYSERIAL.print(MSG_STEPPER_TOO_HIGH);
        MYSERIAL.println(step_rate);
      }
      return timer;
    }

    // Initializes the trapezoid generator from the current block. Called whenever a new
    // block begins.
    static FORCE_INLINE void trapezoid_generator_reset() {

      static int8_t last_extruder = -1;

      if (current_block->direction_bits != last_direction_bits || current_block->active_extruder != last_extruder) {
        last_direction_bits = current_block->direction_bits;
        last_extruder = current_block->active_extruder;
        set_directions();
      }

      #if ENABLED(ADVANCE)

        advance = current_block->initial_advance;
        final_advance = current_block->final_advance;

        // Do E steps + advance steps
        #if ENABLED(MIXING_EXTRUDER)
          long advance_factor = (advance >> 8) - old_advance;
          // ...for mixing steppers proportionally
          MIXING_STEPPERS_LOOP(j)
            e_steps[j] += advance_factor * current_block->step_event_count / current_block->mix_event_count[j];
        #else
          // ...for the active extruder
          e_steps[TOOL_E_INDEX] += ((advance >> 8) - old_advance);
        #endif

        old_advance = advance >> 8;

      #endif

      deceleration_time = 0;
      // step_rate to timer interval
      OCR1A_nominal = calc_timer(current_block->nominal_rate);
      // make a note of the number of step loops required at nominal speed
      step_loops_nominal = step_loops;
      acc_step_rate = current_block->initial_rate;
      acceleration_time = calc_timer(acc_step_rate);
      OCR1A = acceleration_time;

      #if ENABLED(LIN_ADVANCE)
        if (current_block->use_advance_lead) {
          current_estep_rate[current_block->active_extruder] = ((unsigned long)acc_step_rate * current_block->e_speed_multiplier8) >> 8;
          final_estep_rate = (current_block->nominal_rate * current_block->e_speed_multiplier8) >> 8;
        }
      #endif

      // SERIAL_ECHO_START;
      // SERIAL_ECHOPGM("advance :");
      // SERIAL_ECHO(current_block->advance/256.0);
      // SERIAL_ECHOPGM("advance rate :");
      // SERIAL_ECHO(current_block->advance_rate/256.0);
      // SERIAL_ECHOPGM("initial advance :");
      // SERIAL_ECHO(current_block->initial_advance/256.0);
      // SERIAL_ECHOPGM("final advance :");
      // SERIAL_ECHOLN(current_block->final_advance/256.0);
    }

    static void digipot_init();
    static void microstep_init();

};

#endif // STEPPER_H


text:
<?php
// Connection Component Binding
Doctrine_Manager::getInstance()->bindComponent('Settings', 'doctrine');

/**
 * BaseSettings
 *
 * This class has been auto-generated by the Doctrine ORM Framework
 *
 * @property integer $setting_id
 * @property integer $isp_id
 * @property integer $parameter_id
 * @property string $value
 * @property Isp $Isp
 * @property SettingsParameters $SettingsParameters
 *
 * @package    ##PACKAGE##
 * @subpackage ##SUBPACKAGE##
 * @author     ##NAME## <##EMAIL##>
 * @version    SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
 */
abstract class BaseSettings extends Doctrine_Record
{
    public function setTableDefinition()
    {
        $this->setTableName('settings');
        $this->hasColumn('setting_id', 'integer', 4, array(
             'type' => 'integer',
             'fixed' => 0,
             'unsigned' => false,
             'primary' => true,
             'autoincrement' => true,
             'length' => '4',
             ));
        $this->hasColumn('isp_id', 'integer', 4, array(
             'type' => 'integer',
             'default' => 1,
             'notnull' => true,
             'length' => '4',
             ));
        $this->hasColumn('parameter_id', 'integer', 4, array(
             'type' => 'integer',
             'fixed' => 0,
             'unsigned' => false,
             'primary' => false,
             'autoincrement' => false,
             'length' => '4',
             ));
        $this->hasColumn('value', 'string', null, array(
             'type' => 'string',
             'fixed' => 0,
             'unsigned' => false,
             'primary' => false,
             'notnull' => true,
             'autoincrement' => false,
             'length' => '',
             ));
    }

    public function setUp()
    {
        parent::setUp();
        $this->hasOne('Isp', array(
             'local' => 'isp_id',
             'foreign' => 'isp_id',
             'onDelete' => 'CASCADE'));

        $this->hasOne('SettingsParameters', array(
             'local' => 'parameter_id',
             'foreign' => 'parameter_id',
             'onDelete' => 'CASCADE'));
    }
}


text:
"""
Components identify Cloud Provider
===================================

The ``Is*`` component in this module is valid if the
:py:class:`insights.combiners.cloud_provider.CloudProvider` combiner indicates
the host is from the specific Cloud Provider.  Otherwise, it raises a
:py:class:`insights.core.dr.SkipComponent` to prevent dependent components from
executing.

"""
from insights.core.dr import SkipComponent
from insights.core.plugins import component
from insights.combiners.cloud_provider import CloudProvider

@component(CloudProvider)
class IsAWS(object):
    """
    This component uses ``CloudProvider`` combiner to determine the cloud
    provider of the instance.
    It checks if AWS, if not AWS it raises ``SkipComponent``.

    Raises:
        SkipComponent: When it's not an instance from AWS.
    """
    def __init__(self, cp):
        if not cp or cp.cloud_provider != CloudProvider.AWS:
            raise SkipComponent("Not AWS instance")

@component(CloudProvider)
class IsAzure(object):
    """
    This component uses ``CloudProvider`` combiner to determine the cloud
    provider of the instance.
    It checks if Azure, if not Azure it raises ``SkipComponent``.

    Raises:
        SkipComponent: When it's not an instance from Azure.
    """
    def __init__(self, cp):
        if not cp or cp.cloud_provider != CloudProvider.AZURE:
            raise SkipComponent("Not Azure instance")

@component(CloudProvider)
class IsGCP(object):
    """
    This component uses ``CloudProvider`` combiner to determine the cloud
    provider of the instance.
    It checks if Google Cloud Platform (GCP), if not GCP it raises ``SkipComponent``.

    Raises:
        SkipComponent: When it's not an instance from GCP.
    """
    def __init__(self, cp):
        if not cp or cp.cloud_provider != CloudProvider.GOOGLE:
            raise SkipComponent("Not Google Cloud Platform instance")


text:
package org.apache.pulsar.io.influxdb.v1;

import org.influxdb.InfluxDB;

public interface InfluxDBBuilder {
    InfluxDB build(InfluxDBSinkConfig config);
}


text:
layout: flat
title: About STIX
toc: about_toc.html
---

[Structured Threat Information Expression (STIX™)](http://stixproject.github.io/releases/1.2/) is a structured language for describing cyber threat information so it can be shared, stored, and analyzed in a consistent manner.

The [STIX whitepaper](/getting-started/whitepaper) describes the motivation and architecture behind STIX. At a high level the STIX language consists of 9 key constructs and the relationships between them:

- [Observables](http://cyboxproject.github.io) describe what has been or might be seen in cyber
- [Indicators](/data-model/{{site.current_version}}/indicator/IndicatorType) describe patterns for what might be seen and what they mean if they are
- [Incidents](/data-model/{{site.current_version}}/incident/IncidentType) describe instances of specific adversary actions
- [Adversary Tactics, Techniques, and Procedures](/data-model/{{site.current_version}}/ttp/TTPType) describe attack patterns, malware, exploits, kill chains, tools, infrastructure, victim targeting, and other methods used by the adversary
- [Exploit Targets](/data-model/{{site.current_version}}/et/ExploitTargetType) describe vulnerabilities, weaknesses, or configurations that might be exploited
- [Courses of Action](/data-model/{{site.current_version}}/coa/CourseOfActionType) describe response actions that may be taken in response to an attack or as a preventative measure
- [Campaigns](/data-model/{{site.current_version}}/campaign/CampaignType) describe sets of incidents and/or TTPs with a shared intent
- [Threat Actors](/data-model/{{site.current_version}}/ta/ThreatActorType) describe identification and/or characterization of the adversary
- [Reports](/data-model/{{site.current_version}}/report/ReportType) collect related STIX content and give them shared context

### The STIX Community

The [OASIS Cyber Threat Intelligence (CTI) Technical Committee (TC)](https://www.oasis-open.org/committees/cti) leads the ongoing development STIX. See the [Community](/community) page for more information. A few shortcuts:

- [OASIS Technical Committee](https://www.oasis-open.org/committees/cti) - where STIX development happens
- [Mailing Lists](/community/#discussion-list-amp-archives) - stay up to date on development and usage
- [Code Repositories](https://github.com/STIXProject/) - the central location for development of the schemas, specifications, tools, and documentation (including this site)

## Frequently Asked Questions

#### Who is STIX for? What does STIX do for me?

STIX is for anyone involved in defending networks or systems against cyber threats, including cyber defenders, cyber threat analysts, malware analysts, security tool vendors, security researchers, threat sharing communities, and more. STIX provides a common language for describing cyber threat information so it can be shared, stored, and otherwise used in a consistent manner that facilitates automation.

#### How do I get it?

The current release is [STIX Version 2.0](https://oasis-open.github.io/cti-documentation/), which is available on the [STIX 2.0 website](https://oasis-open.github.io/cti-documentation/).

An archive of [previous releases](/releases/archive/) is hosted on this website.

Bindings and related tools to help process and work with STIX are [open source on Github](https://github.com/STIXProject).

#### Where can I find examples of STIX data? Are there any STIX repositories?

The [Samples](/examples) page on this website hosts full threat reports expressed via STIX, including Mandiant's APT1 report and FireEye's Poison Ivy report. [Idioms](/documentation/idioms) also provide good constrained examples.

In addition to the MITRE samples, community members have set up [TAXII](http://taxiiproject.github.io/) repositories containing STIX content and even directories pointing to those repositories. One example repository is [http://hailataxii.com](http://hailataxii.com).

#### How do I use STIX? What tools/utilities are available for this effort?

The primary way to use STIX is of course via commercial products. See ["Who is using STIX?"](#who-is-using-stix) for more information.

If you're developing a product or tool, the current STIX reference implementation is in XML so any XML libraries are suitable for producing and consuming STIX XML. The project also maintains open-source [Python bindings](https://github.com/STIXProject/python-stix) and other [Utilities](https://gibhub.com/STIXProject) to make working with STIX at the code level easier. [Documentation](/documentation) and [Suggested Practices](/documentation/suggested-practices), as well as [Examples](/documentation/idioms), can help you understand how to use the STIX Language conceptually (beyond just producing the XML).

#### Who is using STIX?
The OASIS Cyber Threat Intelligence (CTI) Technical Committee (TC) hosts "STIX/CybOX/TAXII Supporters" lists for both [products](https://wiki.oasis-open.org/cti/Products) and [open source projects](https://wiki.oasis-open.org/cti/Open%20Source%20Projects). You can add your product/project via their [registration form](https://www.surveymonkey.com/r/oasis-cti-tc-supporter-registration).

In additon, the [STIX Blog](http://stixproject.tumblr.com) also notes vendor press releases and announcements.

#### How is STIX licensed?
See the [Terms of Use](/legal).

## Relationship to Other Efforts

#### TAXII

[TAXII](http://taxiiproject.github.io/) (Trusted Automated eXchange of Indicator Information) is the main transport mechanism for cyber threat information represented in STIX. Through the use of TAXII services, organizations can share cyber threat information in a secure and automated manner.

The STIX and TAXII communities work closely together (and in fact consist of many of the same people) to ensure that they continue to provide a full stack for sharing threat intelligence.

#### CybOX

[CybOX](https://cyboxproject.github.io/) (Cyber Observable eXpression) is a language for describing events of stateful properties ("things") that are observable in the cyber domain. STIX leverages CybOX for this purpose, such as in indicator patterns, infrastructure descriptions, and course of action parameters.

The STIX and CybOX communities work closely together (and in fact consist of many of the same people) to ensure that CybOX is valuable independently, as well as supports the use cases required by STIX.

#### MAEC

[MAEC](https://maecproject.github.io/) (Malware Attribute Enumeration and Classification) is a language for describing malware behavior and the results of a malware analysis. STIX leverages MAEC via the TTP construct for this purpose, and additionally both STIX and MAEC use CybOX.

While MAEC is led by DHS, the STIX, CybOX, and MAEC communities work closely together (and in fact consist of many of the same people) to ensure that the combination of the three specifications can interoperate and support both individual and combined usages. The STIX and MAEC teams have together produced a whitepaper describing how to [characterize malware across MAEC and STIX](/about/Characterizing_Malware_MAEC_and_STIX_v1.0.pdf).

#### CAPEC
STIX can utilize [Common Attack Pattern Enumeration and Classification](https://capec.mitre.org/) (CAPEC™) for structured characterization of tactics, techniques, and procedures (TTP) attack patterns through use of the CAPEC schema extension.

#### IODEF
The [Incident Object Description Format](https://tools.ietf.org/html/rfc5070) (IODEF) is an Internet Engineering Task Force (IETF) standard developed for exchange of incident information. There is no formal relationship between STIX and IODEF, although it is possible to leverage IODEF within STIX in order to represent incident information. Doing so, however, would lose the richness and architectural alignment provided by the STIX Incident structure.

#### OpenIOC
The STIX Indicator's test mechanism field is an extensible alternative to providing an indicator signature in something other than CybOX. [Open Indicators of Compromise](http://www.openioc.org/), [Open Vulnerability and Assessment Language](https://oval.cisecurity.org/) (OVAL®), SNORT rules, and YARA rules are supported as default extensions to that test mechanism field.

#### CIQ
The [OASIS Customer Information Quality](https://www.oasis-open.org/committees/ciq/) (CIQ) is a language for representing information about individuals and organizations. The STIX Identity structure uses an extension mechanism to represent identify information used to characterize malicious actors, victims and intelligence sources. The STIX-provided extension leverages CIQ.

#### VERIS
The [Vocabulary for Event Recording and Incident Sharing](http://veriscommunity.net/) (VERIS) is a metrics framework designed to provide a common language for describing security incidents and their effects in a structured manner. The difference between STIX incidents and VERIS is in purpose and use: VERIS is an after-the-fact characterization of cyber incidents intended for post-incident strategic trend analysis and risk management. STIX provides the capability to capture information about security incidents and their effects but does so in the context of a broader threat intelligence framework. Verizon and members of the VERIS team are active members of the STIX community and have contributed their thoughts and access to the VERIS structures to help improve and refine the content of the STIX Incident schema. A good portion of the STIX Incident schema was derived from this VERIS input.


text:
/*
 * Created on Sep 1, 2004
 *
 */
package com.myconnector.web;

import org.apache.log4j.Logger;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

/**
 *
 * @author nil
 */
public class DefaultValidator implements Validator {

    static Logger logger = Logger.getLogger(DefaultValidator.class);

    /* (non-Javadoc)
     * @see org.springframework.validation.Validator#supports(java.lang.Class)
     */
    public boolean supports(Class arg0) {
        return(true);
    }

    /* (non-Javadoc)
     * @see org.springframework.validation.Validator#validate(java.lang.Object, org.springframework.validation.Errors)
     */
    public void validate(Object arg0, Errors arg1) {
    }

}


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

<TITLE>
Locatable
</TITLE>

<META NAME="date" CONTENT="2011-06-20">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.openqa.selenium.internal

Interface Locatable

All Known Implementing Classes:
FirefoxWebElement, HtmlUnitWebElement, InternetExplorerElement, RemoteWebElement

public interface Locatable

Method Summary

 Coordinates
getCoordinates()

 Point
getLocationOnScreenOnceScrolledIntoView()

          Use this to discover where on the screen an element is so that we can click it.

Method Detail

getLocationOnScreenOnceScrolledIntoView

Point getLocationOnScreenOnceScrolledIntoView()

Use this to discover where on the screen an element is so that we can click it. This method
 should cause the element to be scrolled into view.

Returns:
The top lefthand corner location on the screen, or null if the element is not visible

getCoordinates

Coordinates getCoordinates()

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
package org.ensembl.healthcheck.testcase.funcgen;

import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.Team;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Check that every read_file is linked to an alignment. Check that the
 * alignment exists.
 *
 * @author ilavidas
 */

public class ReadFileHasBeenAligned extends SingleDatabaseTestCase {

    private static final int MAX_ERRORS_REPORTED = 20;

    public ReadFileHasBeenAligned() {
        setTeamResponsible(Team.FUNCGEN);
        setDescription("Check that every read_file is linked to an alignment." +
                " Check that the alignment exists.");
    }

    @Override
    public boolean run(DatabaseRegistryEntry dbre) {

        boolean result = true;
        Connection con = dbre.getConnection();
//        int noLinkErrorCount = 0;
//        int noResultSetErrorCount = 0;

        try {
            //fetch all read_files
            Statement stmt = con.createStatement();
            ResultSet readFiles = stmt.executeQuery("SELECT " +
                    "read_file_id,name FROM read_file");

            while (readFiles != null && readFiles.next()) {
                int rfID = readFiles.getInt(1);
                String rfName = readFiles.getString(2);

                //fetch alignments for every read_file
                Statement newStmt = con.createStatement();
                ResultSet alignmentLinks = newStmt.executeQuery("SELECT " +
                        "alignment_id FROM alignment_read_file WHERE " +
                        "read_file_id=" + rfID);

                // Check that the read_file has link(s) to alignments
                if (!alignmentLinks.next()) {
                    /*
                    ReportManager.problem(this, con, "Read_file " + rfName +
                            " with read_file_id " + rfID + " is not linked to" +
                            " any alignment");
//                    noLinkErrorCount++;
                    result = false;
                    */
                    ReportManager.warning(this, con, "Read_file " + rfName +
                            " with read_file_id " + rfID + " is not linked to" +
                            " any alignment");
//                    noLinkErrorCount++;
                    result = true;

                } else {
                    alignmentLinks.first();
                    while (alignmentLinks.next()) {
                        int alignmentID = alignmentLinks.getInt(1);
                        Statement statement = con.createStatement();
                        ResultSet alignments = statement.executeQuery("SELECT" +
                                " * FROM alignment WHERE alignment_id=" +
                                alignmentID);

                        if (!alignments.next()) {
                            ReportManager.problem(this, con, "Read_file " +
                                    rfName + " with read_file_id " + rfID + "" +
                                    " appears to be linked to alignment_id "
                                    + alignmentID + " but such id does NOT " +
                                    "exist in the alignment table.");
                            result = false;
                        }
                    }
                }

                // If the number of errors is too high do not report all of
                // them, as this is usually slow. Print a helpful sql query
                // instead for manual inspection by the user
//                if (noLinkErrorCount > MAX_ERRORS_REPORTED) {
//
//                    String helpfulQuery = "SELECT input_subset" + "" +
//                            ".input_subset_id, input_subset.name FROM " +
//                            "input_subset LEFT JOIN result_set_input ON " +
//                            "(input_subset_id=table_id AND " +
//                            "table_name='input_subset') WHERE result_set_id " +
//                            "IS NULL";
//
//                    ReportManager.info(this, con, "Too many errors found. The" +
//                            " above list is NOT exhaustive! Execute this " +
//                            "query to retrieve all input_subsets that are not" +
//                            " linked to a result_set:\n" + helpfulQuery);
//
//                    break;
//                }

                // Check that the result_set links found in the
                // result_set_input table exist in the result_set table
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return result;
    }
}


text:
package com.microsoft.azure.management.network.v2018_06_01.implementation;

import com.microsoft.azure.management.network.v2018_06_01.VirtualNetworkGatewayConnectionListEntity;
import com.microsoft.azure.arm.model.implementation.WrapperImpl;
import rx.Observable;
import com.microsoft.azure.management.network.v2018_06_01.VirtualNetworkGatewayConnectionStatus;
import com.microsoft.azure.management.network.v2018_06_01.VirtualNetworkGatewayConnectionType;
import java.util.List;
import com.microsoft.azure.management.network.v2018_06_01.IpsecPolicy;
import com.microsoft.azure.management.network.v2018_06_01.VirtualNetworkConnectionGatewayReference;
import com.microsoft.azure.SubResource;
import java.util.Map;
import com.microsoft.azure.management.network.v2018_06_01.TunnelConnectionHealth;

class VirtualNetworkGatewayConnectionListEntityImpl extends WrapperImpl<VirtualNetworkGatewayConnectionListEntityInner> implements VirtualNetworkGatewayConnectionListEntity {
    private final NetworkManager manager;

    VirtualNetworkGatewayConnectionListEntityImpl(VirtualNetworkGatewayConnectionListEntityInner inner,  NetworkManager manager) {
        super(inner);
        this.manager = manager;
    }

    @Override
    public NetworkManager manager() {
        return this.manager;
    }

    @Override
    public String authorizationKey() {
        return this.inner().authorizationKey();
    }

    @Override
    public VirtualNetworkGatewayConnectionStatus connectionStatus() {
        return this.inner().connectionStatus();
    }

    @Override
    public VirtualNetworkGatewayConnectionType connectionType() {
        return this.inner().connectionType();
    }

    @Override
    public Long egressBytesTransferred() {
        return this.inner().egressBytesTransferred();
    }

    @Override
    public Boolean enableBgp() {
        return this.inner().enableBgp();
    }

    @Override
    public String etag() {
        return this.inner().etag();
    }

    @Override
    public String id() {
        return this.inner().id();
    }

    @Override
    public Long ingressBytesTransferred() {
        return this.inner().ingressBytesTransferred();
    }

    @Override
    public List<IpsecPolicy> ipsecPolicies() {
        return this.inner().ipsecPolicies();
    }

    @Override
    public VirtualNetworkConnectionGatewayReference localNetworkGateway2() {
        return this.inner().localNetworkGateway2();
    }

    @Override
    public String location() {
        return this.inner().location();
    }

    @Override
    public String name() {
        return this.inner().name();
    }

    @Override
    public SubResource peer() {
        return this.inner().peer();
    }

    @Override
    public String provisioningState() {
        return this.inner().provisioningState();
    }

    @Override
    public String resourceGuid() {
        return this.inner().resourceGuid();
    }

    @Override
    public Integer routingWeight() {
        return this.inner().routingWeight();
    }

    @Override
    public String sharedKey() {
        return this.inner().sharedKey();
    }

    @Override
    public Map<String, String> tags() {
        return this.inner().getTags();
    }

    @Override
    public List<TunnelConnectionHealth> tunnelConnectionStatus() {
        return this.inner().tunnelConnectionStatus();
    }

    @Override
    public String type() {
        return this.inner().type();
    }

    @Override
    public Boolean usePolicyBasedTrafficSelectors() {
        return this.inner().usePolicyBasedTrafficSelectors();
    }

    @Override
    public VirtualNetworkConnectionGatewayReference virtualNetworkGateway1() {
        return this.inner().virtualNetworkGateway1();
    }

    @Override
    public VirtualNetworkConnectionGatewayReference virtualNetworkGateway2() {
        return this.inner().virtualNetworkGateway2();
    }

}


text:
/*
 * File:   global.h
 *
 */

#ifndef GLOBAL_H
#define	GLOBAL_H

extern "C"{
    #include "khe.h"
}

#include <boost/range/iterator_range_core.hpp>
#include "KheObjIter.h"

/**
 * see global.cpp for definition
 * Set this to "false" if you want to construct solutions; for reading purposes,
 * allowing caching speeds up things very much.
 */
extern bool allowCaching;

extern const bool useBackPointerForNumIds;

#include "Util.h"
#include "ObjNotFound.h"
#include "Ident.h"

#include <string>
#include <vector>

#endif	/* GLOBAL_H */


text:
Run the sql to sqlite3

## Description

* supports named parameters

## Requirement

* libsqlite3.dylib

## Usage

### initialize

**important**

```objc
sqlite3 *sqlax;
NSString *filePath = @"your/sqlite/file/path";
sqlite3_open([filePath UTF8String], &sqlax);

YJMSQLiteQueryExecuter *exec = [[YJMSQLiteQueryExecuter alloc]init];
exec.database = sqlax;
```

### run query

```objc
NSString *createSql = @"CREATE TABLE IF NOT EXISTS names (name TEXT)";
[exec query:createSql];
```

### run query with named parameter

```objc
NSString *insertSql = @"INSERT INTO names(name) VALUES(:name)";
NSString *name = [NSString stringWithFormat:@"%@%d",@"name_",arc4random() % 99];

NSMutableArray *params = [@[] mutableCopy];
[params addObject:[YJMSQLiteNamedParameter namedParameterWithValue:name target:@":name" type:YJMSQLiteDataTypeText]];

[exec query:insertSql withNamedParams:[params copy ]];
```

### get results of select query

```objc
NSString *selectSql = @"SELECT * FROM names";
NSArray  *records = [exec query:selectSql];

[records enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    NSDictionary *record = obj;
    NSLog(@"%@",record[@"name"]);
}];
```

## Install

* Manual
    * Copy `YJMSQLiteNamedParameter.h/m` to your project.
    * Copy `YJMSQLiteQueryExecuter.h/m` to your project.

## Contribution

## License

[MIT](https://github.com/yajamon/YJMSQLiteQueryExecuter/blob/master/LICENSE)

## Author

[yajamon](https://github.com/yajamon)


text:
title: 'Tomato & Black Bean Quesadillas'
author: lbjay
layout: post
permalink: /2007/09/05/tomato-black-bean-quesadillas/
categories:
  - "What's for Lunch"
---

 Tomato & Black Bean Quesadillas

 Originally uploaded by jayluker

Leftovers from dinner last night. These quesadillas feature refried black beans, tomatoes from the garden and grated jack cheese. They were “grilled” in a fantastic cast iron pan I picked up at the [Todd Farm][1] flea market several years ago.

 [1]: http://www.toddfarm.com/


text:
#pragma once
#include <aws/opensearch/OpenSearchService_EXPORTS.h>
#include <aws/opensearch/OpenSearchServiceRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace OpenSearchService
{
namespace Model
{

  /**
   *
 Container for the request parameters to the  GetUpgradeStatus
   *  operation.

See Also:
   AWS
   * API Reference

   */
  class AWS_OPENSEARCHSERVICE_API GetUpgradeStatusRequest : public OpenSearchServiceRequest
  {
  public:
    GetUpgradeStatusRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "GetUpgradeStatus"; }

    Aws::String SerializePayload() const override;

    inline const Aws::String& GetDomainName() const{ return m_domainName; }

    inline bool DomainNameHasBeenSet() const { return m_domainNameHasBeenSet; }

    inline void SetDomainName(const Aws::String& value) { m_domainNameHasBeenSet = true; m_domainName = value; }

    inline void SetDomainName(Aws::String&& value) { m_domainNameHasBeenSet = true; m_domainName = std::move(value); }

    inline void SetDomainName(const char* value) { m_domainNameHasBeenSet = true; m_domainName.assign(value); }

    inline GetUpgradeStatusRequest& WithDomainName(const Aws::String& value) { SetDomainName(value); return *this;}

    inline GetUpgradeStatusRequest& WithDomainName(Aws::String&& value) { SetDomainName(std::move(value)); return *this;}

    inline GetUpgradeStatusRequest& WithDomainName(const char* value) { SetDomainName(value); return *this;}

  private:

    Aws::String m_domainName;
    bool m_domainNameHasBeenSet;
  };

} // namespace Model
} // namespace OpenSearchService
} // namespace Aws


text:
class Model {
public:
    Model(const glm::vec3 origin, const std::string& path) :
            Model{origin, std::vector<std::shared_ptr<Mesh>>{}} {
        loadModel(path, nullptr);
    }

    Model(const glm::vec3 origin, const std::string& path, const std::shared_ptr<Material>& material) :
            Model{origin, std::vector<std::shared_ptr<Mesh>>{}} {
        loadModel(path, material);
    }

    Model(const glm::vec3 origin, std::vector<std::shared_ptr<Mesh>>  meshes) :
            origin{origin},
            meshes{std::move(meshes)} {
    }

    //TODO translation with origin
    std::vector<std::shared_ptr<Primitive>> getPrimitives() {
        auto primitives = std::vector<std::shared_ptr<Primitive>>{};

        for (auto const &mesh : meshes) {
            auto meshPrimitives = mesh->getPrimitives();
            primitives.insert(primitives.end(),
                              std::make_move_iterator(meshPrimitives.begin()),
                              std::make_move_iterator(meshPrimitives.end()));
        }

        return primitives;
    }

private:
    glm::vec3 origin;
    std::vector<std::shared_ptr<Mesh>> meshes;

    void loadModel(const std::string& path, const std::shared_ptr<Material>& material) {
        Assimp::Importer import;
        const aiScene *scene = import.ReadFile(path, aiProcess_Triangulate |
                                                     aiProcess_JoinIdenticalVertices |
                                                     aiProcess_OptimizeMeshes |
                                                     aiProcess_OptimizeGraph);

        if (!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) {
            std::cout << "ERROR::ASSIMP::" << import.GetErrorString() << "\n";
            return;
        }

        processAiNode(scene->mRootNode, scene, material);
    }

    void processAiNode(aiNode *node, const aiScene *scene, const std::shared_ptr<Material>& material) {
        for (unsigned int i = 0; i < node->mNumMeshes; ++i) {
            aiMesh *mesh = scene->mMeshes[node->mMeshes[i]];
            meshes.push_back(this->processAiMesh(mesh, scene, material));
        }

        for (unsigned int i = 0; i < node->mNumChildren; ++i) {
            processAiNode(node->mChildren[i], scene, material);
        }
    }

    static std::shared_ptr<Mesh> processAiMesh(aiMesh *mesh, const aiScene *scene, const std::shared_ptr<Material>& material) {
        std::vector<std::shared_ptr<Primitive>> primitives;
        for (unsigned int i = 0; i < mesh->mNumFaces; ++i) {
            std::array<glm::vec3, 3> vertices{};
            auto face = mesh->mFaces[i];
            for (unsigned int j = 0; j < face.mNumIndices; ++j) {
                auto aiVertex = mesh->mVertices[face.mIndices[j]];
                auto vertex = glm::vec3(aiVertex.x, aiVertex.y, aiVertex.z);
                vertices[j] = vertex;
            }
            if (material) {
                primitives.push_back(std::make_shared<Triangle>(vertices, material));
            } else {
                primitives.push_back(std::make_shared<Triangle>(vertices));
            }
        }

        return std::make_shared<Mesh>(Mesh{primitives});
    }
};

#endif //RAYTRACER_MODEL_H


text:
require 'spec_helper'

describe RBattlenet::Wow::Character::CompletedQuests, type: :game_data do

  describe "#find_character_completed_quests" do
    it "fetches character data" do
      with_connection("wow_character_completed_quests") do
        result = RBattlenet::Wow::Character::CompletedQuests.find(realm: "stormrage", name: "sheday")
        expect(result.quests.class).to eq Array
      end
    end
  end

  describe "#find_multiple_character_completed_questss" do
    it "fetches character data" do
      with_connection("wow_character_completed_quests_multiple") do
        collection = RBattlenet::Wow::Character::CompletedQuests.find([
          { realm: "stormrage", name: "sheday" },
          { realm: "howling-fjord", name: "альвеоняша" },
        ])
        expect(collection.results.map(&:quests).map(&:class)).to eq [Array, Array]
      end
    end
  end
end