text:
require 'spec_helper_min'
require 'helpers/storage_helper'
require 'helpers/subdomainless_helper'

describe Carto::Asset do
  # Needed so subdomainless_helper works
  def host!(_) end

  before(:all) do
    @organization = Carto::Organization.find(FactoryGirl.create(:organization).id)
    @user = FactoryGirl.create(:carto_user)
  end

  after(:all) do
    @organization.destroy
    @user.destroy
  end

  let(:storage_info) do
    {
      type: 's3',
      location: 'manolo_subfolder',
      identifier: 'could_be_a_manolo_hash_23as4g5sh6sd7hd8j9jfgk'
    }
  end

  let(:public_url) do
    'https://manolo.es/es/co/bar'
  end

  describe('#.for_organization') do
    include StorageHelper

    it 'should create a valid asset for organization and resource' do
      bypass_storage
      asset = Carto::Asset.for_organization(organization: @organization,
                                            resource: Tempfile.new(['manolo', '.jpg']))

      asset.valid?.should be_true
    end
  end

  describe('#destroy') do
    it 'doesn\'t try to remove from storage if no storage_info is present' do
      Carto::AssetsService.any_instance.expects(:remove).never
      Carto::Asset.create(user: @user).destroy
    end

    it 'removes asset from storage if storage_info is present' do
      Carto::AssetsService.any_instance.expects(:remove).once
      Carto::Asset.create(user: @user, storage_info: storage_info).destroy
    end
  end

  describe('#absolute_public_url') do
    let(:asset) { Carto::Asset.new(organization: @organization, public_url: '/uploads/wadus') }

    it 'preprends subdomain name in subdomainful' do
      stub_domainful(@organization.name)
      domain = "http://#{@organization.name}.localhost.lan#{CartoDB.http_port}"
      asset.absolute_public_url.should eq domain + asset.public_url
    end

    it 'preprends domain name in subdomainless' do
      stub_subdomainless
      domain = "http://localhost.lan#{CartoDB.http_port}"
      asset.absolute_public_url.should eq domain + asset.public_url
    end
  end

  describe('#validation') do
    it 'requires a user or an organization' do
      asset = Carto::Asset.new
      asset.valid?.should be_false
      asset.errors[:user].should_not be_empty
      asset.errors[:organization].should_not be_empty
    end

    it 'requires a public url' do
      asset = Carto::Asset.new(organization: @organization,
                               storage_info: storage_info)
      asset.valid?.should be_false
      asset.errors[:public_url].should_not be_empty
    end

    describe('#user asset') do
      it 'accepts good asset' do
        asset = Carto::Asset.new(user: @user, public_url: public_url)
        asset.valid?.should be_true
      end

      it 'accepts nil storage_info' do
        asset = Carto::Asset.new(user: @user, public_url: public_url)
        asset.valid?.should be_true
      end

      it 'rejects incomplete storage_info' do
        storage_info.delete(:type)
        asset = Carto::Asset.new(user: @user,
                                 storage_info: storage_info,
                                 public_url: public_url)
        asset.valid?.should be_false
        asset.errors[:storage_info].should_not be_empty
      end

      it 'rejects spammy storage_info' do
        storage_info[:great_idea] = 'to spam a json!'
        asset = Carto::Asset.new(user: @user,
                                 storage_info: storage_info,
                                 public_url: public_url)
        asset.valid?.should be_false
        asset.errors[:storage_info].should_not be_empty
      end
    end

    describe('#organization asset') do
      it 'accepts good asset' do
        asset = Carto::Asset.new(organization: @organization,
                                 storage_info: storage_info,
                                 public_url: public_url)
        asset.valid?.should be_true
      end

      it 'rejects nil storage_info' do
        asset = Carto::Asset.new(organization: @organization,
                                 public_url: public_url)
        asset.valid?.should be_false
        asset.errors[:storage_info].should_not be_empty
        asset.errors[:storage_info].should eq ["can't be blank"]
      end

      it 'rejects incomplete storage_info' do
        storage_info.delete(:type)
        asset = Carto::Asset.new(organization: @organization,
                                 storage_info: storage_info,
                                 public_url: public_url)
        asset.valid?.should be_false
        asset.errors[:storage_info].should_not be_empty
      end

      it 'rejects spammy storage_info' do
        storage_info[:great_idea] = 'to spam a json!'
        asset = Carto::Asset.new(organization: @organization,
                                 storage_info: storage_info,
                                 public_url: public_url)
        asset.valid?.should be_false
        asset.errors[:storage_info].should_not be_empty
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
layout: post
title:  "Skyway Drone Delivery"
description: A web application we built to order a can of coke delivered to the ski hill
categories: projects
img: skyway.png
color: 054ec4
---

Skyway is a drone delivery app.
GitHub

Technologies used:
* Dronekit-python
* Google Maps API
* Django
* Ajax
* Javascript
* HTML
* CSS
* Zurb Foundations
* iPhone
* A bunch of charm


text:
class SigninUtilTest : public BrowserWithTestWindowTest {
 public:
  void SetUp() override {
    BrowserWithTestWindowTest::SetUp();
    signin_util::ResetForceSigninForTesting();
  }

  void TearDown() override {
    signin_util::ResetForceSigninForTesting();
    BrowserWithTestWindowTest::TearDown();
  }
};

TEST_F(SigninUtilTest, GetForceSigninPolicy) {
  EXPECT_FALSE(signin_util::IsForceSigninEnabled());

  g_browser_process->local_state()->SetBoolean(prefs::kForceBrowserSignin,
                                               true);
  signin_util::ResetForceSigninForTesting();
  EXPECT_TRUE(signin_util::IsForceSigninEnabled());
  g_browser_process->local_state()->SetBoolean(prefs::kForceBrowserSignin,
                                               false);
  signin_util::ResetForceSigninForTesting();
  EXPECT_FALSE(signin_util::IsForceSigninEnabled());
}

#if !BUILDFLAG(IS_CHROMEOS_LACROS)
class SigninUtilEnterpriseTest : public BrowserWithTestWindowTest {
 public:
  SigninUtilEnterpriseTest()
      : feature_list_(kAccountPoliciesLoadedWithoutSync) {}

 private:
  base::test::ScopedFeatureList feature_list_;
};

TEST_F(SigninUtilEnterpriseTest, ProfileSeparationEnforcedByPolicy) {
  std::unique_ptr<TestingProfile> profile = TestingProfile::Builder().Build();

  // No policy set on the active profile.
  EXPECT_FALSE(signin_util::ProfileSeparationEnforcedByPolicy(profile.get(),
                                                              std::string()));
  EXPECT_FALSE(
      signin_util::ProfileSeparationEnforcedByPolicy(profile.get(), "none"));
  EXPECT_TRUE(signin_util::ProfileSeparationEnforcedByPolicy(
      profile.get(), "primary_account"));
  EXPECT_TRUE(signin_util::ProfileSeparationEnforcedByPolicy(
      profile.get(), "primary_account_strict"));

  // Active profile has "primary_account" as a user level policy.
  profile->GetPrefs()->SetString(prefs::kManagedAccountsSigninRestriction,
                                 "primary_account");
  profile->GetPrefs()->SetBoolean(
      prefs::kManagedAccountsSigninRestrictionScopeMachine, false);
  EXPECT_FALSE(signin_util::ProfileSeparationEnforcedByPolicy(profile.get(),
                                                              std::string()));
  EXPECT_FALSE(
      signin_util::ProfileSeparationEnforcedByPolicy(profile.get(), "none"));
  EXPECT_TRUE(signin_util::ProfileSeparationEnforcedByPolicy(
      profile.get(), "primary_account"));
  EXPECT_TRUE(signin_util::ProfileSeparationEnforcedByPolicy(
      profile.get(), "primary_account_strict"));

  // Active profile has "primary_account_strict" as a user level policy.
  profile->GetPrefs()->SetString(prefs::kManagedAccountsSigninRestriction,
                                 "primary_account_strict");
  profile->GetPrefs()->SetBoolean(
      prefs::kManagedAccountsSigninRestrictionScopeMachine, false);
  EXPECT_TRUE(signin_util::ProfileSeparationEnforcedByPolicy(profile.get(),
                                                             std::string()));
  EXPECT_TRUE(
      signin_util::ProfileSeparationEnforcedByPolicy(profile.get(), "none"));
  EXPECT_TRUE(signin_util::ProfileSeparationEnforcedByPolicy(
      profile.get(), "primary_account"));
  EXPECT_TRUE(signin_util::ProfileSeparationEnforcedByPolicy(
      profile.get(), "primary_account_strict"));

  // Active profile has "primary_account" as a machine level policy.
  profile->GetPrefs()->SetString(prefs::kManagedAccountsSigninRestriction,
                                 "primary_account");
  profile->GetPrefs()->SetBoolean(
      prefs::kManagedAccountsSigninRestrictionScopeMachine, true);
  EXPECT_TRUE(signin_util::ProfileSeparationEnforcedByPolicy(profile.get(),
                                                             std::string()));
  EXPECT_TRUE(
      signin_util::ProfileSeparationEnforcedByPolicy(profile.get(), "none"));
  EXPECT_TRUE(signin_util::ProfileSeparationEnforcedByPolicy(
      profile.get(), "primary_account"));
  EXPECT_TRUE(signin_util::ProfileSeparationEnforcedByPolicy(
      profile.get(), "primary_account_strict"));

  // Active profile has "primary_account_strict" as a machine level policy.
  profile->GetPrefs()->SetString(prefs::kManagedAccountsSigninRestriction,
                                 "primary_account");
  profile->GetPrefs()->SetBoolean(
      prefs::kManagedAccountsSigninRestrictionScopeMachine, true);
  EXPECT_TRUE(signin_util::ProfileSeparationEnforcedByPolicy(profile.get(),
                                                             std::string()));
  EXPECT_TRUE(
      signin_util::ProfileSeparationEnforcedByPolicy(profile.get(), "none"));
  EXPECT_TRUE(signin_util::ProfileSeparationEnforcedByPolicy(
      profile.get(), "primary_account"));
  EXPECT_TRUE(signin_util::ProfileSeparationEnforcedByPolicy(
      profile.get(), "primary_account_strict"));
}
#endif


text:
package org.jetbrains.plugins.groovy.lang.completion;

import org.jetbrains.plugins.groovy.util.TestUtils;

/**
 * @author ilyas
 */
public class KeywordCompletionTest extends CompletionTestBase {

  public void testBr1() throws Throwable { doTest(); }
  public void testCase_return() throws Throwable { doTest(); }
  public void testClass1() throws Throwable { doTest(); }
  public void testClass2() throws Throwable { doTest(); }
  public void testClass3() throws Throwable { doTest(); }
  public void testClass4() throws Throwable { doTest(); }
  public void testExpr1() throws Throwable { doTest(); }
  public void testExpr2() throws Throwable { doTest(); }
  public void testFile11() throws Throwable { doTest(); }
  public void testFile12() throws Throwable { doTest(); }
  public void testFin() throws Throwable { doTest(); }
  public void testFin2() throws Throwable { doTest(); }
  public void testGRVY1064() throws Throwable { doTest(); }
  public void testGrvy1404() throws Throwable { doTest(); }
  public void testGrvy945() throws Throwable { doTest(); }
  public void testImp1() throws Throwable { doTest(); }
  public void testImp2() throws Throwable { doTest(); }
  public void testImp3() throws Throwable { doTest(); }
  public void testImp4() throws Throwable { doTest(); }
  public void testIns1() throws Throwable { doTest(); }
  public void testIns2() throws Throwable { doTest(); }
  public void testIns3() throws Throwable { doTest(); }
  public void testInt1() throws Throwable { doTest(); }
  public void testLocal1() throws Throwable { doTest(); }
  public void testMod1() throws Throwable { doTest(); }
  public void testMod10() throws Throwable { doTest(); }
  public void testMod11() throws Throwable { doTest(); }
  public void testMod2() throws Throwable { doTest(); }
  public void testMod3() throws Throwable { doTest(); }
  public void testMod4() throws Throwable { doTest(); }
  public void testMod5() throws Throwable { doTest(); }
  public void testMod6() throws Throwable { doTest(); }
  public void testMod7() throws Throwable { doTest(); }
  public void testMod8() throws Throwable { doTest(); }
  public void testMod9() throws Throwable { doTest(); }
  public void testPack1() throws Throwable { doTest(); }
  public void testSt1() throws Throwable { doTest(); }
  public void testSwit1() throws Throwable { doTest(); }
  public void testSwit13() throws Throwable { doTest(); }
  public void testSwit14() throws Throwable { doTest(); }
  public void testSwit2() throws Throwable { doTest(); }
  public void testSwit3() throws Throwable { doTest(); }
  public void testSwit4() throws Throwable { doTest(); }
  public void testSwit5() throws Throwable { doTest(); }
  public void testTag1() throws Throwable { doTest(); }
  public void testTag2() throws Throwable { doTest(); }
  public void testTag3() throws Throwable { doTest(); }
  public void testTag4() throws Throwable { doTest(); }
  public void testTh1() throws Throwable { doTest(); }
  public void testTh2() throws Throwable { doTest(); }
  public void testVar1() throws Throwable { doTest(); }
  public void testVar10() throws Throwable { doTest(); }
  public void testVar13() throws Throwable { doTest(); }
  public void testVar2() throws Throwable { doTest(); }
  public void testVar3() throws Throwable { doTest(); }
  public void testVar4() throws Throwable { doTest(); }
  public void testVar5() throws Throwable { doTest(); }
  public void testVar6() throws Throwable { doTest(); }
  public void testVar7() throws Throwable { doTest(); }
  public void testVar8() throws Throwable { doTest(); }
  public void testVar9() throws Throwable { doTest(); }
  public void testWhile55() throws Throwable { doTest(); }

  @Override
  protected String getBasePath() {
    return TestUtils.getTestDataPath() + "groovy/oldCompletion/keyword";
  }

  protected boolean addReferenceVariants() {
    return false;
  }

}


text:
using System;
using System.Drawing;

using MonoMac.Foundation;
using MonoMac.AppKit;
using MonoMac.CoreGraphics;
using MonoMac.OpenGL;

namespace NeHeLesson17
{
	public class Texture2D
	{
		int texId;
		byte[] data;
		int width, height;

		public Texture2D (string path)
		{
			GetImagaDataFromPath (path);
			LoadTexture ();
		}

		void GetImagaDataFromPath (string path)
		{
			NSImage src;
			CGImage image;
			CGContext context = null;

			src = new NSImage (path);

			image = src.AsCGImage (RectangleF.Empty, null, null);
			width = image.Width;
			height = image.Height;

			int bytesPerRow = image.BytesPerRow;
			int bitsPerPixel = image.BitsPerPixel;
			int bitsPerComponent = image.BitsPerComponent;

			data = new byte[bytesPerRow * height * 4];

			CGImageAlphaInfo ai = CGImageAlphaInfo.PremultipliedLast;
			CGColorSpace colorSpace = CGColorSpace.CreateDeviceRGB();

			context = new CGBitmapContext (data, width, height, 8, 4 * width, colorSpace, ai);

			// Core Graphics referential is upside-down compared to OpenGL referential
			// Flip the Core Graphics context here
			// An alternative is to use flipped OpenGL texture coordinates when drawing textures
			context.TranslateCTM (0, height);
			context.ScaleCTM (1, -1);

			// Set the blend mode to copy before drawing since the previous contents of memory aren't used.
			// This avoids unnecessary blending.
			context.SetBlendMode (CGBlendMode.Copy);

			context.DrawImage (new RectangleF (0, 0, width, height), image);
		}

		void LoadTexture ()
		{
			GL.GenTextures (1, out texId);

			// Bind the texture
			GL.BindTexture (TextureTarget.Texture2D, texId);

			// Setup texture parameters
			GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)All.Linear);
			GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)All.Linear);

			GL.PixelStore (PixelStoreParameter.UnpackRowLength, 0);

			GL.TexImage2D (TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, width, height, 0, PixelFormat.Rgba, PixelType.UnsignedByte, data);
			data = null;

			GL.BindTexture (TextureTarget.Texture2D, 0);
		}

		public int TextureName {
			get { return texId; }
		}
	}
}


text:
 module.exports = function(RED) {
    "use strict";

    function inputSplitNode(n) {
        var node = this;

        RED.nodes.createNode(this,n);
        this.inputProps = n.inputProps.map(function (a) {
            return a.split(".");
        });

        var l = this.inputProps.length;

        this.on('input',function (msg) {
            var outputs = [];
            for (var i=0;i<l;i++) {
                //Find the property
                var prop = node.inputProps[i].reduce(function (obj, i) {
                    return (typeof obj === 'object')
                            ? obj[i]
                            : obj;
                }, msg);

                if (prop !== undefined) {
                    var output = RED.util.cloneMessage(msg);
                    output.payload = prop;
                    outputs.push(output);
                } else {
                    outputs.push(null);
                }
            }
            node.send(outputs);
        });

    }

    RED.nodes.registerType("Input Split",inputSplitNode);
};


text:
#pragma once

#include "il2cpp-config.h"

#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif

#include <stdint.h>

// System.Runtime.Remoting.Messaging.IMessageSink
struct IMessageSink_t2257382795;

#include "mscorlib_System_Object4170816371.h"

#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif

// System.Runtime.Remoting.Messaging.ServerObjectTerminatorSink
struct  ServerObjectTerminatorSink_t1617394198  : public Il2CppObject
{
public:
	// System.Runtime.Remoting.Messaging.IMessageSink System.Runtime.Remoting.Messaging.ServerObjectTerminatorSink::_nextSink
	Il2CppObject * ____nextSink_0;

public:
	inline static int32_t get_offset_of__nextSink_0() { return static_cast<int32_t>(offsetof(ServerObjectTerminatorSink_t1617394198, ____nextSink_0)); }
	inline Il2CppObject * get__nextSink_0() const { return ____nextSink_0; }
	inline Il2CppObject ** get_address_of__nextSink_0() { return &____nextSink_0; }
	inline void set__nextSink_0(Il2CppObject * value)
	{
		____nextSink_0 = value;
		Il2CppCodeGenWriteBarrier(&____nextSink_0, value);
	}
};

#ifdef __clang__
#pragma clang diagnostic pop
#endif


text:
<?php

namespace Stp\SndApi\Common\Exception;

class UnsatisfactoryResponseCodeException extends \Exception
{

}


text:
package gov.nih.nci.cabig.caaers.service.synchronizer;

import gov.nih.nci.cabig.caaers.domain.AbstractMutableRetireableDomainObject;
import gov.nih.nci.cabig.caaers.domain.OtherIntervention;
import gov.nih.nci.cabig.caaers.domain.Study;
import gov.nih.nci.cabig.caaers.service.DomainObjectImportOutcome;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author Ion C. Olaru
 *         Date: 5/3/12 -4:48 PM
 */
public class StudyInterventionSynchronizer implements Synchronizer<Study> {

    private List<String> context = new ArrayList<String>();
    @Override
    public List<String> contexts() {
        return context;
    }
    public void migrate(Study dest, Study src, DomainObjectImportOutcome<Study> studyDomainObjectImportOutcome) {
    	HashMap<String, OtherIntervention> map = new HashMap<String, OtherIntervention>();
		for(OtherIntervention otherIntervention : dest.getActiveOtherInterventions()) {
			map.put(otherIntervention.getHashKey(), otherIntervention);
		}

		for(OtherIntervention xmlOtherIntervention : src.getOtherInterventions()){
			OtherIntervention otherIntervention = map.remove(xmlOtherIntervention.getHashKey());
			if(otherIntervention == null){
				//newly added one, so add it to study
				dest.addOtherIntervention(xmlOtherIntervention);
				continue;
			}
			//Update- do nothing

		}

		//now soft delete, all the ones not present in XML Study
		AbstractMutableRetireableDomainObject.retire(map.values());

//        List<OtherIntervention> otherInterventions = src.getOtherInterventions();
//        if (CollectionUtils.isEmpty(otherInterventions)) return;
//        Set<String> destInterventionsSet = new HashSet<String>();
//
//        for (OtherIntervention otherIntervention : dest.getOtherInterventions()) {
//            destInterventionsSet.add(otherIntervention.getHashKey());
//        }
//
//        for (OtherIntervention otherIntervention : otherInterventions) {
//            if (destInterventionsSet.add(otherIntervention.getHashKey())) {
//                dest.addOtherIntervention(otherIntervention);
//            }
//        }
    }

}


text:
A basic NCurses client for Steam on Linux

### Features:
- Supports both wine and native games at the same time

### Building:
**Dependencies:**
* Steam
* ncurses-dev package

For Ubuntu flavors:
  * ```sudo apt-get install steam```

  * ```sudo apt-get install libncurses5-dev```

Arch:
  * ```sudo pacman -S ncurses```

  * ```sudo pacman -S steam```

  * It can also be found under the AUR as steamcurses-git

Simply run ```make install``` to build and install.

### Usage:
```
 ./steamcurses -u <username> [options]
   -u --username:         your Steam username
   -p --steam_path:       the path to your steamapps directory
   -w --wine_steam_path:  the path to your wine steamapps directory
   -m --update_manifests: update the generated manifests
   -h --help:             print help message
```


text:
layout:     post
title:      "Meteor Basic Notes"
subtitle:   "Be a stupid learner"
date:       2017-03-05
author:     "sabertazimi"
header-img: "img/home-bg.jpg"
tags:
    - Web
    - Front End
    - Meteor
---

* [Meteor Notes](#meteor-notes)
	* [特殊文件夹](#特殊文件夹)
	* [Basic Command](#basic-command)
		* [create and run](#create-and-run)
		* [list package](#list-package)
		* [add package](#add-package)
		* [android platform](#android-platform)
		* [发布](#发布)
	* [常用Package](#常用package)
		* [barbatus:stars-rating 1.0.7](#barbatusstars-rating-107)
		* [accounts-password 1.1.4](#accounts-password-114)
		* [accounts-ui 1.1.6](#accounts-ui-116)
		* [[iron:router](https://atmospherejs.com/iron/router)](#ironrouterhttpsatmospherejscomironrouter)
		* [twbs:bootstrap 3.3.6](#twbsbootstrap-336)
		* [ecmascript 0.1.6](#ecmascript-016)
		* [jquery 1.11.4](#jquery-1114)
		* [mongo 1.1.3](#mongo-113)
	* [传递数据](#传递数据)
	* [设置事件](#设置事件)
	* [Meteor.user()](#meteoruser)
	* [Session](#session)
	* [MongoDB](#mongodb)
	* [安全性](#安全性)
		* [package的安全性](#package的安全性)
		* [MongoDB/Collection的安全性](#mongodbcollection的安全性)

# Meteor Notes

## 特殊文件夹

public(存放assets)、client、server、lib

## Basic Command

### create and run

```bash
meteor create app_folder_name
cd app_folder_name
meteor
```

### list package

```bash
meteor search .或package_name
```

### add package

```bash
meteor add package_name
```

### android platform

```bash
meteor add-platform android
meteor install-sdk android  // ~/.meteor/android-bundle
meteor run android 或 meteor run android-device
 --mobile-server https://hostname:port  指定(http可不写schema)
```

### 发布

```bash
meteor deploy domain/ip address
meteor deploy –delete domain/ip address
```

## 常用Package

### barbatus:stars-rating 1.0.7

Stars rating control

```js
	{{>starsRating mutable=true class="js-rate-image" id=_id}}

	var rating = $(event.currentTarget).data("userrating");
```

### accounts-password 1.1.4

Password support for accounts

### accounts-ui 1.1.6

Simple templates to add login widgets to an app

```html
	 {{> loginButtons}}
```

### [iron:router](https://atmospherejs.com/iron/router)

```html
<template name="ApplicationLayout">
    {{> yield "navbar"}}	<!--规定html区域-->
    {{> yield "main"}}		<!--规定html区域-->
</template>
```

```javascript
Router.configure( {
    layoutTemplate: "ParentTemplateName"  //e.g"ApplicationLayout"
});
```

```javascript
Router.route('/', function () {
  this.render('MyTemplate');
});

Router.route('/items', function () {
  this.render('Items');
});

Router.route('/items', function () {
  this.render('TemplateName': {
	to: "yieldFunctionArgument"    //规定html区域
  });
});

Router.route('/items/_id', function () {
  this.render('TemplateName'{
	to:"yieldFunctionArgument",    //规定html区域
	data:function() {    //传递Template中的特定数据
		return Collection.FindOne({_id: this.params._id});
	}
	});
});

Router.route('/items/:_id', function () {
  var item = Items.findOne({_id: this.params._id});
  this.render('ShowItem', {data: item});
});

Router.route('/files/:filename', function () {
  this.response.end('hi from the server\n');
}, {where: 'server'});

Router.route('/restful', {where: 'server'})
  .get(function () {
    this.response.end('get request\n');
  })
  .post(function () {
    this.response.end('post request\n');
});
```

### twbs:bootstrap 3.3.6

The most popular front-end framework for developing responsive, mobile first projects on the web.

### ecmascript 0.1.6

Compiler plugin that supports ES2015+ in all .js files

### jquery 1.11.4

Manipulate the DOM using CSS selectors

### mongo 1.1.3

Adaptor for using MongoDB and Minimongo over DDP

## 传递数据

```js
//data_variable为对象
Template.html_templatetag_name.helpers(data_variable);
//data_variable为对象数组
Template.html_templateTag_name.helpers(
	{
		property_name:data_variable, e.g Collection.find()、数组名、函数
		prepertyn:data_variablen
	}
);    //传递一个匿名对象参数,它拥有一个对象数组字段/实例域

Template.body.helpers
```

html invoke:

```html
{{#each property_name}}  <img src="{{img_src}}" alt="{{img_alt}}">  {{/each}}
{{#if property_name}} {{/if}}

{{property function_argument}}
```

## 设置事件

```js
//传递一个匿名对象参数,拥有一个函数字段/实例域
Template.templateTag_name.events({
	'click .inner_class_name/#inner_id_name' : function (event) {
		//TODO with coding
		//$(event.target) 选择产生事件的对象
		//$(event.currentTarget)
	},
	'submit jqueryid/jqueryclass' : function(event) {
		event.target.inputTag_name.value;
	}
});
```

## Meteor.user()

```js
Meteor.user()
Meteor.users.find()
Meteor.users.findOne(filter)
Meteor.user().email[num].address
Meteor.user().username
Meteor.user()._id
```

```html
{{#if currentUser}}   {{/if}}
```

## Session

-   将对象的某一个属性设为过滤器

```js
Session.set("userFilter", Object.property_nmae);
```

-   通过get得到过滤器属性值(已设置过滤器为有效值,未设置过滤器为NULL)

```js
{ property_name: Session.get("userFilter") }
```

-   移除过滤器

```js
Session.set("userFilter", undefined);
```

## MongoDB

-   `Meteor.startup( function() {});`

当客户端启动应用时,运行isClient与isServer代码

作用:a.若数据库无数据,则预存一定量数据

-    `new Mongo.Collection("name_string");`

创建Mongo集合——

```js
find( {selector },                   //选择器 propername:filter_value
	{sort : { fieldname : -1 } }  , //从小至大排列的filter
	limit:number
)
```

count、insert(对象{})、remove(Mongo Filter)

update({键值对}、{$set	{键值对}})
	可通过update读入用户操作,更新数据库,可再次反馈给用户

allow(安全性)

## 安全性

### package的安全性

meteor remove insecure

### MongoDB/Collection的安全性


text:
<?php
namespace Amiss\Test\Unit;

use Amiss\Type;
use Amiss\Sql;

/**
 * @group unit
 */
class DateTest extends \Amiss\Test\Helper\TestCase
{
    public function setUp()
    {}

    public function testUnixPrepareForDb()
    {
        $handler = new \Amiss\Sql\Type\Date(['formats'=>'U', 'appTimeZone'=>'UTC', 'dbTimeZone'=>'UTC']);
        $out = $handler->prepareValueForDb($this->createDate('2012-01-01 01:00:00', 'UTC'), array());
        $this->assertEquals(1325379600, $out);
    }

    public function testUnixHandleFromDb()
    {
        $handler = new \Amiss\Sql\Type\Date(['formats'=>'U', 'appTimeZone'=>'UTC', 'dbTimeZone'=>'UTC']);
        $out = $handler->handleValueFromDb(1325379600, array(), array());

        $expected = $this->createDate('2012-01-01 01:00:00', 'UTC');
        $this->assertEquals($expected, $out);
    }

    public function testUnixHandleFromDbWithTimeZone()
    {
        $handler = new \Amiss\Sql\Type\Date(['formats'=>'U', 'appTimeZone'=>'UTC', 'dbTimeZone'=>'Australia/Melbourne']);
        $out = $handler->handleValueFromDb(1, array(), array());

        $expected = $this->createDate('1970-01-01 10:00:01', 'Australia/Melbourne');
        $this->assertEquals($expected, $out);
    }

    public function testUnixHandleZeroFromDb()
    {
        $handler = new \Amiss\Sql\Type\Date(['formats'=>'U', 'appTimeZone'=>'UTC', 'dbTimeZone'=>'UTC']);
        $out = $handler->handleValueFromDb(0, array(), array());
        $expected = $this->createDate('1970-01-01 00:00:00', 'UTC');
        $this->assertEquals($expected, $out);
    }

    /**
     * @dataProvider dataForHandleFromDbWithMultipleFormats
     */
    public function testDateTimeHandleFromDbWithMultipleFormats($format, $value, $expected)
    {
        // Handler order is deliberate - it ensures that the third one is
        // picked up before the second when the incoming value contains the
        // extra values.
        $handler = new \Amiss\Sql\Type\Date([
            'formats'=>['Y-m-d H:i:s', 'Y-m-d', 'Y-m-d H:i'],
            'appTimeZone'=>'Australia/Melbourne',
            'dbTimeZone'=>'Australia/Melbourne'
        ]);
        $out = $handler->handleValueFromDb($value, array(), array());
        $expected = \DateTime::createFromFormat("Y-m-d H:i:s", $expected, new \DateTimeZone('Australia/Melbourne'));
        $this->assertEquals($expected, $out);
    }

    public function dataForHandleFromDbWithMultipleFormats()
    {
        return array(
            array("Y-m-d H:i:s", "2012-03-02 11:10:09", "2012-03-02 11:10:09"),
            array("Y-m-d H:i", "2012-03-02 11:10", "2012-03-02 11:10:00"),
            array("Y-m-d", "2012-03-02", "2012-03-02 00:00:00"),
        );
    }

    /**
     * @dataProvider dataForHandleFromDbWithEmptyValueReturnsNull
     */
    public function testDateTimeHandleFromDbWithEmptyValueReturnsNull($value)
    {
        $handler = new \Amiss\Sql\Type\Date(['formats'=>"datetime", 'appTimeZone'=>'Australia/Melbourne', 'dbTimeZone'=>'Australia/Melbourne']);
        $out = $handler->handleValueFromDb($value, array(), array());
        $this->assertNull($out);
    }

    public function dataForHandleFromDbWithEmptyValueReturnsNull()
    {
        return array(
            array(false),
            array(""),
            array(null),
        );
    }

    public function testDateTimeHandleFromDbWithMultipleFormatsFailsWhenNoFormatMatches()
    {
        $handler = new \Amiss\Sql\Type\Date(['formats'=>['Y-m-d H:i:s'], 'appTimeZone'=>'Australia/Melbourne', 'dbTimeZone'=>'Australia/Melbourne']);
        $this->setExpectedException('UnexpectedValueException', 'Date \'2012-03-04\' could not be handled with any of the following formats: Y-m-d H:i:s');
        $out = $handler->handleValueFromDb('2012-03-04', array(), array());
    }

    public function testDateTimePrepareForDb()
    {
        $handler = new \Amiss\Sql\Type\Date(['formats'=>'Y-m-d H:i:s', 'appTimeZone'=>'Australia/Melbourne', 'dbTimeZone'=>'Australia/Melbourne']);
        $out = $handler->prepareValueForDb($this->createDate('2012-01-01 12:00:00', 'Australia/Melbourne'), array());
        $this->assertEquals('2012-01-01 12:00:00', $out);
    }

    public function dateFromDbZeroesTimeProvider()
    {
        return [
            ['00:00', '00:00:00'],
            ['23:59', '23:59:00'],
            ['23:59:59', '23:59:59'],
            ['00:00:00', '00:00:00'],
            [['00', '00', '00'], '00:00:00'],
        ];
    }

    /** @dataProvider dateFromDbZeroesTimeProvider */
    public function testDateFromDbZeroesTime($in, $out)
    {
        $handler = new \Amiss\Sql\Type\Date([
            'formats'=>'date',
            'appTimeZone'=>'Australia/Melbourne',
            'dbTimeZone'=>'Australia/Melbourne',
            'forceTime'=>$in,
        ]);
        $result = $handler->handleValueFromDb('2012-03-04', [], []);
        $this->assertEquals($result, new \DateTime('2012-03-04 '.$out, new \DateTimeZone('Australia/Melbourne')));
    }

    public function testDateTimeImmutablePrepareForDb()
    {
        $handler = new \Amiss\Sql\Type\Date([
            'formats'=>'Y-m-d H:i:s',
            'appTimeZone'=>'Australia/Melbourne',
            'dbTimeZone'=>'Australia/Melbourne',
        ]);
        $out = $handler->prepareValueForDb(new \DateTimeImmutable('2012-01-01 12:00:00', new \DateTimeZOne('Australia/Melbourne')), []);
        $this->assertEquals('2012-01-01 12:00:00', $out);
    }

    public function testDateTimePrepareForDbWithDifferentDbTimeZone()
    {
        $handler = new \Amiss\Sql\Type\Date(['formats'=>'Y-m-d H:i:s', 'dbTimeZone'=>'UTC', 'appTimeZone'=>'Australia/Melbourne']);
        $out = $handler->prepareValueForDb($this->createDate('2012-01-01 12:00:00', 'Australia/Melbourne'), array());

        // Date should be converted to UTC before save
        $this->assertEquals('2012-01-01 01:00:00', $out);
    }

    private function createDate($date, $tz)
    {
        if ($tz && is_string($tz)) {
            $tz = new \DateTimeZone($tz);
        }
        return \DateTime::createFromFormat('Y-m-d H:i:s', $date, $tz);
    }

    public function testDateTimeCustomClassPrepareForDb()
    {
        $class = __NAMESPACE__.'\PantsDateTime';
        $tz = new \DateTimeZone('UTC');
        $handler = new \Amiss\Sql\Type\Date([
            'formats'=>'Y-m-d H:i:s',
            'appTimeZone'=>'UTC',
            'dbTimeZone'=>'UTC',
            'classes'=>[$class],
        ]);
        $out = $handler->prepareValueForDb(new PantsDateTime('2015-01-01', $tz), array());
        $this->assertEquals('2015-01-01 00:00:00', $out);
    }

    public function testDateTimeCustomClassHandleValueFromDb()
    {
        $class = __NAMESPACE__.'\PantsDateTime';
        $tz = new \DateTimeZone('UTC');
        $handler = new \Amiss\Sql\Type\Date([
            'formats'=>'Y-m-d H:i:s',
            'appTimeZone'=>'UTC',
            'dbTimeZone'=>'UTC',
            'classes'=>$class
        ]);
        $out = $handler->handleValueFromDb('2015-01-01 00:00:00', [], array());
        $this->assertInstanceOf($class, $out);
    }

    public function testDateTimeCustomClassFailsWhenPassedRawDateTime()
    {
        $class = __NAMESPACE__.'\PantsDateTime';
        $tz = new \DateTimeZone('UTC');
        $handler = new \Amiss\Sql\Type\Date([
            'formats'=>'Y-m-d H:i:s',
            'appTimeZone'=>'UTC',
            'dbTimeZone'=>'UTC',
            'classes'=>$class
        ]);

        $this->setExpectedException(
            'UnexpectedValueException',
            "Date value was invalid. Expected $class, found DateTime"
        );
        $out = $handler->prepareValueForDb(new \DateTime('2015-01-01', $tz), array());
    }

    public function testDateTimeCustomClassFailsWhenPassedString()
    {
        $class = __NAMESPACE__.'\PantsDateTime';
        $tz = new \DateTimeZone('UTC');
        $handler = new \Amiss\Sql\Type\Date([
            'formats'=>'Y-m-d H:i:s',
            'appTimeZone'=>'UTC',
            'dbTimeZone'=>'UTC',
            'classes'=>$class
        ]);

        $this->setExpectedException(
            'UnexpectedValueException',
            "Date value was invalid. Expected $class, found string"
        );
        $out = $handler->prepareValueForDb('2015-01-01', array());
    }
}

class PantsDateTime extends \DateTime
{
    public static function createFromFormat($format, $time, $tz=null)
    {
        $dateTime = \DateTime::createFromFormat($format, $time, $tz);
        $dt = new static('@'.$dateTime->getTimeStamp(), new \DateTimeZone('UTC'));
        $dt->setTimeZone($dateTime->getTimeZone());
        return $dt;
    }
}


text:
package org.springframework.boot.validation;

import java.util.LinkedHashSet;
import java.util.Locale;
import java.util.Set;

import javax.validation.MessageInterpolator;

import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;

/**
 * Resolves any message parameters via {@link MessageSource} and then interpolates a
 * message using the underlying {@link MessageInterpolator}.
 *
 * @author Dmytro Nosan
 */
class MessageSourceMessageInterpolator implements MessageInterpolator {

	private static final char PREFIX = '{';

	private static final char SUFFIX = '}';

	private static final char ESCAPE = '\\';

	private final MessageSource messageSource;

	private final MessageInterpolator messageInterpolator;

	MessageSourceMessageInterpolator(MessageSource messageSource, MessageInterpolator messageInterpolator) {
		this.messageSource = messageSource;
		this.messageInterpolator = messageInterpolator;
	}

	@Override
	public String interpolate(String messageTemplate, Context context) {
		return interpolate(messageTemplate, context, LocaleContextHolder.getLocale());
	}

	@Override
	public String interpolate(String messageTemplate, Context context, Locale locale) {
		String message = replaceParameters(messageTemplate, locale);
		return this.messageInterpolator.interpolate(message, context, locale);
	}

	/**
	 * Recursively replaces all message parameters.
	 *

	 * The message parameter prefix { and suffix } can
	 * be escaped using {@code \}, e.g. \{escaped\}.
	 * @param message the message containing the parameters to be replaced
	 * @param locale the locale to use when resolving replacements
	 * @return the message with parameters replaced
	 */
	private String replaceParameters(String message, Locale locale) {
		return replaceParameters(message, locale, new LinkedHashSet<>(4));
	}

	private String replaceParameters(String message, Locale locale, Set<String> visitedParameters) {
		StringBuilder buf = new StringBuilder(message);
		int parentheses = 0;
		int startIndex = -1;
		int endIndex = -1;
		for (int i = 0; i < buf.length(); i++) {
			if (buf.charAt(i) == ESCAPE) {
				i++;
			}
			else if (buf.charAt(i) == PREFIX) {
				if (startIndex == -1) {
					startIndex = i;
				}
				parentheses++;
			}
			else if (buf.charAt(i) == SUFFIX) {
				if (parentheses > 0) {
					parentheses--;
				}
				endIndex = i;
			}
			if (parentheses == 0 && startIndex < endIndex) {
				String parameter = buf.substring(startIndex + 1, endIndex);
				if (!visitedParameters.add(parameter)) {
					throw new IllegalArgumentException("Circular reference '{" + String.join(" -> ", visitedParameters)
							+ " -> " + parameter + "}'");
				}
				String value = replaceParameter(parameter, locale, visitedParameters);
				if (value != null) {
					buf.replace(startIndex, endIndex + 1, value);
					i = startIndex + value.length() - 1;
				}
				visitedParameters.remove(parameter);
				startIndex = -1;
				endIndex = -1;
			}
		}
		return buf.toString();
	}

	private String replaceParameter(String parameter, Locale locale, Set<String> visitedParameters) {
		parameter = replaceParameters(parameter, locale, visitedParameters);
		String value = this.messageSource.getMessage(parameter, null, null, locale);
		return (value != null) ? replaceParameters(value, locale, visitedParameters) : null;
	}

}


text:
Lorem

Lorem ipsum ad his scripta blandit partiendo, eum fastidii accumsan euripidis in, eum liber hendrerit an. Qui ut wisi vocibus suscipiantur, quo dicit ridens inciderint id. Quo mundi lobortis reformidans eu, legimus senserit definiebas an eos. Eu sit tincidunt incorrupte definitionem, vis mutat affert percipit cu, eirmod consectetuer signiferumque eu per. In usu latine equidem dolores.

Lorem ipsum ad his scripta blandit partiendo, eum fastidii accumsan euripidis in, eum liber hendrerit an. Qui ut wisi vocibus suscipiantur, quo dicit ridens inciderint id. Quo mundi lobortis reformidans eu, legimus senserit definiebas an eos. Eu sit tincidunt incorrupte definitionem, vis mutat affert percipit cu, eirmod consectetuer signiferumque eu per. In usu latine equidem dolores.


text:
//
//  wl_PathFinder.h
//  PathFinder
//
//  Created by Sid on 13/12/14.
//  Copyright (c) 2014 whackylabs. All rights reserved.
//

#ifndef __PathFinder__wl_PathFinder__
#define __PathFinder__wl_PathFinder__
#include "wl_Map.h"

namespace wl {

    std::list<Tile*> FindPath(const Coordinate &start,
                                   const Coordinate &end,
                                   Map &map);

}

#endif /* defined(__PathFinder__wl_PathFinder__) */


text:
Dear {{ user.username }},
Welcome to Rec_sys!
To confirm your account please click on the following link:
{{ url_for('auth.confirm',token=token,_external=True) }}

Sincerely,
Zhao Pengya

Note:Do not reply to this email address.


text:
using Microsoft.AspNetCore.Html;
using System.Threading.Tasks;

namespace OrchardCore.DisplayManagement.Implementation
{
    /// <summary>
    /// Coordinates the rendering of shapes.
    /// This interface isn't used directly - instead you would call through a
    /// DisplayHelper created by the IDisplayHelperFactory interface
    /// </summary>
    public interface IHtmlDisplay
    {
        Task<IHtmlContent> ExecuteAsync(DisplayContext context);
    }
}


text:
package org.camunda.bpm.engine.impl.jobexecutor;

/**
 * @author Thorben Lindhauer
 *
 */
public interface JobAcquisitionStrategy {

  void reconfigure(JobAcquisitionContext context);

  long getWaitTime();

  int getNumJobsToAcquire(String processEngine);

}


text:
YUI.add('widget-uievents', function(Y) {

/**
 * Support for Widget UI Events (Custom Events fired by the widget, which wrap the underlying DOM events - e.g. widget:click, widget:mousedown)
 *
 * @module widget
 * @submodule widget-uievents
 */

var BOUNDING_BOX = "boundingBox",
    Widget = Y.Widget,
    RENDER = "render",
    L = Y.Lang,
    EVENT_PREFIX_DELIMITER = ":";

Y.mix(Widget.prototype, {

    /**
     * Destructor logic for UI event infrastructure,
     * invoked during Widget destruction.
     *
     * @method _destroyUIEvents
     * @for Widget
     * @private
     */
    _destroyUIEvents: function() {

        var widgetGuid = Y.stamp(this, true),
            uievts = this._uievts;

        if (uievts) {
            Y.each(uievts, function (info, key) {
                if (info.instances[widgetGuid]) {
                    //  Unregister this Widget instance as needing this delegated
                    //  event listener.
                    delete info.instances[widgetGuid];

                    //  There are no more Widget instances using this delegated
                    //  event listener, so detach it.

                    if (Y.Object.isEmpty(info.instances)) {
                        info.handle.detach();

                        if (uievts[key]) {
                            delete uievts[key];
                        }
                    }
                }
            });
        }
    },

    /**
     * Map of DOM events that should be fired as Custom Events by the
     * Widget instance.
     *
     * @property UI_EVENTS
     * @for Widget
     * @type Object
     */
    UI_EVENTS: Y.Node.DOM_EVENTS,

    /**
     * Returns the node on which to bind delegate listeners.
     *
     * @method _getUIEventNode
     * @for Widget
     * @protected
     */
    _getUIEventNode: function () {
        return this.get(BOUNDING_BOX);
    },

    /**
     * Binds a delegated DOM event listener of the specified type to the
     * Widget's outtermost DOM element to facilitate the firing of a Custom
     * Event of the same type for the Widget instance.
     *
     * @private
     * @for Widget
     * @method _createUIEvent
     * @param type {String} String representing the name of the event
     */
    _createUIEvent: function (type) {

        var uiEvtNode = this._getUIEventNode(),
            key = (Y.stamp(uiEvtNode) + type),
            info,
            handle;

        this._uievts = this._uievts || {};
        info = this._uievts[key];

        //  For each Node instance: Ensure that there is only one delegated
        //  event listener used to fire Widget UI events.

        if (!info) {
            Y.log("Creating delegate for the " + type + " event.", "info", "widget");

            handle = uiEvtNode.delegate(type, function (evt) {

                var widget = Widget.getByNode(this);
                //  Make the DOM event a property of the custom event
                //  so that developers still have access to it.
                widget.fire(evt.type, { domEvent: evt });

            }, "." + Y.Widget.getClassName());

            this._uievts[key] = info = { instances: {}, handle: handle };
        }

        //  Register this Widget as using this Node as a delegation container.
        info.instances[Y.stamp(this)] = 1;
    },

    /**
     * Determines if the specified event is a UI event.
     *
     * @private
     * @method _isUIEvent
     * @for Widget
     * @param type {String} String representing the name of the event
     * @return {String} Event Returns the name of the UI Event, otherwise
     * undefined.
     */
    _getUIEvent: function (type) {

        if (L.isString(type)) {
            var sType = this.parseType(type)[1],
                iDelim,
                returnVal;

            if (sType) {
                // TODO: Get delimiter from ET, or have ET support this.
                iDelim = sType.indexOf(EVENT_PREFIX_DELIMITER);
                if (iDelim > -1) {
                    sType = sType.substring(iDelim + EVENT_PREFIX_DELIMITER.length);
                }

                if (this.UI_EVENTS[sType]) {
                    returnVal = sType;
                }
            }

            return returnVal;
        }
    },

    /**
     * Sets up infastructure required to fire a UI event.
     *
     * @private
     * @method _initUIEvent
     * @for Widget
     * @param type {String} String representing the name of the event
     * @return {String}
     */
    _initUIEvent: function (type) {
        var sType = this._getUIEvent(type),
            queue = this._uiEvtsInitQueue || {};

        if (sType && !queue[sType]) {
            Y.log("Deferring creation of " + type + " delegate until render.", "info", "widget");

            this._uiEvtsInitQueue = queue[sType] = 1;

            this.after(RENDER, function() {
                this._createUIEvent(sType);
                delete this._uiEvtsInitQueue[sType];
            });
        }
    },

    //  Override of "on" from Base to facilitate the firing of Widget events
    //  based on DOM events of the same name/type (e.g. "click", "mouseover").
    //  Temporary solution until we have the ability to listen to when
    //  someone adds an event listener (bug 2528230)
    on: function (type) {
        this._initUIEvent(type);
        return Widget.superclass.on.apply(this, arguments);
    },

    //  Override of "publish" from Base to facilitate the firing of Widget events
    //  based on DOM events of the same name/type (e.g. "click", "mouseover").
    //  Temporary solution until we have the ability to listen to when
    //  someone publishes an event (bug 2528230)
    publish: function (type, config) {
        var sType = this._getUIEvent(type);
        if (sType && config && config.defaultFn) {
            this._initUIEvent(sType);
        }
        return Widget.superclass.publish.apply(this, arguments);
    }

}, true); // overwrite existing EventTarget methods

}, '@VERSION@' ,{requires:['widget-base', 'node-event-delegate']});


text:
module Spree
  class Context < Spree::Base
    include PersistedDynamicAttribute
    include TemporalDynamicAttribute

    has_many :line_items, class_name: 'Spree::LineItem',
                          foreign_key: 'context_id'
    has_many :context_option_values, class_name: 'Spree::ContextOptionValue',
                                     foreign_key: 'context_id',
                                     dependent: :destroy

    def initialize_variables
      @temporal = {}
    end

    attr_reader :temporal

    class << self
      # This argument `params` is already sanitized by the class Spree::ParamsSanitize
      def build_from_params(params, options = {})
        raise StandardError, 'You must be explicit about temporal or not' if options[:temporal].nil?

        context = fetch_context(options)

        context.initialize_variables

        temporal_or_persisted(context, options, params)

        context
      end

      private

      def temporal_or_persisted(context, options, params)
        return context.set_temporal_option_values(params) if options[:temporal]

        context.persist_option_values(params)
        context.save!
      end

      def fetch_context(options)
        return Spree::Context.new if options[:line_item_id].nil?

        Spree::LineItem.find(options[:line_item_id]).context
      end
    end

    def find_existing_option_value(option_type)
      context_option_values.includes(option_value: :option_type)
                           .find { |cov| cov.option_value&.option_type_id == option_type.id }
    end

    def get_mixed_option_value(option_type, options = { temporal: true })
      return get_temporal_option_value(option_type.name) if options[:temporal]

      persisted_option_value(option_type)
    end
  end
end


text:
    //
    //      Forward declarations for many DX11 types.
    //
    //      Most the Metal interface for DX11 can be included without DX11.h
    //      by just forward declarations for the DX11 types (as so...)
    //
struct ID3D11Texture2D;
struct ID3D11RenderTargetView;
struct ID3D11ShaderResourceView;
struct ID3D11DepthStencilView;
struct ID3D11Resource;
struct ID3D11DeviceContext;
struct ID3D11Device;
struct ID3D11CommandList;
struct ID3D11Buffer;
struct ID3D11Texture1D;
struct ID3D11Texture3D;
struct ID3D11DeviceChild;
struct ID3D11Query;
struct ID3D11View;
struct ID3D10Blob;
struct ID3D11VertexShader;
struct ID3D11PixelShader;
struct ID3D11GeometryShader;
struct ID3D11ComputeShader;
struct ID3D11HullShader;
struct ID3D11DomainShader;
struct ID3D11InputLayout;
struct ID3D11SamplerState;
struct ID3D11RasterizerState;
struct ID3D11BlendState;
struct ID3D11DepthStencilState;
struct ID3D11ShaderReflection;
struct ID3D11ShaderReflectionConstantBuffer;
struct ID3D11ShaderReflectionVariable;
struct ID3D11UnorderedAccessView;
struct ID3D11ClassLinkage;
struct ID3D11ClassInstance;
struct IUnknown;

struct ID3D11Resource1;
struct ID3D11DeviceChild1;
struct ID3D11DeviceContext1;
struct ID3D11Device1;

struct ID3DUserDefinedAnnotation;

struct _GUID;
typedef struct _GUID GUID;
typedef long HRESULT;
enum D3D_FEATURE_LEVEL;

struct IDXGIDevice1;
struct IDXGISwapChain;
struct IDXGIAdapter1;
struct IDXGIFactory1;
typedef enum DXGI_FORMAT DXGI_FORMAT;

typedef struct D3D11_BLEND_DESC D3D11_BLEND_DESC;
typedef struct D3D11_DEPTH_STENCIL_DESC D3D11_DEPTH_STENCIL_DESC;
typedef struct D3D11_RASTERIZER_DESC D3D11_RASTERIZER_DESC;
typedef struct D3D11_SAMPLER_DESC D3D11_SAMPLER_DESC;
typedef struct D3D11_BUFFER_DESC D3D11_BUFFER_DESC;
typedef struct D3D11_TEXTURE1D_DESC D3D11_TEXTURE1D_DESC;
typedef struct D3D11_TEXTURE2D_DESC D3D11_TEXTURE2D_DESC;
typedef struct D3D11_TEXTURE3D_DESC D3D11_TEXTURE3D_DESC;
typedef struct D3D11_SUBRESOURCE_DATA D3D11_SUBRESOURCE_DATA;
typedef struct D3D11_RENDER_TARGET_VIEW_DESC D3D11_RENDER_TARGET_VIEW_DESC;
typedef struct D3D11_SHADER_RESOURCE_VIEW_DESC D3D11_SHADER_RESOURCE_VIEW_DESC;
typedef struct D3D11_UNORDERED_ACCESS_VIEW_DESC D3D11_UNORDERED_ACCESS_VIEW_DESC;
typedef struct D3D11_DEPTH_STENCIL_VIEW_DESC D3D11_DEPTH_STENCIL_VIEW_DESC;
typedef struct D3D11_SO_DECLARATION_ENTRY D3D11_SO_DECLARATION_ENTRY;
typedef struct D3D11_INPUT_ELEMENT_DESC D3D11_INPUT_ELEMENT_DESC;
typedef struct D3D11_QUERY_DESC D3D11_QUERY_DESC;

#define DX_VERSION_11           1
#define DX_VERSION_11_1         2
#define DX_VERSION              DX_VERSION_11_1

namespace ID3D
{
    using Texture2D             = ID3D11Texture2D;
    using TextureCube           = ID3D11Texture2D;
    using RenderTargetView      = ID3D11RenderTargetView;
    using ShaderResourceView    = ID3D11ShaderResourceView;
    using DepthStencilView      = ID3D11DepthStencilView;
    using CommandList           = ID3D11CommandList;
    using Buffer                = ID3D11Buffer;
    using Texture1D             = ID3D11Texture1D;
    using Texture3D             = ID3D11Texture3D;
    using Query                 = ID3D11Query;
    using View                  = ID3D11View;
    using Blob                  = ID3D10Blob;
    using VertexShader          = ID3D11VertexShader;
    using PixelShader           = ID3D11PixelShader;
    using GeometryShader        = ID3D11GeometryShader;
    using ComputeShader         = ID3D11ComputeShader;
    using HullShader            = ID3D11HullShader;
    using DomainShader          = ID3D11DomainShader;
    using InputLayout           = ID3D11InputLayout;
    using SamplerState          = ID3D11SamplerState;
    using RasterizerState       = ID3D11RasterizerState;
    using BlendState            = ID3D11BlendState;
    using DepthStencilState     = ID3D11DepthStencilState;
    using ShaderReflection      = ID3D11ShaderReflection;
    using ShaderReflectionConstantBuffer    = ID3D11ShaderReflectionConstantBuffer;
    using ShaderReflectionVariable          = ID3D11ShaderReflectionVariable;
    using UnorderedAccessView   = ID3D11UnorderedAccessView;
    using ClassLinkage          = ID3D11ClassLinkage;
    using ClassInstance         = ID3D11ClassInstance;

    #if DX_VERSION == DX_VERSION_11_1
        using DeviceContext1    = ID3D11DeviceContext1;
        using Device1           = ID3D11Device1;
    #endif

    using DeviceContext         = ID3D11DeviceContext;
    using Device                = ID3D11Device;
    using DeviceChild           = ID3D11DeviceChild;
    using Resource              = ID3D11Resource;
    using UserDefinedAnnotation = ID3DUserDefinedAnnotation;
}

namespace IDXGI
{
    using Device        = IDXGIDevice1;
    using SwapChain     = IDXGISwapChain;
    using Adapter       = IDXGIAdapter1;
    using Factory       = IDXGIFactory1;
}


text:
package uk.co.ribot.easyadapter;

/**
 * This class holds information about the position of an item in the {@link uk.co.ribot.easyadapter.EasyAdapter}
 */
public class PositionInfo {

    private int mPosition;
    private boolean mFirst;
    private boolean mLast;

    /**
     * Constructs an empty PositionInfo object
     */
    public PositionInfo() {

    }

    /**
     * Constructs a PositionInfo with: position, first and last
     *
     * @param position the position of the item
     * @param first    true if the item is the first
     * @param last     true if the item is the last
     */

    public PositionInfo(int position, boolean first, boolean last) {
        setPosition(position);
        setFirst(first);
        setLast(last);
    }

    /**
     * @return position of the item in the {@link uk.co.ribot.easyadapter.EasyAdapter}
     */
    public int getPosition() {
        return mPosition;
    }

    /**
     * @return true if the item is the first one in the {@link uk.co.ribot.easyadapter.EasyAdapter}
     */
    public boolean isFirst() {
        return mFirst;
    }

    /**
     * @return true if the item is the last one in the {@link uk.co.ribot.easyadapter.EasyAdapter}
     */
    public boolean isLast() {
        return mLast;
    }

    /**
     * Sets the position of the item
     *
     * @param position position of the item
     */
    public void setPosition(int position) {
        mPosition = position;
    }

    /**
     * Sets whether the item is the first one or not
     *
     * @param first true if the item is the first
     */
    public void setFirst(boolean first) {
        mFirst = first;
    }

    /**
     * Sets whether the item is the last one or not
     *
     * @param last true if the item is the last
     */
    public void setLast(boolean last) {
        mLast = last;
    }
}


text:
package com.jnape.devnexus.demo.examples;

import com.jnape.devnexus.demo.functions.Function1;
import com.jnape.devnexus.demo.functions.Function2;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

import static java.util.Arrays.asList;

public class Folds {

    private static final Function2<String, String, String> EXPLAIN_FOLD = new Function2<String, String, String>() {
        @Override
        public String apply(String acc, String x) {
            return "f(" + acc + ", " + x + ")";
        }
    };
    private static final Function1<String, String>         EXPLAIN_MAP  = new Function1<String, String>() {
        @Override
        public String apply(String x) {
            return "f(" + x + ")";
        }
    };

    public static void main(String[] args) {
        List<String> numbers = asList("1", "2", "3", "4", "5");

        System.out.println("foldLeft: " + foldLeft(EXPLAIN_FOLD, "0", numbers));
        System.out.println("foldRight: " + foldRight(EXPLAIN_FOLD, "0", numbers));
        System.out.println("reduceLeft: " + reduceLeft(EXPLAIN_FOLD, numbers));
        System.out.println("reduceRight: " + reduceRight(EXPLAIN_FOLD, numbers));
        System.out.println("map: " + map(EXPLAIN_MAP, numbers));
    }

    public static <A, B> Iterable<B> map(final Function1<A, B> fn, Iterable<A> xs) {
        return foldLeft(new Function2<List<B>, A, List<B>>() {
            @Override
            public List<B> apply(List<B> bs, A a) {
                bs.add(fn.apply(a));
                return bs;
            }
        }, new ArrayList<B>(), xs);
    }

    public static <Acc, Element> Acc foldLeft(Function2<Acc, Element, Acc> fn, Acc acc, Iterable<Element> elements) {
        Iterator<Element> iterator = elements.iterator();
        Acc result = acc;
        while (iterator.hasNext())
            result = fn.apply(result, iterator.next());
        return result;
    }

    public static <Element> Element reduceLeft(Function2<Element, Element, Element> fn,
                                               Iterable<Element> elements) {
        final Iterator<Element> iterator = elements.iterator();
        return foldLeft(fn, iterator.next(), new Iterable<Element>() {
            @Override
            public Iterator<Element> iterator() {
                return iterator;
            }
        });
    }

    public static <Acc, Element> Acc foldRight(final Function2<Element, Acc, Acc> fn, final Acc acc,
                                               Iterable<Element> elements) {
        return foldLeft(fn.flip(), acc, reverse(elements));
    }

    public static <Element> Element reduceRight(final Function2<Element, Element, Element> fn,
                                                Iterable<Element> elements) {
        return reduceLeft(fn.flip(), reverse(elements));
    }

    private static <Element> Iterable<Element> reverse(final Iterable<Element> elements) {
        return new Iterable<Element>() {
            @Override
            public Iterator<Element> iterator() {
                ArrayList<Element> listCopy = new ArrayList<Element>() {{
                    for (Element element : elements) {
                        add(element);
                    }
                }};
                final ListIterator<Element> reversingIterator = listCopy.listIterator(listCopy.size());

                return new Iterator<Element>() {
                    @Override
                    public boolean hasNext() {
                        return reversingIterator.hasPrevious();
                    }

                    @Override
                    public Element next() {
                        return reversingIterator.previous();
                    }

                    @Override
                    public void remove() {
                        throw new UnsupportedOperationException();
                    }
                };
            }
        };
    }
}


text:
[pipeline](https://p-concourse.wings.cf-app.com/teams/system-team-pivotalui-pivui-d6f4/pipelines/pivotal-ui)

## Set pipeline

1. Install the [lastpass cli](https://github.com/lastpass/lastpass-cli)
1. Download fly from [concourse](https://p-concourse.wings.cf-app.com/teams/system-team-pivotalui-pivui-d6f4/pipelines/pivotal-ui)
1. `lpass login`
1. `fly -t wings login -c https://p-concourse.wings.cf-app.com -n system-team-pivotalui-pivui-d6f4`
1. `fly -t wings set-pipeline -c ./pipeline.yml -p pivotal-ui --load-vars-from <(lpass show --notes "Shared-Pivotal UI/concourse/credentials.yml")`

## Build dockerfile

##### Build

1. [Start docker machine](https://docs.docker.com/machine/)
1. `eval $(docker-machine env default)`
1. `docker build . -t pivotalui/concourse:v<NEXT_NUMBER>`

##### Run tests on docker image

```
docker run -it pivotalui/concourse /bin/bash
git clone https://github.com/pivotal-cf/pivotal-ui /pivotal-ui
cd /pivotal-ui/library
npm i
gulp build
gulp ci
cd ../styleguide
npm i
gulp styleguide-build
cd ../styleguide_new
npm i
./node_modules/.bin/webpack --config backend-webpack.config.babel.js --progress
./node_modules/.bin/webpack --config frontend-webpack.config.babel.js --progress
./node_modules/.bin/selenium-standalone install
./node_modules/.bin/selenium-standalone start &
./node_modules/.bin/gemini --reporter flat test
```

##### Publish

1. `docker login` (credentials are in lastpass)
1. `docker push pivotalui/concourse:v<SOME_NUMBER>`


text:
speaker: lex
title: "UpSet: Visualization of Intersecting Sets"
# paper | invited | keynote | tutorial |
type: paper
slides-key:
slides-ppt: https://sci.utah.edu/~vdl/talks/2015-04-23_UpSet.pptx
slides-pdf: https://sci.utah.edu/~vdl/talks/2015-04-23_UpSet.pdf
date: 2014-11-03

held:
 - IEEE InfoVis, Paris, France, 2014-11-03.
---


text:
"""Add data_source_urls to job_executions to support placeholders

Revision ID: 021
Revises: 020
Create Date: 2015-02-24 12:47:17.871520

"""

# revision identifiers, used by Alembic.
revision = '021'
down_revision = '020'

from alembic import op
import sqlalchemy as sa

from sahara.db.sqlalchemy import types as st

def upgrade():
    op.add_column('job_executions',
                  sa.Column('data_source_urls', st.JsonEncoded()))


text:
public class Server_Command {

    // protected
    protected Server_CmdType m_cmd;
    protected int   m_cid;

    Server_Command (Server_CmdType cmd, int cid) {
        m_cmd = cmd;
        m_cid = cid;
    }

    Server_CmdType getServCmd () {
        return m_cmd;
    }

    int getMyCid () {
        return m_cid;
    }
}


text:
 Work in progress.. Please excuse us, the chat is comming soon.. :)

    Still some bugs chating on the server

    You can add issues to our GitHub repository:

        Team-Paradise

Live Chat

                {{#each this.info}}

{{this.sender}}

{{this.msg}}

                {{/each}}

        <input class="form-control input-lg" id="message"/>
        <button id="submitBtn" class="btn btn-primary">Send</button>


text:
{% assign MAX_SIZE = 3 %}
{% assign TAG_SCORE = 1 %}
{% assign CATEGORY_SCORE = 0.5 %}

{% assign score_list = "" | split: "" %}
{% assign post_index = 0 %}

{% for post in site.posts %}
  {% if post.url != page.url %}
    {% assign score = 0 %}

    {% for tag in post.tags %}
      {% if page.tags contains tag %}
        {% assign score = score | plus: TAG_SCORE %}
      {% endif %}
    {% endfor %}

    {% for category in post.categories %}
      {% if page.categories contains category %}
        {% assign score = score | plus: CATEGORY_SCORE %}
      {% endif %}
    {% endfor %}

    {% if score > 0 %}
      {% capture score_item %}{{ score }}:{{ post_index }}{% endcapture %}
      {% assign score_list = score_list | push: score_item %}
    {% endif %}

  {% endif %}
  {% assign post_index = post_index | plus: 1 %}
{% endfor %}

{% if score_list.size > 0 %}
  {% assign score_list = score_list | sort | reverse %}
  {% assign count = 0 %}

{{ site.data.label.post.relate_posts }}

    {% for score_item in score_list %}
      {% assign data = score_item | split: ":" %}
      {% assign index = data[1] | plus: 0 %}
      {% assign post = site.posts[index] %}

                {{ post.date | date: site.data.date_format.post }}
                {{ post.date | date_to_xmlschema }}

{{ post.title }}

              {% assign content = post.content %}
              {% include no-linenos.html %}

{{ content | markdownify | strip_html | truncate: 200 | replace: '&', '&' }}

      {% assign count = count | plus: 1 %}
      {% if count >= MAX_SIZE %}
        {% break %}
      {% endif %}
    {% endfor %}

{% endif %}


text:
/**
 * Graph common, shared and supertype layers.
 */
package org.gazzax.labs.solrdf.graph;


text:
package bammerbom.ultimatecore.sponge.modules.sign.api;

import bammerbom.ultimatecore.sponge.api.permission.Permission;
import bammerbom.ultimatecore.sponge.api.permission.PermissionLevel;
import org.spongepowered.api.text.Text;

public class SignPermissions {
    public static Permission UC_SIGN_COLOR_COLOR = Permission.create("uc.sign.color.[COLOR]", "sign", PermissionLevel.VIP, null, Text.of("Allows you to use a certain color on signs."));
    public static Permission UC_SIGN_STYLE_COLOR = Permission.create("uc.sign.style.[STYLE]", "sign", PermissionLevel.VIP, null, Text.of("Allows you to use a certain style on signs."));
}


text:
package fields;

public class Ja extends Ia {

	public int getField() {
		return field;
	}

	public void setField(int newvalue) {
		field = newvalue;
	}

}


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

namespace Grabacr07.KanColleWrapper.Models.Raw
{
	// ReSharper disable InconsistentNaming
	public class kcsapi_kdock_getship
	{
		public int api_id { get; set; }
		public int api_ship_id { get; set; }
		public kcsapi_kdock[] api_kdock { get; set; }
		public kcsapi_ship2 api_ship { get; set; }
		public kcsapi_slotitem[] api_slotitem { get; set; }
	}
	// ReSharper restore InconsistentNaming
}


text:
package com.camunda.consulting.jsfSimpleTasklist;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

@ManagedBean
@ViewScoped
public class TaskBean {
  private String id;

  public String getId() {
    return id;
  }

  public void setId(String id) {
    this.id = id;
  }

}


text:
package sun.net;

import java.net.InetAddress;
import java.io.FileDescriptor;
import java.io.IOException;

/**
 * Defines static methods to be invoked prior to binding or connecting TCP sockets.
 */

public final class NetHooks {

    // Android-removed: No SDP support.
    // /**
    //  * A provider with hooks to allow sockets be converted prior to binding or
    //  * connecting a TCP socket.
    //  *
    //  * <p> Concrete implementations of this class should define a zero-argument
    //  * constructor and implement the abstract methods specified below.
    //  */
    //  public static abstract class Provider {
    //     /**
    //      * Initializes a new instance of this class.
    //      */
    //     protected Provider() {}
    //
    //    /**
    //      * Invoked prior to binding a TCP socket.
    //      */
    //     public abstract void implBeforeTcpBind(FileDescriptor fdObj,
    //                                            InetAddress address,
    //                                            int port)
    //         throws IOException;
    //
    //     /**
    //      * Invoked prior to connecting an unbound TCP socket.
    //      */
    //     public abstract void implBeforeTcpConnect(FileDescriptor fdObj,
    //                                              InetAddress address,
    //                                              int port)
    //         throws IOException;
    // }

    /**
     * For now, we load the SDP provider on Solaris. In the future this may
     * be changed to use the ServiceLoader facility to allow the deployment of
     * other providers.
     */
    // Android-removed: No SDP support
    // private static final Provider provider = new sun.net.sdp.SdpProvider();

    /**
     * Invoke prior to binding a TCP socket.
     */
    public static void beforeTcpBind(FileDescriptor fdObj,
                                     InetAddress address,
                                     int port)
        throws IOException
    {
        // Android-removed: No SDP support
        // provider.implBeforeTcpBind(fdObj, address, port);
    }

    /**
     * Invoke prior to connecting an unbound TCP socket.
     */
    public static void beforeTcpConnect(FileDescriptor fdObj,
                                        InetAddress address,
                                        int port)
        throws IOException
    {
        // Android-removed: No SDP support
        // provider.implBeforeTcpConnect(fdObj, address, port);
    }
}


text:
import React from 'react';
import ReactDOM from 'react-dom';
import SharedFileView from './components/shared-file-view/shared-file-view';
import SharedFileViewTip from './components/shared-file-view/shared-file-view-tip';
import VideoPlayer from './components/video-player';

import './css/video-file-view.css';

const { rawPath, err } = window.shared.pageOptions;

class SharedFileViewImage extends React.Component {
  render() {
    return <SharedFileView content={<FileContent />} />;
  }
}

class FileContent extends React.Component {
  render() {
    if (err) {
      return <SharedFileViewTip />;
    }

    const videoJsOptions = {
      autoplay: false,
      controls: true,
      preload: 'auto',
      sources: [{
        src: rawPath
      }]
    };
    return (

          <VideoPlayer { ...videoJsOptions } />

    );
  }
}

ReactDOM.render(
  <SharedFileViewImage />,
  document.getElementById('wrapper')
);


text:
'use strict'

// configurables
let maxDepth
let replace

const flatTypes = [String, Number, Boolean]

const isDefined = val => val !== null && val !== undefined

const isFlat = val => !isDefined(val) || ~flatTypes.indexOf(val.constructor)

/**
 * Truncates variables.
 * @param {Object} obj - The object to truncate.
 * @param {Object|Number} [options={}] - If a number, the maxDepth, otherwise configurable options.
 * @param {Number} [options.maxDepth=10] - The max depth to build.
 * @param {Object} [options.replace=] - What to replace the truncated reference to.
 * @param {Number} [curDepth=0] - The current depth (used for recursive requests).
 * @returns {Object} The truncated object.
 */
const truncate = (obj, options = {}, curDepth = 0) => {
  options = isNaN(options) ? options : { maxDepth: options }
  options.maxDepth = options.maxDepth || maxDepth
  options.replace = options.replace || replace

  if (curDepth < options.maxDepth) {
    const newDepth = curDepth + 1

    if (isFlat(obj)) {
      return obj
    } else if (Array.isArray(obj)) {
      const newArr = []
      obj.forEach(value => {
        if (isFlat(value)) {
          newArr.push(value)
        } else {
          newArr.push(truncate(value, options, newDepth))
        }
      })
      return newArr
    } else {
      const newObj = {}
      for (const key in obj) {
        if (isFlat(obj[key])) {
          newObj[key] = obj[key]
        } else {
          newObj[key] = truncate(obj[key], options, newDepth)
        }
      }
      return newObj
    }
  }

  return options.replace
}

/**
 * Configures globals and defaults.
 * @param {Object} [obj={}] - The configuration.
 * @param {Number} obj.maxDepth - The default and global maxDepth for future truncations.
 * @param {} obj.replace - The default and global replacement value.
 */
truncate.config = (obj = {}) => {
  maxDepth = obj.maxDepth || maxDepth
  replace = obj.replace || replace
}

/**
 * Allows you to reset the variables (mainly for testing).
 */
truncate.reset = () => {
  maxDepth = 10
  replace = undefined
}

truncate.reset()

module.exports = truncate


text:
layout: post
title: Young at Art Celebration 2019

featureImg: yaa-main-image.jpg

teaser: Join us for the Young at Art Celebration

homepage: true

unique-cta: true

mega-cta-img: young-at-art-2019.jpg
mega-cta-heading: Questions?
mega-cta-button-text: Contact us!
mega-cta-button-text-url: mailto:info@stlartworks.org
---
Thursday, May 2, 6:00 pm - 9:30 pm

Please join us for a fun night of celebration with a Pop art theme!

About this Event:
- Guests will enjoy cocktails and artistically inspired food stations.
- One-of-a-kind original works of art created by our teen apprentices and other unique items will be available for purchase in a silent auction. All proceeds support our nationally recognized, award-winning program.
- We're honored to welcome critically acclaimed St. Louis musician, educator, arranger, and music director, Lamar Harris, as our featured performer. Together, we celebrate the bright future our program and our young creatives!

TICKETS $95:
Includes cocktail reception, gourmet food stations, and complimentary valet parking

RESERVED TABLES $1,000:
All of the above, plus premier reserved seating for 10

SPONSOR $2,500+:
All of the above, plus name listed on event promotions and recognition during the event

For Tickets:
Click Here to Purchase
or Call St. Louis ArtWorks 314-899-9734

Where: St. Louis ArtWorks, 5959 Delmar Blvd., St. Louis, MO 63112


text:
package com.wms.opensource.shopfast.task;

import com.shopify.api.resources.Product;
import com.wms.opensource.shopfast.R;
import com.wms.opensource.shopfast.cache.JsonCache;
import com.wms.opensource.shopfast.cache.ProductCache;
import com.wms.opensource.shopfast.handler.HandlerMessage;
import com.wms.opensource.shopfast.shopify.HTMLBodyProcessor;
import com.wms.opensource.shopfast.shopify.JSONProcessor;
import com.wms.opensource.shopfast.shopify.PersistFileNameProvider;
import com.wms.opensource.shopfast.shopify.ShopifyUtil;
import com.wms.opensource.shopfast.util.FileUtil;
import com.wms.opensource.shopfast.util.MessageUtil;
import com.wms.opensource.shopfast.util.StorageUtil;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.view.View;
import android.widget.ProgressBar;

public class LoadProductDetailsTask extends AsyncTask<Integer, Void, Void> {

	private Context context = null;
	private Handler handler = null;
	private ProgressBar progressBar = null;

	private Product product = null;

	public LoadProductDetailsTask(Context context, Handler handler, ProgressBar progressBar) {
		this.context = context;
		this.handler = handler;
		this.progressBar = progressBar;
	}

	protected void onPreExecute() {
		progressBar.setVisibility(View.VISIBLE);
    }

	protected Void doInBackground(Integer... params) { // params[0] is the product ID
		product = ShopifyUtil.getProductByID(context, params[0]);
		String bodyHtml = product.getBodyHtml();
		String plainBody = HTMLBodyProcessor.convertToPlainText(bodyHtml);
		product.setBodyHtml(plainBody);
		return null;
	}

    protected void onPostExecute(Void result) {
    	progressBar.setVisibility(View.INVISIBLE);

		ProductCache.putProduct(product.getId(), product);
    	String productJSONString = JSONProcessor.convertProductDetailsToJSON(product);
		JsonCache.putProductJson(product.getId(), productJSONString);
		FileUtil.writeStringToFile(productJSONString, StorageUtil.getTempDirectory(context), PersistFileNameProvider.getProductDetailsFileName(product.getId()),
				context.getString(R.string.charSetName));

		MessageUtil.sendHandlerMessage(handler, HandlerMessage.STORE_PRODUCT_DETAILS_LOADED);
    }

    public Product getProduct() {
    	return product;
    }

}


text:
#ifndef PNGPP_REQUIRE_COLOR_SPACE_HPP_INCLUDED
#define PNGPP_REQUIRE_COLOR_SPACE_HPP_INCLUDED

#include "error.hpp"
#include "rgb_pixel.hpp"
#include "rgba_pixel.hpp"
#include "gray_pixel.hpp"
#include "ga_pixel.hpp"
#include "index_pixel.hpp"
#include "io_base.hpp"

namespace png
{

    namespace detail
    {

        template< typename pixel >
        struct wrong_color_space
        {
            inline static char const* error_msg();
        };

        template<> inline char const*
        wrong_color_space< rgb_pixel >::error_msg()
        {
            return "8-bit RGB color space required";
        }

        template<> inline char const*
        wrong_color_space< rgb_pixel_16 >::error_msg()
        {
            return "16-bit RGB color space required";
        }

        template<> inline char const*
        wrong_color_space< rgba_pixel >::error_msg()
        {
            return "8-bit RGBA color space required";
        }

        template<> inline char const*
        wrong_color_space< rgba_pixel_16 >::error_msg()
        {
            return "16-bit RGBA color space required";
        }

        template<> inline char const*
        wrong_color_space< gray_pixel >::error_msg()
        {
            return "8-bit Grayscale color space required";
        }

        template<> inline char const*
        wrong_color_space< gray_pixel_1 >::error_msg()
        {
            return "1-bit Grayscale color space required";
        }

        template<> inline char const*
        wrong_color_space< gray_pixel_2 >::error_msg()
        {
            return "2-bit Grayscale color space required";
        }

        template<> inline char const*
        wrong_color_space< gray_pixel_4 >::error_msg()
        {
            return "4-bit Grayscale color space required";
        }

        template<> inline char const*
        wrong_color_space< gray_pixel_16 >::error_msg()
        {
            return "16-bit Grayscale color space required";
        }

        template<> inline char const*
        wrong_color_space< ga_pixel >::error_msg()
        {
            return "8-bit Gray+Alpha color space required";
        }

        template<> inline char const*
        wrong_color_space< ga_pixel_16 >::error_msg()
        {
            return "16-bit Gray+Alpha color space required";
        }

        template<> inline char const*
        wrong_color_space< index_pixel >::error_msg()
        {
            return "8-bit Colormap color space required";
        }

        template<> inline char const*
        wrong_color_space< index_pixel_1 >::error_msg()
        {
            return "1-bit Colormap color space required";
        }

        template<> inline char const*
        wrong_color_space< index_pixel_2 >::error_msg()
        {
            return "2-bit Colormap color space required";
        }

        template<> inline char const*
        wrong_color_space< index_pixel_4 >::error_msg()
        {
            return "4-bit Colormap color space required";
        }

    } // namespace detail

    /**
     * \brief IO transformation class template.  Enforces image color space.
     *
     * This IO transformation class template used to enforce source image
     * color space.
     *
     * \see image, image::read
     */
    template< typename pixel >
    struct require_color_space
    {
        typedef pixel_traits< pixel > traits;

        void operator()(io_base& io) const
        {
            if (io.get_color_type() != traits::get_color_type()
                || io.get_bit_depth() != traits::get_bit_depth())
            {
                throw error(detail::wrong_color_space< pixel >::error_msg());
            }
        }
    };

} // namespace png

#endif // PNGPP_REQUIRE_COLOR_SPACE_HPP_INCLUDED


text:
static DDLogLevel ddLogLevel = DDLogLevelDebug;

static NSOperationQueue *queue = nil;

@implementation HBTDatabaseManager

+ (NSOperationQueue *)operationQueue {
    if (!queue) {
        queue = [[NSOperationQueue alloc] init];
        queue.maxConcurrentOperationCount = 10;
    }
    return queue;
}

#pragma mark - Currency
+ (void)loadCurrencies:(MRSaveCompletionHandler)completion {
    // load currencies from file and put them into db.
    // I want like this, ok :3
    [[HBTAPIClient sharedAPIClient] liveRatesWithSuccessBlock:^(id responseObject) {
        if (responseObject[@"error"]) {
            if (completion) {
                NSError *error = [NSError errorWithDomain:@"com.trader.network" code:42 userInfo:nil];
                completion(NO, error);
            }
        }
        else {
            NSDictionary *responseDictionary = (NSDictionary *)responseObject;

            NSString *source = responseDictionary[@"source"];
            NSArray *currencies =
            [[(NSDictionary *)responseDictionary[@"quotes"] allKeys] compactObjectsUsingBlock:^NSDictionary *(NSString *obj, NSUInteger idx) {
                NSString *result =
                [self targetFromConversion:obj withSource:source];
                return @{@"code":result, @"name":result};
            }];
            [Currency saveAllFromDictionaries:currencies completion:completion];
        }
    } errorBlock:^(NSError *error, NSString *errorDescription) {
        DDLogError(@"error is %@", error);
        if (completion) {
            completion(NO, error);
        }
    }];
}

#pragma mark - Helpers / Conversion
+ (NSString*) targetFromConversion:(NSString *)conversion withSource:(NSString *)source {
    NSString *pattern = [@"^" stringByAppendingString:source];
    return [conversion stringByReplacingOccurrencesOfStringPattern:pattern withString:@""];
}

+ (NSArray *) conversionsFromDictionary:(NSDictionary *)dictionary {
    NSDictionary * quotes = dictionary[@"quotes"];
    return
    [[quotes allKeys] mapObjectsUsingBlock:^NSDictionary *(NSString *obj, NSUInteger idx) {
        return @{
                 @"source" : dictionary[@"source"],
                 @"target" : [self targetFromConversion:obj withSource:dictionary[@"source"]],
                 @"quote" : quotes[obj],
                 @"timestamp" : dictionary[@"timestamp"]
                 };
    }];
}

#pragma mark - Conversion
+ (NSArray *)downloadsForConversions:(NSArray *)conversions withProgressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock withCompletion:(MRSaveCompletionHandler)completion {
    NSArray *operations = conversions;
    NSArray *requestOperations =
    [AFURLConnectionOperation batchOfRequestOperations:operations progressBlock:progressBlock completionBlock:^(NSArray *operations) {
        NSArray *responses =
        [operations compactObjectsUsingBlock:^NSDictionary *(AFURLConnectionOperation * obj, NSUInteger idx) {
            return ((NSDictionary *)[obj.responseData jsonObject]);
        }];

        [MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext) {
            for (NSDictionary *responseObject in responses) {
                if (responseObject[@"error"]) {
                    // do something :/
                    DDLogDebug(@"error %@", responseObject[@"error"]);
                }
                else {
                    NSDictionary *responseDictionary = (NSDictionary *)responseObject;
                    NSArray *conversions =
                    [self conversionsFromDictionary:responseDictionary];
                    for (NSDictionary * conversion in conversions) {
                        [Conversion updateOrCreateWithDictionary:conversion inContext:localContext];
                    }
                }
            }
        } completion:completion];
    }];

    return requestOperations;
}

+ (void)loadConversionsOperations:(NSArray *)conversions withProgressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock withCompletion:(MRSaveCompletionHandler)completion {
    NSArray *requestOperations = [self downloadsForConversions:conversions withProgressBlock:progressBlock withCompletion:completion];

    [[self operationQueue] addOperations:requestOperations waitUntilFinished:NO];
}

+ (void)loadFavoritedConversionsWithProgressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock withCompletion:(MRSaveCompletionHandler)completion {
    NSArray *operations =
    [[Conversion sourcesAndTargets] compactObjectsUsingBlock:^AFURLConnectionOperation *(NSDictionary *obj, NSUInteger idx) {
        return [[HBTAPIClient sharedAPIClient] liveOperationForSource:obj[@"source"] withCurrencies:obj[@"currencies"]];
    }];

    NSArray *requestOperations = [self downloadsForConversions:operations withProgressBlock:progressBlock withCompletion:completion];

    DDLogDebug(@"requests: %@",requestOperations);
    [[self operationQueue] addOperations:requestOperations waitUntilFinished:NO];
}

+ (void)loadAllConversionsWithProgressBlock:(void (^)(NSUInteger, NSUInteger))progressBlock withCompletion:(MRSaveCompletionHandler)completion {
    NSArray *allCurrenciesCodes = [[Currency MR_findAll] valueForKey:@"code"];
    NSArray *operations =
    [allCurrenciesCodes compactObjectsUsingBlock:^AFURLConnectionOperation *(NSString *obj, NSUInteger idx) {
        return [[HBTAPIClient sharedAPIClient] liveOperationForSource:obj withCurrencies:nil];
    }];

    NSArray * requestOperations = [self downloadsForConversions:operations withProgressBlock:progressBlock withCompletion:completion];

    [[self operationQueue] addOperations:requestOperations waitUntilFinished:NO];
}

@end


text:
'use strict';

import triggerTab from './triggerTab.js';

/**
 * Кнопки вперед/назад
 */
export function bindSwitchers() {
  const self = this;
  const options = self.options;
  let stopIndex = self.counterElements - 1;

  if (self.$next) {
    $(document).on('datatabs:update', function(event, uuid) {
      const mainId = self.$element.get(0).dataTabs.uuid;
      if (uuid == mainId) {
        let nextStatus = getStatusNext(self, stopIndex);

        if (nextStatus.isNext) {
          self.$next.removeClass(options.classes.disabledSwitcher);
        }else{
          self.$next.addClass(options.classes.disabledSwitcher);
        }
      }
    });

    self.$next.on(options.switchersEvent, function(event) {
      event.preventDefault();
      let nextStatus = getStatusNext(self, stopIndex);

      if (nextStatus.isNext) {
        triggerTab(self, nextStatus.next);
      }
    });
  }

  if (self.$prev) {
    $(document).on('datatabs:update', function(event, uuid) {
      const mainId = self.$element.get(0).dataTabs.uuid;
      if (uuid == mainId) {
        let prevStatus = getStatusPrev(self, stopIndex);

        if (prevStatus.isPrev) {
          self.$prev.removeClass(options.classes.disabledSwitcher);
        }else{
          self.$prev.addClass(options.classes.disabledSwitcher);
        }
      }
    });

    self.$prev.on(options.switchersEvent, function(event) {
      event.preventDefault();
      let prevStatus = getStatusPrev(self, stopIndex);

      if (prevStatus.isPrev) {
        triggerTab(self, prevStatus.prev);
      }
    });
  }
}

function getStatusNext(self, stopIndex) {
  let next = self.states.activeIndex + 1;
  let isNext = true; // разрешен следующий?
  if (next > stopIndex) {
    if(self.options.loop){
      next = 0;
    }else{
      isNext = false;
    }
  };

  return {next,isNext}
}

function getStatusPrev(self, stopIndex) {
  let prev = self.states.activeIndex - 1;
  let isPrev = true; // разрешен предыдущий?
  if (prev < 0) {
    if(self.options.loop){
      prev = stopIndex;
    }else{
      isPrev = false;
    }
  };

  return {prev,isPrev}
}
/**
 * Отслеживаем переключение
 */
export function bindTriggers() {
  const self = this;
  const options = self.options;

  self.$anchors.on(options.event, function(event) {
    if (options.prevent) {
      event.preventDefault();
    }

    const anchor = $(this).get(0);

    triggerTab(self, anchor.dataTabs.myIndex)

  });
}

/**
 * Закрывать контент при клике на поле вне табов?
 */
export function hideOnClosest() {
  const self = this;
  if (!self.options.hideOnClosest) {
    return;
  }

  $(document).on('click', function(event) {
    const $parent = $(event.target).closest( self.$element );
    const isClose = $parent.length == 0;

    if (isClose) {
      self.closeAllTabs();
    }
  });
}

/**
 * Закрыть все вкладки
 */
export function closeAllTabs() {
  const self = this;

  const $parent = self.$element;
  const isCloseOnJquery = (self.options.useJqMethods && self.options.jqMethodClose);
  const closeAll = self.options.useToggle;

  const activeTab = self.options.classes.activeTab;
  const closeTab = self.options.classes.closeTab;
  const activeButton = self.options.classes.activeButton;
  const closeButton = self.options.classes.closeButton;

  // если можно скрывать активный таб то скрываем все, иначе все кроме активного
  let $targets = (closeAll) ? self.$targets : self.$targets.not( `.${activeTab}` );
  let $anchors = (closeAll) ? self.$anchors : self.$anchors.not( `.${activeButton}` );

  if (isCloseOnJquery) {
    $targets[self.options.jqMethodClose]();
  }

  $anchors.removeClass( activeButton ).addClass( closeButton );
  $targets.removeClass( activeTab ).addClass( closeTab );
}

/**
 * Ставим класс родительскому элементу при наведении
 */
export function bindHover() {
  const self = this;
  const options = self.options;
  const $parentTabs = self.$element;

  $parentTabs.hover((event) => {
    $parentTabs.addClass(options.classes.hover);
    options.onMouseover(event, self);
  }, (event) => {
    $parentTabs.removeClass(options.classes.hover);
    options.onMouseout(event, self);

    if (self.options.hideOnMouseout) {
      if (self.options.mouseoutTimeOut) {
        setTimeout(function () {
          if (!self.$element.hasClass(options.classes.hover)) {
            self.closeAllTabs();
          }
        }, self.options.mouseoutTimeOut)
      }else{
        self.closeAllTabs();
      }
    }
  });

}


text:
var passport = require('passport');

var config = require('../config');

function _401(str) {
  var err = new Error(str ? str.message || str : 'No message');
  err.status = 401;
  return err;
}

function local(req, res, next) {
  return function (err, user, message) {
    // message will only be set if passport strategy has encountered login
    // error (not a coding error).
    if (message)
      err = _401(message);

    if(err)
      return next(err);

    req.login(user, function (err) {
      if (err) return next(err);

      user = user.toObject();
      delete user.local;

      res.status(200);

      res.format({
        html: function() {
          res.redirect(req.session.lastPath || '/');
        },
        json: function () {
          if(req.session.lastPath) res.set('Location', req.session.lastPath);

          res.json(user);
        }
      });
    });
  };
}

function social(req, res, next) {
  return function (err, user, message) {
    function respond(err, user) {

      if(err)
        err = _.pick(err, 'status', 'message');

      if(req.session.loginWindow) {

        res.status(err ? err.status || 500 : 200);

        _.extend(res.locals, {
          error: err,
          user: user,
          newUser: req.session.newUser,
          redirect: req.session.lastPath
        });

        res.render('social-callback-script');
      } else {
        res.redirect(req.session.lastPath || '/');
      }

      delete req.session.lastPath;
      delete req.session.loginWindow;
    }

    // message will only be set if passport strategy has encountered login
    // error (not a coding error).
    if (message)
      err = _401(message);

    if (err)
      return respond(err);

    // NOTE: passport does not seem to return an error if permission's are not granted, but user === false
    if(!user) {
      if(!req.session.newUser) {
        err = new Error(config.messages.externalLoginFailed);
        err.status = 400;
      }

      return respond(err);
    }

    req.login(user, function (err) {
      respond(err, _.omit(user.toObject(), passport.providers));
    });
  };
}

var mw = {
  local: function (req, res, next) {
    passport.authenticate('local', local(req, res, next))(req, res, next);
  },

  logout: function(req, res, next) {
    req.logout();
    res.status(200);
    res.locals.ok = true;
    next();
  }
};

// TODO place this in server/passport.js instead... it is currently placed
// here because of warepot's loader sequence (server/passport.js needs to be
// loaded after (User) model.
passport.providers = [];

_.each(config.providers, function(strategyConfig, key) {
  passport.providers.push(key);

  mw[key] = {
    login: function(req, res, next) {
      delete req.session.newUser;
      req.session.loginWindow = !!req.query.loginWindow;
      passport.authenticate(key, { scope: strategyConfig.scope || config.scope })(req,res,next);
    },
    callback: function (req, res, next) {
      passport.authenticate(key, social(req, res, next))(req, res, next);
    },
    verify: function(req, res, next) {
      req.session.verifying = true;
      passport.authenticate(key)(req, res, next);
    }
  };
});

module.exports = mw;


text:
import os
import IPython.core.magic as ipym

@ipym.magics_class
class ClangppMagics(ipym.Magics):
    @ipym.cell_magic
    def clang(self, line, cell=None):
        """Compile, execute C++ code with clang, and return the standard output."""
        prep = os.path.abspath(os.getcwd())
        # Define the source and executable filenames.
        source_filename  = prep + '/temp.cpp'
        program_filename = prep + '/temp.exe'
        # Write the code contained in the cell to the C++ file.
        with open(source_filename, 'w') as f:
            f.write(cell)
        # Compile the C++ code into an executable.
        compile = self.shell.getoutput(
                "clang++ -std=c++1z -O2 -Wall -pedantic -pthread {0:s} -o {1:s}".format(
                source_filename, program_filename))
        # Execute the executable and return the output.
        output = self.shell.getoutput(program_filename)
        return output

if __name__ == '__main__':
    from IPython import get_ipython
    get_ipython().register_magics(ClangppMagics)


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Acacia valida Tindale & Kodela

### Remarks
null


text:
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.firebase.samples.apps.mlkit.java.barcodescanning;

import android.graphics.Bitmap;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.util.Log;

import com.google.android.gms.tasks.Task;
import com.google.firebase.ml.vision.FirebaseVision;
import com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode;
import com.google.firebase.ml.vision.barcode.FirebaseVisionBarcodeDetector;
import com.google.firebase.ml.vision.common.FirebaseVisionImage;
import com.google.firebase.samples.apps.mlkit.common.CameraImageGraphic;
import com.google.firebase.samples.apps.mlkit.common.FrameMetadata;
import com.google.firebase.samples.apps.mlkit.common.GraphicOverlay;
import com.google.firebase.samples.apps.mlkit.java.VisionProcessorBase;

import java.io.IOException;
import java.util.List;

/**
 * Barcode Detector Demo.
 */
public class BarcodeScanningProcessor extends VisionProcessorBase<List<FirebaseVisionBarcode>> {

    private static final String TAG = "BarcodeScanProc";

    private final FirebaseVisionBarcodeDetector detector;

    public BarcodeScanningProcessor() {
        // Note that if you know which format of barcode your app is dealing with, detection will be
        // faster to specify the supported barcode formats one by one, e.g.
        // new FirebaseVisionBarcodeDetectorOptions.Builder()
        //     .setBarcodeFormats(FirebaseVisionBarcode.FORMAT_QR_CODE)
        //     .build();
        detector = FirebaseVision.getInstance().getVisionBarcodeDetector();
    }

    @Override
    public void stop() {
        try {
            detector.close();
        } catch (IOException e) {
            Log.e(TAG, "Exception thrown while trying to close Barcode Detector: " + e);
        }
    }

    @Override
    protected Task<List<FirebaseVisionBarcode>> detectInImage(FirebaseVisionImage image) {
        return detector.detectInImage(image);
    }

    @Override
    protected void onSuccess(
            @Nullable Bitmap originalCameraImage,
            @NonNull List<FirebaseVisionBarcode> barcodes,
            @NonNull FrameMetadata frameMetadata,
            @NonNull GraphicOverlay graphicOverlay) {
        graphicOverlay.clear();
        if (originalCameraImage != null) {
            CameraImageGraphic imageGraphic = new CameraImageGraphic(graphicOverlay, originalCameraImage);
            graphicOverlay.add(imageGraphic);
        }
        for (int i = 0; i < barcodes.size(); ++i) {
            FirebaseVisionBarcode barcode = barcodes.get(i);
            BarcodeGraphic barcodeGraphic = new BarcodeGraphic(graphicOverlay, barcode);
            graphicOverlay.add(barcodeGraphic);
        }
        graphicOverlay.postInvalidate();
    }

    @Override
    protected void onFailure(@NonNull Exception e) {
        Log.e(TAG, "Barcode detection failed " + e);
    }
}


text:
package org.apache.druid.query.search;

public abstract class SearchQueryDecisionHelper
{
  private final double bitmapIntersectCost;

  protected SearchQueryDecisionHelper(final double bitmapIntersectCost)
  {
    this.bitmapIntersectCost = bitmapIntersectCost;
  }

  public double getBitmapIntersectCost()
  {
    return bitmapIntersectCost;
  }
}