text:
import social = require('../../interfaces/social');
import ui_constants = require('../../interfaces/ui');
import net = require('../../../../third_party/uproxy-lib/net/net.types');
import user_interface = require('../scripts/ui');

var ui = ui_context.ui;
var core = ui_context.core;
var model = ui_context.model;

Polymer({
  ready: function() {
    // Expose global ui object and UI module in this context. This allows the
    // hidden? watch for the get/give toggle to actually update.
    this.ui = ui;
    this.ui_constants = ui_constants;
    this.GettingState = social.GettingState;
    this.model = model;
  },
  start: function() {
    if (!this.instance.isOnline) {
      this.ui.toastMessage = ui.i18n_t("FRIEND_OFFLINE", { name: this.user.name });
      return;
    }

    ui.startGettingFromInstance(this.instance.instanceId).catch((e: Error) => {
      console.error('could not get access: ' + e.message);
    });
  },
  stop: function() {
    ui.stopUsingProxy();
    ui.stopGettingFromInstance(this.instance.instanceId);
  }
});


text:
package sc.iview.commands.demo.basic;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import graphics.scenery.attribute.material.Material;
import net.imagej.mesh.Mesh;

import net.imagej.mesh.io.stl.STLMeshIO;
import org.joml.Vector3f;
import org.scijava.command.Command;
import org.scijava.command.CommandService;
import org.scijava.io.IOService;
import org.scijava.log.LogService;
import org.scijava.plugin.Menu;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;

import sc.iview.SciView;

import graphics.scenery.Node;
import sc.iview.commands.demo.ResourceLoader;

import static sc.iview.commands.MenuWeights.*;

/**
 * A demo of meshes.
 *
 * @author Kyle Harrington
 * @author Curtis Rueden
 */
@Plugin(type = Command.class, label = "Mesh Demo", menuRoot = "SciView", //
        menu = { @Menu(label = "Demo", weight = DEMO), //
                 @Menu(label = "Basic", weight = DEMO_BASIC), //
                 @Menu(label = "Mesh", weight = DEMO_BASIC_MESH) })
public class MeshDemo implements Command {

    @Parameter
    private IOService io;

    @Parameter
    private LogService log;

    @Parameter
    private SciView sciView;

    @Parameter
    private CommandService commandService;

    @Override
    public void run() {
        final Mesh m;
        try {
            File meshFile = ResourceLoader.createFile( getClass(), "/WieseRobert_simplified_Cip1.stl" );
            STLMeshIO stlReader = new STLMeshIO();
            m = stlReader.open(meshFile.getAbsolutePath());
        }
        catch (IOException exc) {
            log.error( exc );
            return;
        }

        Node msh = sciView.addMesh( m );
        msh.setName( "Mesh Demo" );

        //msh.fitInto( 15.0f, true );

        msh.ifMaterial( mat -> {
            mat.setAmbient( new Vector3f( 1.0f, 0.0f, 0.0f ) );
            mat.setDiffuse( new Vector3f( 0.8f, 0.5f, 0.4f ) );
            mat.setSpecular( new Vector3f( 1.0f, 1.0f, 1.0f ) );
            return null;
        });

        msh.ifGeometry( geom -> { geom.setDirty(true); return null; });
        msh.ifSpatial( spatial -> { spatial.setNeedsUpdate(true); return null; });

        sciView.getFloor().ifSpatial(spatial -> {
            spatial.setPosition(new Vector3f(0, -25, 0));
            return null;
        });

        sciView.setActiveNode(msh);
        sciView.centerOnNode( sciView.getActiveNode() );
    }

    public static void main(String... args) throws Exception {
        SciView sv = SciView.create();

        CommandService command = sv.getScijavaContext().getService(CommandService.class);

        HashMap<String, Object> argmap = new HashMap<>();

        command.run(MeshDemo.class, true, argmap);
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace WingEngine
{
	SceneSystem::SceneSystem()
		:mCreate(false)
	{

	}

	SceneSystem::~SceneSystem()
	{

	}

	bool SceneSystem::create()
	{
		if (mCreate)
		{
			WING_LOG_WARN("SceneSystem has been create");
			return false;
		}
		mCreate = true;

		mRootNode = WING_NEW Node();
		mRootNode->setName(ROOTNODE);

		return true;
	}

	void SceneSystem::destroy()
	{
		WING_DELETE(mRootNode);
	}

	void SceneSystem::addNode(std::string name, SmartPtr<Node> node)
	{
		if (findNode(name) == nullptr)
		{
			mNode[name] = node;
		}
		else
		{
			WING_LOG_WARN("%s is exit",name.c_str());
		}
	}

	SmartPtr<Node> SceneSystem::findNode(std::string name)
	{
		std::map<std::string, SmartPtr<Node>>::iterator iter = mNode.find(name);
		if (iter == mNode.end())
			return nullptr;

		return iter->second;
	}

	void SceneSystem::removeNode(std::string name)
	{
		std::map<std::string, SmartPtr<Node>>::iterator iter = mNode.find(name);
		if (iter != mNode.end())
		{
			mNode.erase(iter);
		}
	}

	void SceneSystem::addNodeToRenderer()
	{
		std::map<std::string, SmartPtr<Node>>::iterator beg = mNode.begin();
		for (;beg != mNode.end();beg++)
		{
			Node* node = beg->second;
			if (node->getRenderType() != RenderTypeNULL)
			{
				RendererSystem::getInstance()->addRenderable((Renderable*)node);
			}

		}
	}
}


text:
package org.dozer.factory;

import java.lang.reflect.Method;

import org.dozer.BeanFactory;
import org.dozer.util.MappingUtils;
import org.dozer.util.ReflectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Public custom bean factory that can be used by application code when mapping JAXB data objects
 *
 * @author Vincent Jassogne
 * @author Jose Barragan
 */
public class JAXBBeanFactory implements BeanFactory {

    private static final char INNER_CLASS_DELIMITER = '$';

    private final Logger log = LoggerFactory.getLogger(JAXBBeanFactory.class);

    /**
     * Create a bean implementation of a JAXB interface.
     *
     * @param srcObj      The source object
     * @param srcObjClass The source object class
     * @param beanId      the name of the destination interface class
     * @return A implementation of the destination interface
     */
    @Override
    public Object createBean(Object srcObj, Class<?> srcObjClass, String beanId) {
        log.debug("createBean(Object, Class, String) - start [{}]", beanId);

        int indexOf = beanId.indexOf(INNER_CLASS_DELIMITER);
        while (indexOf > 0) {
            beanId = beanId.substring(0, indexOf) + beanId.substring(indexOf + 1);
            log.debug("createBean(Object, Class, String) - HAS BEEN CHANGED TO  [{}]", beanId);
            indexOf = beanId.indexOf(INNER_CLASS_DELIMITER);
        }
        Object result;

        Class<?> objectFactory = MappingUtils.loadClass(beanId.substring(0, beanId.lastIndexOf(".")) + ".ObjectFactory");
        Object factory = ReflectionUtils.newInstance(objectFactory);
        Method method = null;
        try {
            method = ReflectionUtils.getMethod(objectFactory, "create" + beanId.substring(beanId.lastIndexOf(".") + 1), new Class[]{});
        } catch (NoSuchMethodException e) {
            MappingUtils.throwMappingException(e);
        }
        Object returnObject = ReflectionUtils.invoke(method, factory, new Object[]{});
        log.debug("createBean(Object, Class, String) - end [{}]", returnObject.getClass().getName());
        result = returnObject;

        return result;
    }

}


text:
#ifndef _ShaderExNormalMapLighting_
#define _ShaderExNormalMapLighting_

#include "OgreShaderPrerequisites.h"
#ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS
#include "OgreShaderParameter.h"
#include "OgreShaderSubRenderState.h"
#include "OgreVector4.h"
#include "OgreLight.h"
#include "OgreCommon.h"

namespace Ogre {
namespace RTShader {

/** \addtogroup Core
*  @{
*/
/** \addtogroup RTShader
*  @{
*/

#define SGX_LIB_NORMALMAPLIGHTING					"SGXLib_NormalMapLighting"
#define SGX_FUNC_CONSTRUCT_TBNMATRIX				"SGX_ConstructTBNMatrix"
#define SGX_FUNC_TRANSFORMNORMAL					"SGX_TransformNormal"
#define SGX_FUNC_TRANSFORMPOSITION					"SGX_TransformPosition"
#define SGX_FUNC_FETCHNORMAL						"SGX_FetchNormal"
#define SGX_FUNC_LIGHT_DIRECTIONAL_DIFFUSE			"SGX_Light_Directional_Diffuse"
#define SGX_FUNC_LIGHT_DIRECTIONAL_DIFFUSESPECULAR	"SGX_Light_Directional_DiffuseSpecular"
#define SGX_FUNC_LIGHT_POINT_DIFFUSE				"SGX_Light_Point_Diffuse"
#define SGX_FUNC_LIGHT_POINT_DIFFUSESPECULAR		"SGX_Light_Point_DiffuseSpecular"
#define SGX_FUNC_LIGHT_SPOT_DIFFUSE					"SGX_Light_Spot_Diffuse"
#define SGX_FUNC_LIGHT_SPOT_DIFFUSESPECULAR			"SGX_Light_Spot_DiffuseSpecular"

/** Normal Map Lighting extension sub render state implementation.
Derives from SubRenderState class.
*/
class _OgreRTSSExport NormalMapLighting : public SubRenderState
{

// Interface.
public:
	/** Class default constructor */
	NormalMapLighting();

	/**
	@see SubRenderState::getType.
	*/
	virtual const String& getType() const;

	/**
	@see SubRenderState::getType.
	*/
	virtual int getExecutionOrder() const;

	/**
	@see SubRenderState::updateGpuProgramsParams.
	*/
	virtual void updateGpuProgramsParams(Renderable* rend, Pass* pass, const AutoParamDataSource* source, const LightList* pLightList);

	/**
	@see SubRenderState::copyFrom.
	*/
	virtual void copyFrom(const SubRenderState& rhs);

	/**
	@see SubRenderState::preAddToRenderState.
	*/
	virtual bool preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass);

	/**
	Set the index of the input vertex shader texture coordinate set
	*/
	void setTexCoordIndex(unsigned int index) { mVSTexCoordSetIndex = index;}

	/**
	Return the index of the input vertex shader texture coordinate set.
	*/
	unsigned int getTexCoordIndex() const { return mVSTexCoordSetIndex; }

	// Type of this render state.
	static String Type;

	// Normal map space definition.
	enum NormalMapSpace
	{
		NMS_TANGENT,		// Normal map contains normal data in tangent space.
							// This is the default normal mapping behavior and it requires that the
							// target mesh will have valid tangents within its vertex data.

		NMS_OBJECT			// Normal map contains normal data in object local space.
							// This normal mapping technique has the advantages of better visualization results,
							// lack of artifacts that comes from texture mirroring usage, it doesn't requires tangent
							// and it also saves some instruction in the vertex shader stage.
							// The main drawback of using this kind of normal map is that the target object must be static
							// in terms of local space rotations and translations.
	};

	/**
	Set the normal map space.
	@param normalMapSpace The normal map space.
	*/
	void setNormalMapSpace(NormalMapSpace normalMapSpace) { mNormalMapSpace = normalMapSpace; }

	/** Return the normal map space. */
	NormalMapSpace getNormalMapSpace() const { return mNormalMapSpace; }

	/**
	Set the normal map texture name.
	*/
	void setNormalMapTextureName(const String& textureName) { mNormalMapTextureName = textureName; }

	/**
	Return the normal map texture name.
	*/
	const String& getNormalMapTextureName() const { return mNormalMapTextureName; }

	/**
	Set the normal map filtering attributes.
	@param minFilter The desired min filter.
	@param magFilter The desired mag filter.
	@param mipFilter The desired mip filter.
	*/
	void setNormalMapFiltering(const FilterOptions minFilter, const FilterOptions magFilter, const FilterOptions mipFilter)
	{ mNormalMapMinFilter = minFilter; mNormalMapMagFilter = magFilter; mNormalMapMipFilter = mipFilter; }

	/**
	Return the normal map filtering attributes.
	@param minFilter The desired min filter.
	@param magFilter The desired mag filter.
	@param mipFilter The desired mip filter.
	*/
	void getNormalMapFiltering(FilterOptions& minFilter, FilterOptions& magFilter, FilterOptions& mipFilter) const
	{ minFilter = mNormalMapMinFilter; magFilter = mNormalMapMagFilter ; mipFilter = mNormalMapMipFilter; }

	/** Setup the normal map anisotropy value.
	@param anisotropy The anisotropy value.
	*/
	void setNormalMapAnisotropy(unsigned int anisotropy) { mNormalMapAnisotropy = anisotropy; }

	/** Return the normal map anisotropy value. */
	unsigned int getNormalMapAnisotropy() const { return mNormalMapAnisotropy; }

	/** Setup the normal map map mip bias value.
	@param mipBias The map mip bias value.
	*/
	void setNormalMapMipBias(Real mipBias) { mNormalMapMipBias = mipBias; }

	/** Return the normal map mip bias value. */
	Real getNormalMapMipBias() const { return mNormalMapMipBias; }

// Protected types:
protected:

	// Per light parameters.
	struct _OgreRTSSExport LightParams
	{
		// Light type.
		Light::LightTypes mType;
		// Light position.
		UniformParameterPtr mPosition;
		// Vertex shader output vertex position to light position direction (texture space).
		ParameterPtr mVSOutToLightDir;
		// Pixel shader input vertex position to light position direction (texture space).
		ParameterPtr mPSInToLightDir;
		// Light direction.
		UniformParameterPtr mDirection;
		// Vertex shader output light direction (texture space).
		ParameterPtr mVSOutDirection;
		// Pixel shader input light direction (texture space).
		ParameterPtr mPSInDirection;
		// Attenuation parameters.
		UniformParameterPtr mAttenuatParams;
		// Spot light parameters.
		UniformParameterPtr mSpotParams;
		// Diffuse colour.
		UniformParameterPtr mDiffuseColour;
		// Specular colour.
		UniformParameterPtr mSpecularColour;

	};

	typedef vector<LightParams>::type LightParamsList;
	typedef LightParamsList::iterator LightParamsIterator;
	typedef LightParamsList::const_iterator LightParamsConstIterator;

// Protected methods
protected:

	/**
	Set the track per vertex colour type. Ambient, Diffuse, Specular and Emissive lighting components source
	can be the vertex colour component. To establish such a link one should provide the matching flags to this
	sub render state.
	*/
	void setTrackVertexColourType(TrackVertexColourType type) { mTrackVertexColourType = type; }

	/**
	Return the current track per vertex type.
	*/
	TrackVertexColourType getTrackVertexColourType() const { return mTrackVertexColourType; }

	/**
	Set the light count per light type that this sub render state will generate.
	@see ShaderGenerator::setLightCount.
	*/
	void setLightCount(const int lightCount[3]);

	/**
	Get the light count per light type that this sub render state will generate.
	@see ShaderGenerator::getLightCount.
	*/
	void getLightCount(int lightCount[3]) const;
	/**
	Set the specular component state. If set to true this sub render state will compute a specular
	lighting component in addition to the diffuse component.
	@param enable Pass true to enable specular component computation.
	*/
	void setSpecularEnable(bool enable) { mSpecularEnable = enable; }

	/**
	Get the specular component state.
	*/
	bool getSpecularEnable() const	  { return mSpecularEnable; }

	/**
	@see SubRenderState::resolveParameters.
	*/
	virtual bool resolveParameters(ProgramSet* programSet);

	/** Resolve global lighting parameters */
	bool resolveGlobalParameters(ProgramSet* programSet);

	/** Resolve per light parameters */
	bool resolvePerLightParameters(ProgramSet* programSet);

	/**
	@see SubRenderState::resolveDependencies.
	*/
	virtual bool resolveDependencies(ProgramSet* programSet);

	/**
	@see SubRenderState::addFunctionInvocations.
	*/
	virtual bool addFunctionInvocations(ProgramSet* programSet);

	/**
	Internal method that adds related vertex shader functions invocations.
	*/
	bool addVSInvocation(Function* vsMain, const int groupOrder, int& internalCounter);

	/**
	Internal method that adds per light illumination component functions invocations.
	*/
	bool addVSIlluminationInvocation(LightParams* curLightParams, Function* vsMain, const int groupOrder, int& internalCounter);

	/**
	Internal method that perform normal fetch invocation.
	*/
	bool addPSNormalFetchInvocation(Function* psMain, const int groupOrder, int& internalCounter);

	/**
	Internal method that adds global illumination component functions invocations.
	*/
	bool addPSGlobalIlluminationInvocation(Function* psMain, const int groupOrder, int& internalCounter);

	/**
	Internal method that adds per light illumination component functions invocations.
	*/
	bool addPSIlluminationInvocation(LightParams* curLightParams, Function* psMain, const int groupOrder, int& internalCounter);

	/**
	Internal method that adds the final colour assignments.
	*/
	bool addPSFinalAssignmentInvocation(Function* psMain, const int groupOrder, int& internalCounter);

// Attributes.
protected:
	// The normal map texture name.
	String mNormalMapTextureName;
	// Track per vertex colour type.
	TrackVertexColourType mTrackVertexColourType;
	// Specular component enabled/disabled.
	bool mSpecularEnable;
	// Light list.
	LightParamsList mLightParamsList;
	// Normal map texture sampler index.
	unsigned short mNormalMapSamplerIndex;
	// Vertex shader input texture coordinate set index.
	unsigned int mVSTexCoordSetIndex;
	// The normal map min filter.
	FilterOptions mNormalMapMinFilter;
	// The normal map mag filter.
	FilterOptions mNormalMapMagFilter;
	// The normal map mip filter.
	FilterOptions mNormalMapMipFilter;
	// The normal map max anisotropy value.
	unsigned int mNormalMapAnisotropy;
	// The normal map mip map bias.
	Real mNormalMapMipBias;
	// The normal map space.
	NormalMapSpace mNormalMapSpace;
	// World matrix parameter.
	UniformParameterPtr mWorldMatrix;
	// World matrix inverse rotation matrix parameter.
	UniformParameterPtr mWorldInvRotMatrix;
	// Camera position in world space parameter.
	UniformParameterPtr mCamPosWorldSpace;
	// Vertex shader input position parameter.
	ParameterPtr mVSInPosition;
	// Vertex shader world position parameter.
	ParameterPtr mVSWorldPosition;
	// Vertex shader output view vector (position in camera space) parameter.
	ParameterPtr mVSOutView;
	// Pixel shader input view position (position in camera space) parameter.
	ParameterPtr mPSInView;
	// Vertex shader input normal.
	ParameterPtr mVSInNormal;
	// Vertex shader input tangent.
	ParameterPtr mVSInTangent;
	// Vertex shader local TNB matrix.
	ParameterPtr mVSTBNMatrix;
	// Vertex shader local light direction.
	ParameterPtr mVSLocalDir;
	// Normal map texture sampler parameter.
	UniformParameterPtr mNormalMapSampler;
	// Pixel shader normal parameter.
	ParameterPtr mPSNormal;
	// Vertex shader input texture coordinates.
	ParameterPtr mVSInTexcoord;
	// Vertex shader output texture coordinates.
	ParameterPtr mVSOutTexcoord;
	// Pixel shader input texture coordinates.
	ParameterPtr mPSInTexcoord;
	// Pixel shader temporary diffuse calculation parameter.
	ParameterPtr mPSTempDiffuseColour;
	// Pixel shader temporary specular calculation parameter.
	ParameterPtr mPSTempSpecularColour;
	// Pixel shader input/local diffuse parameter.
	ParameterPtr mPSDiffuse;
	// Pixel shader input/local specular parameter.
	ParameterPtr mPSSpecular;
	// Pixel shader output diffuse parameter.
	ParameterPtr mPSOutDiffuse;
	// Pixel shader output specular parameter.
	ParameterPtr mPSOutSpecular;
	// Derived scene colour parameter.
	UniformParameterPtr mDerivedSceneColour;
	// Ambient light colour parameter.
	UniformParameterPtr mLightAmbientColour;
	// Derived ambient light colour parameter.
	UniformParameterPtr mDerivedAmbientLightColour;
	// Surface ambient colour parameter.
	UniformParameterPtr mSurfaceAmbientColour;
	// Surface diffuse colour parameter.
	UniformParameterPtr mSurfaceDiffuseColour;
	// Surface specular colour parameter.
	UniformParameterPtr mSurfaceSpecularColour;
	// Surface emissive colour parameter.
	UniformParameterPtr mSurfaceEmissiveColour;
	// Surface shininess parameter.
	UniformParameterPtr mSurfaceShininess;
	// Shared blank light.
	static Light msBlankLight;
};

/**
A factory that enables creation of NormalMapLighting instances.
@remarks Sub class of SubRenderStateFactory
*/
class _OgreRTSSExport NormalMapLightingFactory : public SubRenderStateFactory
{
public:

	/**
	@see SubRenderStateFactory::getType.
	*/
	virtual const String& getType() const;

	/**
	@see SubRenderStateFactory::createInstance.
	*/
	virtual SubRenderState* createInstance(ScriptCompiler* compiler, PropertyAbstractNode* prop, Pass* pass, SGScriptTranslator* translator);

	/**
	@see SubRenderStateFactory::writeInstance.
	*/
	virtual void writeInstance(MaterialSerializer* ser, SubRenderState* subRenderState, Pass* srcPass, Pass* dstPass);

protected:

	/**
	@see SubRenderStateFactory::createInstanceImpl.
	*/
	virtual SubRenderState* createInstanceImpl();

};

/** @} */
/** @} */

}
}

#endif
#endif


text:
class CefBrowserCToCpp
    : public CefCToCpp<CefBrowserCToCpp, CefBrowser, cef_browser_t> {
 public:
  CefBrowserCToCpp();

  // CefBrowser methods.
  CefRefPtr<CefBrowserHost> GetHost() OVERRIDE;
  bool CanGoBack() OVERRIDE;
  void GoBack() OVERRIDE;
  bool CanGoForward() OVERRIDE;
  void GoForward() OVERRIDE;
  bool IsLoading() OVERRIDE;
  void Reload() OVERRIDE;
  void ReloadIgnoreCache() OVERRIDE;
  void StopLoad() OVERRIDE;
  int GetIdentifier() OVERRIDE;
  bool IsSame(CefRefPtr<CefBrowser> that) OVERRIDE;
  bool IsPopup() OVERRIDE;
  bool HasDocument() OVERRIDE;
  CefRefPtr<CefFrame> GetMainFrame() OVERRIDE;
  CefRefPtr<CefFrame> GetFocusedFrame() OVERRIDE;
  CefRefPtr<CefFrame> GetFrame(int64 identifier) OVERRIDE;
  CefRefPtr<CefFrame> GetFrame(const CefString& name) OVERRIDE;
  size_t GetFrameCount() OVERRIDE;
  void GetFrameIdentifiers(std::vector<int64>& identifiers) OVERRIDE;
  void GetFrameNames(std::vector<CefString>& names) OVERRIDE;
  bool SendProcessMessage(CefProcessId target_process,
      CefRefPtr<CefProcessMessage> message) OVERRIDE;
};

#endif  // USING_CEF_SHARED
#endif  // CEF_LIBCEF_DLL_CTOCPP_BROWSER_CTOCPP_H_


text:
/**
* @projectDescription  CSS Utility Class.
*
* @version  1.0
*/

var CssUtils = {

	/**
	 * Create rule from arguments and return it as string.
	 *
	 * @alias createRule
	 * @alias CssUtils.createRule
	 * @param {String} elementSelector Rule definition - example: "#myDiv".
	 * @param {String} ruleDefinition Rule definition string - example "width:40px; color: #FFF;".
	 * @return {String} Constructed css rule
	 */
	createRule : function(elementSelector, ruleDefinition) {
		var ruleArray = new StringBuilder();
		ruleArray.append(elementSelector, "{", ruleDefinition, "}");
		return ruleArray.toString();
	},

	/**
	 * Insert rule into existing stylesheet defined by sheetTitle.
	 *
	 * @alias insertRule
	 * @alias CssUtils.insertRule
	 * @param {String, Array, Object} ruleDefinition Rule definition - example: "#myDiv {width:40px; color: #FFF;}".
	 * @param {String} sheetTitle Stylesheet title.
	 * @return {Boolean} inserted
	 */
	insertRule : function(ruleDefinition, sheetTitle) {
		var inserted = false;
		var multiple = !(typeof ruleDefiniton === "string");
		var styles = document.styleSheets;
		for ( var style = 0, stylesLength = styles.length; style < stylesLength; style++) {
			if (styles[style].title == sheetTitle) {
				if(multiple){
					for(var ruleIndex in ruleDefinition){
						syles[style].insertRule(ruleDefinition[ruleIndex]);
					}
				}
				else{
					syles[style].insertRule(ruleDefinition);
				}
				inserted = true;
			}
		}
		return inserted;
	},

	/**
	 * Deletes css rule defined by ruleSelector in stylesheet defined by sheetTitle.
	 *
	 * @alias deleteRule
	 * @alias CssUtils.deleteRule
	 * @param {String} ruleSelector Rule name.
	 * @param {String} sheetTitle Stylesheet title.
	 */
	deleteRule : function(ruleSelector, sheetTitle) {
		var styles = document.styleSheets;
		// search for styleSheet defined by title
		for ( var styleIndex = 0, stylesLength = styles.length; styleIndex < stylesLength; styleIndex++) {
			// if styleSheet exists, find and remove rule
			if (styles[styleIndex].title == sheetTitle) {
				var rules = syles[styleIndex].cssRules;
				for ( var ruleIndex = 0, rulesLength = rules.length; ruleIndex < rulesLength; ruleIndex++) {
					if (rules[ruleIndex].selectorText == ruleSelector) {
						syles[styleIndex].deleteRule(ruleIndex);
					}
				}
			}
		}
	},

	/**
	 * Create new stylesheet.
	 *
	 * @alias createStyleSheet
	 * @alias CssUtils.createStyleSheet
	 * @param {String} sheetTitle
	 * @param {String} cssRules String containing css rules.
	 * @param {Object} location Element to append stylesheet.
	 */
	createStyleSheet : function(sheetTitle, cssRules, location) {
		var styleSheet = document.createElement('style');
		if(cssRules){
			styleSheet.innerHTML = cssRules;
		}
		if(location){
			location.appendChild(styleSheet);
		}
		return styleSheet;
	}

};


text:
import json
import unittest
import unittest.mock as mock

import hunting.level.parser as parser
import hunting.resources.files as res_files
from hunting.constants import *
from hunting.level.map import LevelMap, LevelTile
from hunting.sim.ai.ais import TestMonster, DummyAI
from hunting.sim.entities import GameObject, Fighter
from hunting.sim.runner import run_level, run_turn

class TestRunner(unittest.TestCase):
    def test_speed_system(self):
        level = LevelMap()
        level.add_faction(None, {})
        level.add_object(GameObject('1', level.log, 0, 0, 'slow', fighter=Fighter(1, 1, 1, 1, 1, speed=30),
                                    ai=DummyAI()))
        level.add_object(GameObject('2', level.log, 0, 0, 'fast', fighter=Fighter(1, 1, 1, 1, 1), ai=DummyAI()))
        for _ in range(4):
            run_turn(level)
        start_events = [e[OBJ_ID] for e in level.log.events if e[EVENT_TYPE] == BEGIN_TURN_EVENT]
        self.assertEqual(['1', '1', '1', '2'], start_events)

    def test_ends_if_one_faction(self):
        level = LevelMap()
        level.add_faction('1', {})
        level.add_object(GameObject('1', level.log, 0, 0, 'test', faction='1'))
        run_level(level)

        self.assertTrue(len(level.log.events) == 0)

    @mock.patch('random.randint', return_value=75)
    def test_runs_test_combat(self, _):
        level = LevelMap()
        level.set_map([[LevelTile()], [LevelTile()]])
        for x in [0, 1]:
            o = GameObject(x, level.log, x, 0, 'test', faction=x, ai=TestMonster(level),
                           fighter=Fighter(1, 1, defense=0, power=1, xp=0, death_function=level.remove_object))
            level.add_faction(x, {})
            level.add_object(o)
        run_level(level)
        event_types = [e[EVENT_TYPE] for e in level.log.events]

        self.assertEqual([BEGIN_TURN_EVENT, ATTACK_EVENT, TAKE_DAMAGE_EVENT, OBJECT_DESTRUCTION_EVENT, END_TURN_EVENT],
                         event_types)

    # This is not a unit test! However I'm not sure where to put it. So here it is.
    @mock.patch('random.randint', return_value=75)
    def test_level_json(self, _):
        level = parser.parse_level(res_files.test_test_level_json)
        run_level(level)

        with open(res_files.test_test_level_log_json, 'r') as f:
            self.assertEqual(level.log.events, json.load(f))


text:
package uuid

import (
	"bytes"
	"crypto/rand"
	"encoding/hex"
	"fmt"
	"io"
	"strings"
)

// Array is a pass-by-value UUID that can be used as an effecient key in a map.
type Array [16]byte

// UUID converts uuid into a slice.
func (uuid Array) UUID() UUID {
	return uuid[:]
}

// String returns the string representation of uuid,
// xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.
func (uuid Array) String() string {
	return uuid.UUID().String()
}

// A UUID is a 128 bit (16 byte) Universal Unique IDentifier as defined in RFC
// 4122.
type UUID []byte

// A Version represents a UUIDs version.
type Version byte

// A Variant represents a UUIDs variant.
type Variant byte

// Constants returned by Variant.
const (
	Invalid   = Variant(iota) // Invalid UUID
	RFC4122                   // The variant specified in RFC4122
	Reserved                  // Reserved, NCS backward compatibility.
	Microsoft                 // Reserved, Microsoft Corporation backward compatibility.
	Future                    // Reserved for future definition.
)

var rander = rand.Reader // random function

// New returns a new random (version 4) UUID as a string.  It is a convenience
// function for NewRandom().String().
func New() string {
	return NewRandom().String()
}

// Parse decodes s into a UUID or returns nil.  Both the UUID form of
// xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx and
// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx are decoded.
func Parse(s string) UUID {
	if len(s) == 36+9 {
		if strings.ToLower(s[:9]) != "urn:uuid:" {
			return nil
		}
		s = s[9:]
	} else if len(s) != 36 {
		return nil
	}
	if s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-' {
		return nil
	}
	var uuid [16]byte
	for i, x := range [16]int{
		0, 2, 4, 6,
		9, 11,
		14, 16,
		19, 21,
		24, 26, 28, 30, 32, 34} {
		if v, ok := xtob(s[x:]); !ok {
			return nil
		} else {
			uuid[i] = v
		}
	}
	return uuid[:]
}

// Equal returns true if uuid1 and uuid2 are equal.
func Equal(uuid1, uuid2 UUID) bool {
	return bytes.Equal(uuid1, uuid2)
}

// Equal returns true if uuid1 and uuid2 are equal.
func (uuid UUID) Equal(uuid2 UUID) bool {
	return Equal(uuid, uuid2)
}

// Array returns an array representation of uuid that can be used as a map key.
// Array panics if uuid is not valid.
func (uuid UUID) Array() Array {
	if len(uuid) != 16 {
		panic("invalid uuid")
	}
	var a Array
	copy(a[:], uuid)
	return a
}

// String returns the string form of uuid, xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
// , or "" if uuid is invalid.
func (uuid UUID) String() string {
	if len(uuid) != 16 {
		return ""
	}
	var buf [36]byte
	encodeHex(buf[:], uuid)
	return string(buf[:])
}

// URN returns the RFC 2141 URN form of uuid,
// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx,  or "" if uuid is invalid.
func (uuid UUID) URN() string {
	if len(uuid) != 16 {
		return ""
	}
	var buf [36 + 9]byte
	copy(buf[:], "urn:uuid:")
	encodeHex(buf[9:], uuid)
	return string(buf[:])
}

func encodeHex(dst []byte, uuid UUID) {
	hex.Encode(dst[:], uuid[:4])
	dst[8] = '-'
	hex.Encode(dst[9:13], uuid[4:6])
	dst[13] = '-'
	hex.Encode(dst[14:18], uuid[6:8])
	dst[18] = '-'
	hex.Encode(dst[19:23], uuid[8:10])
	dst[23] = '-'
	hex.Encode(dst[24:], uuid[10:])
}

// Variant returns the variant encoded in uuid.  It returns Invalid if
// uuid is invalid.
func (uuid UUID) Variant() Variant {
	if len(uuid) != 16 {
		return Invalid
	}
	switch {
	case (uuid[8] & 0xc0) == 0x80:
		return RFC4122
	case (uuid[8] & 0xe0) == 0xc0:
		return Microsoft
	case (uuid[8] & 0xe0) == 0xe0:
		return Future
	default:
		return Reserved
	}
}

// Version returns the version of uuid.  It returns false if uuid is not
// valid.
func (uuid UUID) Version() (Version, bool) {
	if len(uuid) != 16 {
		return 0, false
	}
	return Version(uuid[6] >> 4), true
}

func (v Version) String() string {
	if v > 15 {
		return fmt.Sprintf("BAD_VERSION_%d", v)
	}
	return fmt.Sprintf("VERSION_%d", v)
}

func (v Variant) String() string {
	switch v {
	case RFC4122:
		return "RFC4122"
	case Reserved:
		return "Reserved"
	case Microsoft:
		return "Microsoft"
	case Future:
		return "Future"
	case Invalid:
		return "Invalid"
	}
	return fmt.Sprintf("BadVariant%d", int(v))
}

// SetRand sets the random number generator to r, which implements io.Reader.
// If r.Read returns an error when the package requests random data then
// a panic will be issued.
//
// Calling SetRand with nil sets the random number generator to the default
// generator.
func SetRand(r io.Reader) {
	if r == nil {
		rander = rand.Reader
		return
	}
	rander = r
}


text:
require 'spec_helper'

describe Idobata::Hook::Airbrake, type: :hook do
  let(:payload) { fixture_payload("airbrake/#{fixture}.json") }

  before do
    post payload, 'Content-Type' => 'application/json'
  end

  describe '#process_payload' do
    subject { hook.process_payload }

    context 'via rack' do
      let(:fixture) { 'rack_error' }

      its([:source]) { should eq(<<-HTML.strip_heredoc) }

          Airbrake
          production
          118

          RuntimeError: You threw an exception for testing
          from
          http://airbrake.io:445/pages/exception_test

      HTML

      its([:format]) { should eq(:html) }
    end

    context 'standalone' do
      let(:fixture) { 'standalone_error' }

      its([:source]) { should eq(<<-HTML.strip_heredoc) }

          idobata-hooks

          1

          NameError: undefined local variable or method `hi' for main:Object

      HTML

      its([:format]) { should eq(:html) }
    end
  end
end


text:
'use strict';

app.controller('NetworkCtrl', function($scope, $route, dataService, timerService) {

	var loadData = function () {
		console.log("Getting Network Data");

		dataService.getData("/network/chart/usdHash/60", function(data){
			$scope.config = data;
			console.log(data);
		});

	};

	loadData();
	// timerService.register(loadData, $route.current.controller);

	// $scope.$on("$routeChangeStart", function () {
 //       timerService.remove($route.current.controller);
 //    });
});


text:
from nova.tests.unit.integrated.v3 import test_servers

class ServerExternalEventsSamplesJsonTest(test_servers.ServersSampleBase):
    extension_name = "os-server-external-events"

    def setUp(self):
        """setUp Method for AdminActions api samples extension

        This method creates the server that will be used in each tests
        """
        super(ServerExternalEventsSamplesJsonTest, self).setUp()
        self.uuid = self._post_server()

    def test_create_event(self):
        subs = {
            'uuid': self.uuid,
            'name': 'network-changed',
            'status': 'completed',
            'tag': 'foo',
            }
        response = self._do_post('os-server-external-events',
                                 'event-create-req',
                                 subs)
        subs.update(self._get_regexes())
        self._verify_response('event-create-resp', subs, response, 200)


text:
<?php

declare(strict_types=1);

namespace Mmoreram\PHPFormatter\Tests\Fixer;

use PHPUnit_Framework_TestCase;

use Mmoreram\PHPFormatter\Fixer\HeaderFixer;

/**
 * Class HeaderWithStrictFixerTest.
 */
class HeaderWithStrictFixerTest extends PHPUnit_Framework_TestCase
{
    /**
     * Test fixer.
     */
    public function testFix()
    {
        $data = '<?php

/**
 * This file is part of the php-formatter package
 *
 * Copyright (c) 2014 Marc Morera
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * Feel free to edit as you please, and have fun.
 *
 * @author Marc Morera <yuhu@mmoreram.com>
 */

declare(strict_types=1);';

        $header = '/**
 * This file is part of the php-formatter package
 *
 * Copyright (c) 2014 Marc Morera
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * Feel free to edit as you please, and have fun.
 *
 * @author Marc Morera <yuhu@mmoreram.com>
 */
';

        $fixedDataExpected =
'<?php

/**
 * This file is part of the php-formatter package
 *
 * Copyright (c) 2014 Marc Morera
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * Feel free to edit as you please, and have fun.
 *
 * @author Marc Morera <yuhu@mmoreram.com>
 */

declare(strict_types=1);';

        $headerFixer = new HeaderFixer($header);
        $this->assertFalse($headerFixer->fix($data));
    }
}


text:
package org.apache.arrow.vector.ipc;

import static org.apache.arrow.vector.testing.ValueVectorDataPopulator.setVector;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.channels.Channels;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.function.ToIntBiFunction;

import org.apache.arrow.memory.BufferAllocator;
import org.apache.arrow.memory.RootAllocator;
import org.apache.arrow.vector.FieldVector;
import org.apache.arrow.vector.UInt1Vector;
import org.apache.arrow.vector.UInt2Vector;
import org.apache.arrow.vector.UInt4Vector;
import org.apache.arrow.vector.UInt8Vector;
import org.apache.arrow.vector.ValueVector;
import org.apache.arrow.vector.VarCharVector;
import org.apache.arrow.vector.VectorSchemaRoot;
import org.apache.arrow.vector.dictionary.Dictionary;
import org.apache.arrow.vector.dictionary.DictionaryProvider;
import org.apache.arrow.vector.types.pojo.ArrowType;
import org.apache.arrow.vector.types.pojo.DictionaryEncoding;
import org.apache.arrow.vector.types.pojo.Field;
import org.apache.arrow.vector.types.pojo.FieldType;
import org.apache.arrow.vector.types.pojo.Schema;
import org.apache.arrow.vector.util.ByteArrayReadableSeekableByteChannel;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

/**
 * Test the round-trip of dictionary encoding,
 * with unsigned integer as indices.
 */
@RunWith(Parameterized.class)
public class TestUIntDictionaryRoundTrip {

  private final boolean streamMode;

  public TestUIntDictionaryRoundTrip(boolean streamMode) {
    this.streamMode = streamMode;
  }

  private BufferAllocator allocator;

  private DictionaryProvider.MapDictionaryProvider dictionaryProvider;

  @Before
  public void init() {
    allocator = new RootAllocator(Long.MAX_VALUE);
    dictionaryProvider = new DictionaryProvider.MapDictionaryProvider();
  }

  @After
  public void terminate() throws Exception {
    allocator.close();
  }

  private byte[] writeData(FieldVector encodedVector) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    VectorSchemaRoot root =
        new VectorSchemaRoot(
            Arrays.asList(encodedVector.getField()), Arrays.asList(encodedVector), encodedVector.getValueCount());
    try (ArrowWriter writer = streamMode ?
        new ArrowStreamWriter(root, dictionaryProvider, out) :
        new ArrowFileWriter(root, dictionaryProvider, Channels.newChannel(out))) {
      writer.start();
      writer.writeBatch();
      writer.end();

      return out.toByteArray();
    }
  }

  private void readData(
      byte[] data,
      Field expectedField,
      ToIntBiFunction<ValueVector, Integer> valGetter,
      long dictionaryID,
      int[] expectedIndices,
      String[] expectedDictItems) throws IOException {
    try (ArrowReader reader = streamMode ?
             new ArrowStreamReader(new ByteArrayInputStream(data), allocator) :
             new ArrowFileReader(new SeekableReadChannel(new ByteArrayReadableSeekableByteChannel(data)), allocator)) {

      // verify schema
      Schema readSchema = reader.getVectorSchemaRoot().getSchema();
      assertEquals(1, readSchema.getFields().size());
      assertEquals(expectedField, readSchema.getFields().get(0));

      // verify vector schema root
      assertTrue(reader.loadNextBatch());
      VectorSchemaRoot root = reader.getVectorSchemaRoot();

      assertEquals(1, root.getFieldVectors().size());
      ValueVector encodedVector = root.getVector(0);
      assertEquals(expectedIndices.length, encodedVector.getValueCount());

      for (int i = 0; i < expectedIndices.length; i++) {
        assertEquals(expectedIndices[i], valGetter.applyAsInt(encodedVector, i));
      }

      // verify dictionary
      Map<Long, Dictionary> dictVectors = reader.getDictionaryVectors();
      assertEquals(1, dictVectors.size());
      Dictionary dictionary = dictVectors.get(dictionaryID);
      assertNotNull(dictionary);

      assertTrue(dictionary.getVector() instanceof VarCharVector);
      VarCharVector dictVector = (VarCharVector) dictionary.getVector();
      assertEquals(expectedDictItems.length, dictVector.getValueCount());
      for (int i = 0; i < dictVector.getValueCount(); i++) {
        assertArrayEquals(expectedDictItems[i].getBytes(), dictVector.get(i));
      }
    }
  }

  private ValueVector createEncodedVector(int bitWidth, VarCharVector dictionaryVector) {
    final DictionaryEncoding dictionaryEncoding =
        new DictionaryEncoding(bitWidth, false, new ArrowType.Int(bitWidth, false));
    Dictionary dictionary = new Dictionary(dictionaryVector, dictionaryEncoding);
    dictionaryProvider.put(dictionary);

    final FieldType type =
        new FieldType(true, dictionaryEncoding.getIndexType(), dictionaryEncoding, null);
    final Field field = new Field("encoded", type, null);
    return field.createVector(allocator);
  }

  @Test
  public void testUInt1RoundTrip() throws IOException {
    final int vectorLength = UInt1Vector.MAX_UINT1 & UInt1Vector.PROMOTION_MASK;
    try (VarCharVector dictionaryVector = new VarCharVector("dictionary", allocator);
         UInt1Vector encodedVector1 = (UInt1Vector) createEncodedVector(8, dictionaryVector)) {
      int[] indices = new int[vectorLength];
      String[] dictionaryItems = new String[vectorLength];
      for (int i = 0; i < vectorLength; i++) {
        encodedVector1.setSafe(i, (byte) i);
        indices[i] = i;
        dictionaryItems[i] = String.valueOf(i);
      }
      encodedVector1.setValueCount(vectorLength);
      setVector(dictionaryVector, dictionaryItems);
      byte[] data = writeData(encodedVector1);
      readData(
          data, encodedVector1.getField(), (vector, index) -> (int) ((UInt1Vector) vector).getValueAsLong(index),
          8L, indices, dictionaryItems);
    }
  }

  @Test
  public void testUInt2RoundTrip() throws IOException {
    try (VarCharVector dictionaryVector = new VarCharVector("dictionary", allocator);
        UInt2Vector encodedVector2 = (UInt2Vector) createEncodedVector(16, dictionaryVector)) {
      int[] indices = new int[]{1, 3, 5, 7, 9, UInt2Vector.MAX_UINT2};
      String[] dictItems = new String[UInt2Vector.MAX_UINT2];
      for (int i = 0; i < UInt2Vector.MAX_UINT2; i++) {
        dictItems[i] = String.valueOf(i);
      }

      setVector(encodedVector2, (char) 1, (char) 3, (char) 5, (char) 7, (char) 9, UInt2Vector.MAX_UINT2);
      setVector(dictionaryVector, dictItems);

      byte[] data = writeData(encodedVector2);
      readData(data, encodedVector2.getField(), (vector, index) -> (int) ((UInt2Vector) vector).getValueAsLong(index),
          16L, indices, dictItems);
    }
  }

  @Test
  public void testUInt4RoundTrip() throws IOException {
    final int dictLength = 10;
    try (VarCharVector dictionaryVector = new VarCharVector("dictionary", allocator);
        UInt4Vector encodedVector4 = (UInt4Vector) createEncodedVector(32, dictionaryVector)) {
      int[] indices = new int[]{1, 3, 5, 7, 9};
      String[] dictItems = new String[dictLength];
      for (int i = 0; i < dictLength; i++) {
        dictItems[i] = String.valueOf(i);
      }

      setVector(encodedVector4, 1, 3, 5, 7, 9);
      setVector(dictionaryVector, dictItems);

      setVector(encodedVector4, 1, 3, 5, 7, 9);
      byte[] data = writeData(encodedVector4);
      readData(data, encodedVector4.getField(), (vector, index) -> (int) ((UInt4Vector) vector).getValueAsLong(index),
          32L, indices, dictItems);
    }
  }

  @Test
  public void testUInt8RoundTrip() throws IOException {
    final int dictLength = 10;
    try (VarCharVector dictionaryVector = new VarCharVector("dictionary", allocator);
        UInt8Vector encodedVector8 = (UInt8Vector) createEncodedVector(64, dictionaryVector)) {
      int[] indices = new int[]{1, 3, 5, 7, 9};
      String[] dictItems = new String[dictLength];
      for (int i = 0; i < dictLength; i++) {
        dictItems[i] = String.valueOf(i);
      }

      setVector(encodedVector8, 1L, 3L, 5L, 7L, 9L);
      setVector(dictionaryVector, dictItems);

      byte[] data = writeData(encodedVector8);
      readData(data, encodedVector8.getField(), (vector, index) -> (int) ((UInt8Vector) vector).getValueAsLong(index),
          64L, indices, dictItems);
    }
  }

  @Parameterized.Parameters(name = "stream mode = {0}")
  public static Collection<Object[]> getRepeat() {
    return Arrays.asList(
        new Object[]{true},
        new Object[]{false}
    );
  }
}


text:
package com.github.agourlay.cornichon.core

import munit.FunSuite

class FeatureSpec extends FunSuite {
  test("a Feature have Scenarios with unique names") {
    intercept[IllegalArgumentException] {
      val f = FeatureDef("malformed feature", Scenario("doing stuff", Nil) :: Scenario("doing stuff", Nil) :: Nil)
      assert(f.name == "malformed feature") //never reached
    }
  }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

	<meta http-equiv="content-type" content="text/html;charset=iso-8859-2" />
	<meta name="author" content="Luka Cvrk (www.solucija.com)" />
	<link rel="stylesheet" href="style.css" type="text/css" />
	<title>Internet Sharing</title>

Browse Today's favorites or All time favorites.
Please Log in to share and download files.

Internet Sharing

What do you want to share today?

Music

Videos

Archives

Images

Docs

All

				<form method="post" action="?">

<input type="text" name="search" class="search" /> <input type="submit" value="Search" class="button" />

				</form>

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex.

Read Mark

NOV
13th

The Future of P2P Networks

People like to share files, but what will the future bring?

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui.

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

Lorem ipsum dolor sit amet
consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis.

Read Mark

Lorem ipsum dolor sit amet
consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis.

Read Mark

RSS Feed · Most Popular · Today's Favorites · All Time Favorites · Sharing Policy · CSS and XHTML

			© Copyright 2006 Internet Sharing, Design: Luka Cvrk, Solucija


text:
class BoolClass
  prepend Hashstructor

  member :shaq, value_type: TrueClass, required: true, attr_kind: :reader
end


text:
package ren.hankai.cordwood.data.jpa.logging;

import org.apache.commons.lang3.StringUtils;
import org.eclipse.persistence.logging.AbstractSessionLog;
import org.eclipse.persistence.logging.SessionLog;
import org.eclipse.persistence.logging.SessionLogEntry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * Eclipselink 到 SLF4J 日志适配器。 以下是 eclipse link 和 SLF4J 日志级别的对应关系
 *

 *
ALL,FINER,FINEST -> TRACE
 *
FINE -> DEBUG
 *
CONFIG,INFO -> INFO
 *
WARNING -> WARN
 *
SEVERE -> ERROR
 *

 *
 * @author hankai
 * @version 1.0.0
 * @since Mar 29, 2018 8:54:47 PM
 */
public class Slf4jSessionLogger extends AbstractSessionLog {

  /**
   * SLF4J 日志级别。
   */
  private enum LogLevel {
    TRACE, DEBUG, INFO, WARN, ERROR, OFF
  }

  public static final String ECLIPSELINK_NAMESPACE = "org.eclipse.persistence.logging";
  public static final String DEFAULT_CATEGORY = "default";
  public static final String DEFAULT_ECLIPSELINK_NAMESPACE =
      ECLIPSELINK_NAMESPACE + "." + DEFAULT_CATEGORY;
  private Map<Integer, LogLevel> mapLevels;
  private final Map<String, Logger> categoryLoggers = new HashMap<>();

  /**
   * 将日志器加到日志类别中。
   *
   * @param loggerCategory 日志类别
   * @param loggerNameSpace 日志命名空间
   * @author hankai
   * @since Mar 29, 2018 9:00:13 PM
   */
  private void addLogger(String loggerCategory, String loggerNameSpace) {
    categoryLoggers.put(loggerCategory, LoggerFactory.getLogger(loggerNameSpace));
  }

  /**
   * 主动初始化日志器。
   *
   * @author hankai
   * @since Mar 29, 2018 9:00:01 PM
   */
  private void createCategoryLoggers() {
    for (final String category : SessionLog.loggerCatagories) {
      addLogger(category, ECLIPSELINK_NAMESPACE + "." + category);
    }
    addLogger(DEFAULT_CATEGORY, DEFAULT_ECLIPSELINK_NAMESPACE);
  }

  /**
   * 为指定的类别生成日志器。
   *
   * @param category 类别
   * @return 日志器
   * @author hankai
   * @since Mar 29, 2018 8:59:25 PM
   */
  private Logger getLogger(String category) {
    if (StringUtils.isEmpty(category) || !categoryLoggers.containsKey(category)) {
      category = DEFAULT_CATEGORY;
    }
    return categoryLoggers.get(category);
  }

  /**
   * 为 eclipse link 的日志级别找到对应的 SLF4J 日志级别。
   *
   * @param level eclipselink 日志级别
   * @return SLF4J 日志级别
   * @author hankai
   * @since Mar 29, 2018 8:58:38 PM
   */
  private LogLevel getLogLevel(Integer level) {
    LogLevel logLevel = mapLevels.get(level);
    if (logLevel == null) {
      logLevel = LogLevel.OFF;
    }
    return logLevel;
  }

  /**
   * 构造 SLF4J 和 Eclipselink 的日志级别对应关系。
   *
   * @author hankai
   * @since Mar 29, 2018 8:58:21 PM
   */
  private void initMapLevels() {
    mapLevels = new HashMap<>();
    mapLevels.put(SessionLog.ALL, LogLevel.TRACE);
    mapLevels.put(SessionLog.FINEST, LogLevel.TRACE);
    mapLevels.put(SessionLog.FINER, LogLevel.DEBUG);
    mapLevels.put(SessionLog.FINE, LogLevel.INFO);
    mapLevels.put(SessionLog.CONFIG, LogLevel.INFO);
    mapLevels.put(SessionLog.INFO, LogLevel.INFO);
    mapLevels.put(SessionLog.WARNING, LogLevel.WARN);
    mapLevels.put(SessionLog.SEVERE, LogLevel.ERROR);
  }

  /**
   * 初始化日志器和日志级别映射。
   */
  public Slf4jSessionLogger() {
    super();
    createCategoryLoggers();
    initMapLevels();
  }

  @Override
  public void log(SessionLogEntry entry) {
    if (!shouldLog(entry.getLevel(), entry.getNameSpace())) {
      return;
    }
    final Logger logger = getLogger(entry.getNameSpace());
    final LogLevel logLevel = getLogLevel(entry.getLevel());
    final StringBuilder message = new StringBuilder();
    message.append(getSupplementDetailString(entry));
    message.append(formatMessage(entry));
    switch (logLevel) {
      case TRACE:
        logger.trace(message.toString());
        break;
      case DEBUG:
        logger.debug(message.toString());
        break;
      case INFO:
        logger.info(message.toString());
        break;
      case WARN:
        logger.warn(message.toString());
        break;
      case ERROR:
        logger.error(message.toString());
        break;
      default:
        break;
    }
  }

  @Override
  public boolean shouldDisplayData() {
    if (shouldDisplayData != null) {
      return shouldDisplayData.booleanValue();
    } else {
      return false;
    }
  }

  @Override
  public boolean shouldLog(int level) {
    return shouldLog(level, "default");
  }

  @Override
  public boolean shouldLog(int level, String category) {
    final Logger logger = getLogger(category);
    boolean resp = false;
    final LogLevel logLevel = getLogLevel(level);
    switch (logLevel) {
      case TRACE:
        resp = logger.isTraceEnabled();
        break;
      case DEBUG:
        resp = logger.isDebugEnabled();
        break;
      case INFO:
        resp = logger.isInfoEnabled();
        break;
      case WARN:
        resp = logger.isWarnEnabled();
        break;
      case ERROR:
        resp = logger.isErrorEnabled();
        break;
      default:
        break;
    }
    return resp;
  }
}


text:
/**
 * Created by Liara Anna Maria Rørvig on 12/08/2017.
 */
'use strict';

let JSONFormatter = ( request, response, body, callback ) => {
    if ( body instanceof Error ) {
        if ( body.body ) {
            body = body.body;
        } else {
            body = {
                message : body.message
            };
        }
    } else if ( Buffer.isBuffer( body ) ) {
        body = body.toString( 'base64' );
    }

    let should_pretty_print = request.query.pretty_print !== 'false';
    let data                = JSON.stringify( body, null, should_pretty_print ? 2 : 0 );
    let content_length      = Buffer.byteLength( data );

    response.setHeader( 'Content-Length', content_length );

    return data;
};

module.exports = JSONFormatter;


text:
module Spree::Search
  class Solr < Spree::Search::Base
    # method should return hash with conditions {:conditions=> "..."} for Product model
    def get_products_conditions_for(query)
      facets = {
          :fields => [:price_range, :taxon_names, :brand_property, :color_option, :size_option],
          :browse => @properties[:facets_hash].map{|k,v| "#{k}:#{v}"},
          :zeros => false
      }
      search_options = {:facets => facets, :limit => 25000, :lazy => true}
      if order_by_price
        search_options.merge!(:order => (order_by_price == 'descend') ? "price desc" : "price asc")
      end
      full_query = query + " AND is_active:(true)"
      if taxon
        taxons_query = taxon.self_and_descendants.map{|t| "taxon_ids:(#{t.id})"}.join(" OR ")
        full_query += " AND (#{taxons_query})"
      end

      result = Product.find_by_solr(full_query, search_options)
      @properties[:products] = result.records
      count = result.records.size

      products = Product.paginate_all_by_solr(query,
                  :page => page, :per_page => per_page, :total_entries => count)

      @properties[:products] = products
      @properties[:suggest] = nil
      begin
      if suggest = result.suggest
        suggest.sub!(/\sAND.*/, '')
        @properties[:suggest] = suggest if suggest != query
      end
      rescue
      end

      @properties[:facets] = parse_facets_hash(result.facets)
      {:conditions=> ["products.id IN (?)", products.map(&:id)]}
    end

    def prepare(params)
      @properties[:facets_hash] = params[:facets] || {}
      @properties[:taxon] = params[:taxon].blank? ? nil : Taxon.find(params[:taxon])
      @properties[:per_page] = params[:per_page]
      @properties[:page] = params[:page]
      @properties[:manage_pagination] = true
      @properties[:order_by_price] = params[:order_by_price]
    end

    private

    def parse_facets_hash(facets_hash = {"facet_fields" => {}})
      facets = []
      price_ranges = YAML::load(Spree::Config[:product_price_ranges])
      facets_hash["facet_fields"].each do |name, options|
        next if options.size <= 1
        facet = Facet.new(name.sub('_facet', ''))
        if name == 'price_range_facet'
          price_ranges.each do |price_range|
            count = options[price_range]
            facet.options << FacetOption.new(price_range, count) if count
          end
        else
          options.each do |value, count|
            facet.options << FacetOption.new(value, count)
          end
        end
        facets << facet
      end
      facets
    end
  end

  class Facet
    attr_accessor :options
    attr_accessor :name
    def initialize(name, options = [])
      self.name = name
      self.options = options
    end
  end

  class FacetOption
    attr_accessor :name
    attr_accessor :count
    def initialize(name, count)
      self.name = name
      self.count = count
    end
  end
end


text:
'use strict';
require('./common');
var assert = require('assert');
var zlib = require('../');

var gzip = zlib.createGzip();
var gunz = zlib.createUnzip();

gzip.pipe(gunz);

var output = '';
var input = 'A line of data\n';
gunz.setEncoding('utf8');
gunz.on('data', function(c) {
  output += c;
});

process.on('exit', function() {
  assert.equal(output, input);

  // Make sure that the flush flag was set back to normal
  assert.equal(gzip._flushFlag, zlib.Z_NO_FLUSH);

  console.log('ok');
});

// make sure that flush/write doesn't trigger an assert failure
gzip.flush(); write();
function write() {
  gzip.write(input);
  gzip.end();
  gunz.read(0);
}


text:
import DebitCardsLayout from './DebitCardsLayout.jsx'

export default DebitCardsLayout


text:
namespace StripeTests
{
    using System;
    using System.Collections.Generic;
    using System.Reflection;
    using Newtonsoft.Json;
    using Stripe;
    using Xunit;

    /// <summary>
    /// This wholesome test ensures that lists (as in <see cref="List{T}"/>) are used instead of
    /// arrays (<c>[]</c>) in Stripe entities and options classes.
    /// </summary>
    public class UseListsInsteadOfArrays : WholesomeTest
    {
        private const string AssertionMessage =
            "Found at least one array type. Please use List<> instead.";

        [Fact]
        public void Check()
        {
            List<string> results = new List<string>();

            // Get all classes that derive from StripeEntity or implement INestedOptions
            var stripeClasses = GetSubclassesOf(typeof(StripeEntity));
            stripeClasses.AddRange(GetClassesWithInterface(typeof(INestedOptions)));

            foreach (Type stripeClass in stripeClasses)
            {
                foreach (PropertyInfo property in stripeClass.GetProperties())
                {
                    var propType = property.PropertyType;

                    // Skip properties that don't have a `JsonProperty` attribute
                    var attribute = property.GetCustomAttribute<JsonPropertyAttribute>();
                    if (attribute == null)
                    {
                        continue;
                    }

                    // Skip non-array types
                    if (!propType.GetTypeInfo().IsArray)
                    {
                        continue;
                    }

                    results.Add($"{stripeClass.Name}.{property.Name}");
                }
            }

            AssertEmpty(results, AssertionMessage);
        }
    }
}


text:
<resources>
    <string name="app_name">"Tumblr Photography Application "</string>

    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="title_activity_web_view_fragment">WebViewFragment</string>
    <string name="title_activity_go_to_tumblr">GoToTumblr</string>
</resources>


text:
extern "C" {
  #include "LIBRARY/src/bid64_exp.c"
}

#  pragma GCC diagnostic pop

#endif


text:
container_id: supersonic
docs_sections:
  - name: Supersonic API
    id: api-reference
  - name: Cordova API
    id: api-reference/cordova
---

<!DOCTYPE html>

    {% include meta_tags.html %}
    <title>{{page.title}} - Supersonic Framework</title>
    {% include head_includes.html %}

    {% include header.html %}

        {{content}}

    {% include footer.html %}

    {% include base_scripts.html %}


text:
package testutil

import (
	"testing"

	peer "gx/ipfs/QmRBqJF7hb8ZSpRcMwUt8hNhydWcxGEhtk81HKq6oUwKvs/go-libp2p-peer"
	ci "gx/ipfs/QmUWER4r4qMvaCnX5zREcfyiWN7cXN9g3a7fkRqNz8qWPP/go-libp2p-crypto"
	ma "gx/ipfs/QmYzDkkgAEmrcNzFCiYo6L1dTX4EAG1gZkbtdbd9trL4vd/go-multiaddr"
)

type Identity interface {
	Address() ma.Multiaddr
	ID() peer.ID
	PrivateKey() ci.PrivKey
	PublicKey() ci.PubKey
}

// TODO add a cheaper way to generate identities

func RandIdentity() (Identity, error) {
	p, err := RandPeerNetParams()
	if err != nil {
		return nil, err
	}
	return &identity{*p}, nil
}

func RandIdentityOrFatal(t *testing.T) Identity {
	p, err := RandPeerNetParams()
	if err != nil {
		t.Fatal(err)
	}
	return &identity{*p}
}

// identity is a temporary shim to delay binding of PeerNetParams.
type identity struct {
	PeerNetParams
}

func (p *identity) ID() peer.ID {
	return p.PeerNetParams.ID
}

func (p *identity) Address() ma.Multiaddr {
	return p.Addr
}

func (p *identity) PrivateKey() ci.PrivKey {
	return p.PrivKey
}

func (p *identity) PublicKey() ci.PubKey {
	return p.PubKey
}


text:
from django.utils.translation import ugettext_lazy as _

import horizon
from openstack_dashboard.dashboards.project import dashboard

class Project_CustomerInvoices(horizon.Panel):
    name = _("Invoices")
    slug = "customer_invoices"
    # permissions = ('openstack.roles.member',)

dashboard.Project.register(Project_CustomerInvoices)


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--
  ~ Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
  ~
  ~ WSO2 Inc. licenses this file to you 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.
  -->
<Analytics>
    <Editable>true</Editable>
    <Name>AndroidDataScript</Name>
    <Script>        CREATE TEMPORARY TABLE AndroidDataData USING CarbonAnalytics OPTIONS(tableName "IOT_PER_DEVICE_STREAM_ANDROID_DATA_STATS", incrementalParams "IOT_PER_DEVICE_STREAM_ANDROID_DATA_STATS, DAY");

        CREATE TEMPORARY TABLE Android_Data_Stat_Per_Day USING CarbonAnalytics
        OPTIONS (tableName "Android_Data_Stat_Per_Day",
        schema "owner STRING, deviceId STRING, type STRING, total LONG -i, year INT -i, month INT -i, day INT -i, timestamp STRING",
        primaryKeys "year, month, day, deviceId, owner, type",
        mergeSchema "false");

        INSERT INTO TABLE Android_Data_Stat_Per_Day
        SELECT meta_owner as owner, meta_deviceId as deviceId, type, sum(total) as total, year, month, day, getDateStartingTime(year, month, day) as timestamp
        FROM AndroidDataData
        GROUP BY year, month, day, meta_deviceId, meta_owner, type ORDER BY timestamp DESC;

        INCREMENTAL_TABLE_COMMIT IOT_PER_DEVICE_STREAM_ANDROID_DATA_STATS;
    </Script>
    <CronExpression>0 0/5 * * * ?</CronExpression>
</Analytics>


text:
set(PACKAGE_VERSION 1.1)
if("${PACKAGE_FIND_VERSION_MAJOR}" EQUAL 1)
  set(PACKAGE_VERSION_COMPATIBLE 1)
  if("${PACKAGE_FIND_VERSION_MINOR}" EQUAL 1)
    set(PACKAGE_VERSION_EXACT 1)
  endif()
endif()


text:
"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.default = void 0;

const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor;var _default =

AsyncFunction;exports.default = _default;
//# sourceMappingURL=AsyncFunction.js.map


text:
package com.zaxxer.hikari.proxy;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * This is the proxy class for java.sql.PreparedStatement.
 *
 * @author Brett Wooldridge
 */
public abstract class PreparedStatementProxy extends StatementProxy implements PreparedStatement
{
   protected PreparedStatementProxy(ConnectionProxy connection, PreparedStatement statement)
   {
      super(connection, statement);
   }

   // **********************************************************************
   //              Overridden java.sql.PreparedStatement Methods
   // **********************************************************************

   /** {@inheritDoc} */
   @Override
   public boolean execute() throws SQLException
   {
      connection.markCommitStateDirty();
      return ((PreparedStatement) delegate).execute();
   }

   /** {@inheritDoc} */
   @Override
   public ResultSet executeQuery() throws SQLException
   {
      connection.markCommitStateDirty();
      ResultSet resultSet = ((PreparedStatement) delegate).executeQuery();
      return ProxyFactory.getProxyResultSet(connection, this, resultSet);
   }

   /** {@inheritDoc} */
   @Override
   public int executeUpdate() throws SQLException
   {
      connection.markCommitStateDirty();
      return ((PreparedStatement) delegate).executeUpdate();
   }

   /** {@inheritDoc} */
   @Override
   public long executeLargeUpdate() throws SQLException
   {
      connection.markCommitStateDirty();
      return ((PreparedStatement) delegate).executeLargeUpdate();
   }
}


text:
using DataCloner.Core.Configuration;
using DataCloner.Core.Data;
using DataCloner.Core.Framework;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace DataCloner.Core.Metadata
{
    public sealed class MetadataContainer
    {
        internal delegate void Initialiser(IQueryDispatcher dispatcher, Settings settings, ref MetadataContainer container);

        public string ConfigFileHash { get; set; }
        public Dictionary<ServerIdentifier, ServerIdentifier> ServerMap { get; set; }
        public List<SqlConnection> ConnectionStrings { get; set; }
        public AppMetadata Metadatas { get; set; }

        public MetadataContainer()
        {
            ServerMap = new Dictionary<ServerIdentifier, ServerIdentifier>();
            ConnectionStrings = new List<SqlConnection>();
            Metadatas = new AppMetadata();
        }

        /// <summary>
        /// Verify if the last build of the container's metadata still match with the current cloning settings.
        /// </summary>
        /// <param name="dispatcher">Query dispatcher</param>
        /// <param name="app">Application user config</param>
        /// <param name="mapId">MapId</param>
        /// <param name="behaviourId">BehaviourId</param>
        /// <param name="container">Container</param>
        public static void VerifyIntegrityWithSettings(IQueryDispatcher dispatcher, Settings settings, ref MetadataContainer container)
        {
            if (dispatcher == null) throw new ArgumentNullException(nameof(dispatcher));
            if (settings == null) throw new ArgumentNullException(nameof(settings));
            if (settings.Project == null) throw new ArgumentNullException(nameof(settings.Project));
            if (String.IsNullOrWhiteSpace(settings.Project.Name)) throw new ArgumentException(nameof(settings.Project.Name));
            if (settings.Project.ConnectionStrings != null &&
                !settings.Project.ConnectionStrings.Any())
                throw new NullReferenceException("settings.Project.ConnectionStrings");

            var project = settings.Project;
            var containerFileName = project.Name + "_";
            Map map = null;
            Behaviour clonerBehaviour = null;

            //Hash the selected map, connnectionStrings and the cloner
            //configuration to see if it match the lasted builded container
            var configData = new MemoryStream();
            SerializationHelper.Serialize(configData, project.ConnectionStrings);

            if (settings.MapId.HasValue)
            {
                map = settings.Project.Maps.FirstOrDefault(m => m.Id == settings.MapId);
                if (map == null)
                    throw new Exception($"Map id '{settings.MapId}' not found in configuration file for application '{project.Name}'!");
                containerFileName += map.From + "-" + map.To;
                SerializationHelper.Serialize(configData, map);

                if (map.UsableBehaviours != null && map.UsableBehaviours.Split(',').ToList().Contains(settings.BehaviourId.ToString()))
                {
                    clonerBehaviour = project.Behaviours.FirstOrDefault(c => c.Id == settings.BehaviourId);
                    if (clonerBehaviour == null)
                        throw new KeyNotFoundException(
                            $"There is no behaviour '{settings.BehaviourId}' in the configuration for the appName name '{project.Name}'.");

                    SerializationHelper.Serialize(configData, clonerBehaviour);
                    SerializationHelper.Serialize(configData, project.Templates);
                }
            }
            else
                containerFileName += "defaultMap";

            if (settings.BehaviourId != null)
                containerFileName += "_" + settings.BehaviourId;
            containerFileName += ".cache";

            //Hash user config
            configData.Position = 0;
            //var murmur = MurmurHash.Create32(managed: false);
            //var configHash = Encoding.UTF8.GetString(murmur.ComputeHash(configData));
            var configHash = container.ConfigFileHash + "random";

            //If in-memory container is good, we use it
            if (container != null && container.ConfigFileHash == configHash)
                return;

            if (!settings.UseInMemoryCacheOnly)
            {
                //If container on disk is good, we use it
                container = TryLoadContainer(containerFileName, configHash);
                if (container != null)
                {
                    dispatcher.InitProviders(container.Metadatas, container.ConnectionStrings);
                    return;
                }
            }

            //We rebuild the container
            container = BuildMetadataWithSettings(dispatcher, containerFileName, project, clonerBehaviour, map, configHash);

            //Persist container
            if (!settings.UseInMemoryCacheOnly)
                container.Save(containerFileName);
        }

        /// <summary>
        /// Verify if the last build of the container's metadata still match with the sql servers (application's connectionStrings).
        /// </summary>
        /// <param name="dispatcher">Query dispatcher</param>
        /// <param name="proj">Project config</param>
        /// <param name="container">Metadata container</param>
        public static void VerifyIntegrityOfSqlMetadata(IQueryDispatcher dispatcher, ProjectContainer proj, ref MetadataContainer container)
        {
            if (dispatcher == null) throw new ArgumentNullException(nameof(dispatcher));
            if (proj == null) throw new ArgumentNullException(nameof(proj));
            if (proj.ConnectionStrings != null && !proj.ConnectionStrings.Any()) throw new NullReferenceException("ConnectionStrings");

            var containerFileName = proj.Name + ".schema";

            //Hash the connnectionStrings to see if it match the last build
            var configData = new MemoryStream();
            SerializationHelper.Serialize(configData, proj.ConnectionStrings);
            configData.Position = 0;

            //HashAlgorithm murmur = MurmurHash.Create32(managed: false);
            //var configHash = Encoding.UTF8.GetString(murmur.ComputeHash(configData));
            var configHash = container.ConfigFileHash + "random";

            //If in-memory container is good, we use it
            if (container != null && container.ConfigFileHash == configHash)
                return;
            //If container on disk is good, we use it
            container = TryLoadContainer(containerFileName, configHash);
            if (container != null)
                dispatcher.InitProviders(container.Metadatas, container.ConnectionStrings);
            //We rebuild the container
            else
                container = BuildMetadata(dispatcher, containerFileName, proj.ConnectionStrings, configHash);
        }

        public void Serialize(Stream output, FastAccessList<object> referenceTracking = null)
        {
            Serialize(new BinaryWriter(output, Encoding.UTF8, true), referenceTracking);
        }

        public static MetadataContainer Deserialize(Stream input, FastAccessList<object> referenceTracking = null)
        {
            return Deserialize(new BinaryReader(input, Encoding.UTF8, true));
        }

        public void Serialize(BinaryWriter output, FastAccessList<object> referenceTracking = null)
        {
            output.Write(ConfigFileHash);

            if (ServerMap != null)
            {
                output.Write(ServerMap.Count);
                foreach (var sm in ServerMap)
                {
                    sm.Key.Serialize(output);
                    sm.Value.Serialize(output);
                }
            }
            else
                output.Write(0);

            output.Write(ConnectionStrings.Count);
            foreach (var cs in ConnectionStrings)
                cs.Serialize(output);
            Metadatas.Serialize(output, referenceTracking);

            output.Flush();
        }

        public void Save(string path)
        {
            using (var fs = new FileStream(path, FileMode.Create))
            {
                Serialize(fs);
            }
        }

        public static MetadataContainer Deserialize(BinaryReader input, FastAccessList<object> referenceTracking = null)
        {
            var config = new MetadataContainer { ConfigFileHash = input.ReadString() };

            DeserializeBody(input, config, referenceTracking);

            return config;
        }

        /// <summary>
        /// Also merge user configs
        /// </summary>
        /// <param name="dispatcher"></param>
        /// <param name="containerFileName"></param>
        /// <param name="proj"></param>
        /// <param name="clonerBehaviour"></param>
        /// <param name="map"></param>
        /// <param name="configHash"></param>
        /// <returns></returns>
        private static MetadataContainer BuildMetadataWithSettings(IQueryDispatcher dispatcher, string containerFileName,
                                                                   ProjectContainer proj, Behaviour clonerBehaviour,
                                                                   Map map, string configHash)
        {
            var container = new MetadataContainer { ConfigFileHash = configHash, ServerMap = map.ConvertToDictionnary() };

            ////Get servers source
            //var serversSource = map.Roads.Select(r => r.ServerSrc).Distinct().ToList();

            ////Replace variables
            //for (int i = 0; i < serversSource.Count(); i++)
            //{
            //    if (serversSource[i].IsVariable())
            //    {
            //        var configVar = map.Variables.FirstOrDefault(v => v.Name == serversSource[i]);
            //        if (configVar == null)
            //            throw new Exception($"The variable '{0}' is not found in the map with id='{1}'.", serversSource[i], map.Id));
            //        serversSource[i] = configVar.Value.ToString();
            //    }
            //}

            ////Copy connection strings
            //foreach (var cs in app.ConnectionStrings.Where(c => serversSource.Contains(c.Id.ToString())))
            //    container.ConnectionStrings.Add(new SqlConnection(cs.Id, cs.ProviderName, cs.ConnectionString));

            //Copy connection strings
            foreach (var cs in proj.ConnectionStrings)
            {
                container.ConnectionStrings.Add(
                    new SqlConnection(cs.Id)
                    {
                        ProviderName = cs.ProviderName,
                        ConnectionString = cs.ConnectionString
                    });
            }

            if (container.ConnectionStrings.Count() == 0)
                throw new Exception("No connectionStrings!");

            FetchMetadata(dispatcher, ref container);

            Behaviour behaviour = null;
            if (clonerBehaviour != null)
            {
                List<Variable> vars = null;
                if (map != null)
                    vars = map.Variables;

                behaviour = clonerBehaviour.Build(proj.Templates, vars);
            }
            container.Metadatas.FinalizeMetadata(behaviour);

            return container;
        }

        /// <summary>
        /// Only build the database schema.
        /// </summary>
        /// <param name="dispatcher"></param>
        /// <param name="containerFileName"></param>
        /// <param name="connections"></param>
        /// <param name="configHash"></param>
        /// <returns></returns>
        private static MetadataContainer BuildMetadata(IQueryDispatcher dispatcher, string containerFileName,
                                                       List<Connection> connections, string configHash)
        {
            var container = new MetadataContainer { ConfigFileHash = configHash };

            //Copy connection strings
            foreach (var cs in connections)
            {
                container.ConnectionStrings.Add(
                    new SqlConnection(cs.Id)
                    {
                        ProviderName = cs.ProviderName,
                        ConnectionString = cs.ConnectionString
                    });
            }

            FetchMetadata(dispatcher, ref container);
            container.Metadatas.FinalizeSchema();

            //Save container
            container.Save(containerFileName);
            return container;
        }

        private static void FetchMetadata(IQueryDispatcher dispatcher, ref MetadataContainer container)
        {
            dispatcher.InitProviders(container.Metadatas, container.ConnectionStrings);

            foreach (var cs in container.ConnectionStrings)
            {
                var provider = dispatcher.GetQueryHelper(cs.Id);

                foreach (var database in provider.GetDatabasesName())
                {
                    provider.GetColumns(container.Metadatas.LoadColumns, cs.Id, database);
                    provider.GetForeignKeys(container.Metadatas.LoadForeignKeys, cs.Id, database);
                    provider.GetUniqueKeys(container.Metadatas.LoadUniqueKeys, cs.Id, database);
                }
            }
        }

        private static MetadataContainer DeserializeBody(BinaryReader input, MetadataContainer config,
            FastAccessList<object> referenceTracking = null)
        {
            var nbServerMap = input.ReadInt32();
            for (var i = 0; i < nbServerMap; i++)
            {
                var src = ServerIdentifier.Deserialize(input);
                var dst = ServerIdentifier.Deserialize(input);
                config.ServerMap.Add(src, dst);
            }
            var nbConnection = input.ReadInt32();
            for (var i = 0; i < nbConnection; i++)
                config.ConnectionStrings.Add(SqlConnection.Deserialize(input));

            config.Metadatas = AppMetadata.Deserialize(input, referenceTracking);

            return config;
        }

        private static MetadataContainer TryLoadContainer(string containerFile, string configHash)
        {
            MetadataContainer container = null;

            if (File.Exists(containerFile))
            {
                using (var fs = new FileStream(containerFile, FileMode.Open))
                using (var br = new BinaryReader(fs, Encoding.UTF8, true))
                {
                    var fileHash = br.ReadString();

                    //Check if container file match with config file version
                    if (fileHash == configHash)
                    {
                        container = new MetadataContainer { ConfigFileHash = fileHash };
                        DeserializeBody(br, container);
                    }
                }
            }
            return container;
        }
    }
}


text:
<?php
// WARNING, this is a read only file created by import scripts
// WARNING
// WARNING,  Changes made to this file will be clobbered
// WARNING
// WARNING,  Please make changes on poeditor instead of here
//
//
?>
subject: Relatório sobre a transferência nº {target.id}

{alternative:plain}

Prezado Senhor(a),

Por favor, faça o download do relatório sobre a transferência nº {target.id} anexo a este e-mail.

Atenciosamente,
{cfg:site_name}

{alternative:html}

    Prezado Senhor(a),

    Por favor, faça o download do relatório sobre a transferência nº {target.id} anexo a este e-mail.

Atenciosamente,

{cfg:site_name}


text:
class AssignmentDueDate < DueDate
  belongs_to :assignment, class_name: 'Assignment', foreign_key: 'parent_id'
  belongs_to :deadline_type, class_name: 'DeadlineType', foreign_key: 'deadline_type_id'
end


text:
package network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import main.Main;

public class Child implements Runnable {

	private Socket s;

	public Child(Socket s) {
		this.s = s;
	}

	public void run() {
		System.out.println("New Child : " + s.getInetAddress() + ":" + s.getPort());
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
			while (true) {
				// Waiting for message
				String str = br.readLine();

				// Construct Message, TODO Check tab length
				String[] tab = str.split("&");
				Message msg = new Message(Long.valueOf(tab[0]), tab[1], tab[2]);

				// TODO Forward
				Main.server.sendMessage(msg);

			}

		} catch (IOException e) {
			System.out.println("Connection lost with " + s.getInetAddress() + ":" + s.getPort());
		}
	}

	public void close(){
		try {
			s.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void sendMessage(Message msg) {
		try {
			PrintWriter out = new PrintWriter(s.getOutputStream(), true);

			// TODO Message Format
			out.println(msg.getDate() + "&" + msg.getLogin() + "&" + msg.getText());

			// Validate
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}


text:
Ejemplo de uso de GITHUB App

En este proyecto se explica con un ejemplo como utilizar el Math.random en JS.


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

/**
 * This package contains the classes for servicebus samples.
 */
package com.azure.resourcemanager.servicebus.samples;


text:
package vultrnosql

//ListTables list tables
func (vultrnosql *Vultrnosql) ListTables(request interface{}) (resp interface{}, err error) {

	return resp, err
}

//DeleteTables delete tables
func (vultrnosql *Vultrnosql) DeleteTables(request interface{}) (resp interface{}, err error) {
	return resp, err
}

//DescribeTables Describe tables
func (vultrnosql *Vultrnosql) DescribeTables(request interface{}) (resp interface{}, err error) {
	return resp, err
}

//CreateTables create tables
func (vultrnosql *Vultrnosql) CreateTables(request interface{}) (resp interface{}, err error) {
	return resp, err
}


text:
This generates a simple contribution report, by username, for a GitHub
repositiory.

## Usage

```
$ npm i -g contribution-report
$ contribution-report --help
```

### Examples

```bash
# Get contributor list with components
$ contribution-report -c -r nodejs/node -s 2015-10-05 -u 2015-10-12

66 commits in `nodejs/node` between 2015-10-05 and 2015-10-12:
* @Trott 11 commits
  * 1 to `lib,test`, 1 to `tools`, 1 to `lib`, 8 to `test`
* @indutny 6 commits
  * 1 to `buffer`, 1 to `stream_wrap`, 1 to `http_server`, 3 to `http`
* @trevnorris 5 commits
  * 1 to `js_stream`, 1 to `async_wrap`, 3 to `buffer`
* @evanlucas 4 commits
  * 1 to `test`, 3 to `util`
* @skomski 4 commits
  * 1 to `test`, 3 to `src`
…
```

```bash
# Get collaborators (requires push access to the repo)
$ contribution-report -C -r nodejs/nodejs.org -s 2015-10-05 -u 2015-10-12 \
  -U <GitHub user> -P <GitHub access token>

43 commits in `nodejs/nodejs.org` between 2015-10-05 and 2015-10-12:
* @fhemberger 9 commits (is a collaborator)
* @mikeal 7 commits (is a collaborator)
* @phillipj 6 commits (is a collaborator)
* @Trott 4 commits (is a collaborator)
* @greenkeeperio-bot 3 commits
…
```

## License

MIT License. See LICENSE.txt


text:
<?php

namespace Oro\Bundle\ImapBundle\Tests\Unit\Manager\DTO;

use Oro\Bundle\ImapBundle\Manager\ImapEmailFlagManager;

class ImapEmailFlagManagerTest extends \PHPUnit\Framework\TestCase
{
    /** @var ImapEmailFlagManager */
    private $manager;

    /** @var \PHPUnit\Framework\MockObject\MockObject */
    private $connector;

    /** @var \PHPUnit\Framework\MockObject\MockObject */
    protected $em;

    /** @var \PHPUnit\Framework\MockObject\MockObject */
    private $repoImapEmail;

    protected function setUp()
    {
        $this->connector = $this->getMockBuilder('Oro\Bundle\ImapBundle\Connector\ImapConnector')
            ->disableOriginalConstructor()
            ->getMock();

        $this->em = $this->getMockBuilder('Oro\Bundle\EntityBundle\ORM\OroEntityManager')
            ->disableOriginalConstructor()
            ->getMock();

        $this->repoImapEmail = $this->getMockBuilder('Oro\Bundle\ImapBundle\Entity\Repository\ImapEmailRepository')
            ->disableOriginalConstructor()
            ->getMock();

        $this->manager = new ImapEmailFlagManager($this->connector, $this->em);
    }

    public function testSetFlags()
    {
        $folderId = 1;
        $emailId = 2;
        $flags = [];

        $this->repoImapEmail->expects($this->once())
            ->method('getUid')
            ->will($this->returnValue(1))
            ->with($folderId, $emailId);

        $this->em->expects($this->once())
            ->method('getRepository')->willReturn($this->repoImapEmail);

        $this->connector->expects($this->once())
            ->method('setFlags')
            ->with(1, $flags);

        $emailFolder = $this->getMockBuilder('Oro\Bundle\EmailBundle\Entity\EmailFolder')
            ->disableOriginalConstructor()
            ->getMock();
        $emailFolder->expects($this->once())
            ->method('getId')->will($this->returnValue($folderId));

        $email = $this->getMockBuilder('Oro\Bundle\EmailBundle\Entity\Email')
            ->disableOriginalConstructor()
            ->getMock();
        $email->expects($this->once())
            ->method('getId')->will($this->returnValue($emailId));

        $this->manager->setFlags($emailFolder, $email, $flags);
    }

    public function testSetSeen()
    {
        $folderId = 1;
        $emailId = 2;
        $flags = [ImapEmailFlagManager::FLAG_SEEN];

        $this->repoImapEmail->expects($this->once())
            ->method('getUid')
            ->will($this->returnValue(1))
            ->with($folderId, $emailId);

        $this->em->expects($this->once())
            ->method('getRepository')->willReturn($this->repoImapEmail);

        $this->connector->expects($this->once())
            ->method('setFlags')
            ->with(1, $flags);

        $emailFolder = $this->getMockBuilder('Oro\Bundle\EmailBundle\Entity\EmailFolder')
            ->disableOriginalConstructor()
            ->getMock();
        $emailFolder->expects($this->once())
            ->method('getId')->will($this->returnValue($folderId));

        $email = $this->getMockBuilder('Oro\Bundle\EmailBundle\Entity\Email')
            ->disableOriginalConstructor()
            ->getMock();
        $email->expects($this->once())
            ->method('getId')->will($this->returnValue($emailId));

        $this->manager->setSeen($emailFolder, $email);
    }

    public function testSetUnSeen()
    {
        $folderId = 1;
        $emailId = 2;
        $flags = [ImapEmailFlagManager::FLAG_UNSEEN];

        $this->repoImapEmail->expects($this->once())
            ->method('getUid')
            ->will($this->returnValue(1))
            ->with($folderId, $emailId);

        $this->em->expects($this->once())
            ->method('getRepository')->willReturn($this->repoImapEmail);

        $this->connector->expects($this->once())
            ->method('setFlags')
            ->with(1, $flags);

        $emailFolder = $this->getMockBuilder('Oro\Bundle\EmailBundle\Entity\EmailFolder')
            ->disableOriginalConstructor()
            ->getMock();
        $emailFolder->expects($this->once())
            ->method('getId')->will($this->returnValue($folderId));

        $email = $this->getMockBuilder('Oro\Bundle\EmailBundle\Entity\Email')
            ->disableOriginalConstructor()
            ->getMock();
        $email->expects($this->once())
            ->method('getId')->will($this->returnValue($emailId));

        $this->manager->setUnseen($emailFolder, $email);
    }
}