text:
package org.maculaframework.boot.core.config;

import org.maculaframework.boot.MaculaConstants;
import org.maculaframework.boot.core.config.jpa.MaculaJpaRepositoriesConfigurationRegistar;
import org.maculaframework.boot.core.repository.domain.support.AuditorAwareStub;
import org.maculaframework.boot.core.repository.domain.support.DbDateTimeProvider;
import org.maculaframework.boot.core.repository.jpa.templatequery.template.FreemarkerSqlTemplates;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.transaction.annotation.AbstractTransactionManagementConfiguration;

/**
 *

 * JpaRepositoriesConfiguration JPA Repository配置
 *

 *
 * @author Rain
 * @since 2019-02-18
 */
@Configuration
@EnableJpaAuditing(auditorAwareRef = "auditorAwareStub", dateTimeProviderRef = "dbDateTimeProvider")
@EnableConfigurationProperties(HibernateProperties.class)
@ConditionalOnClass(JpaRepository.class)
@ConditionalOnProperty(prefix = MaculaConstants.CONFIG_JPA_PREFIX, name = "enabled", havingValue = "true", matchIfMissing = true)
@Import(MaculaJpaRepositoriesConfigurationRegistar.class)
class JpaRepositoriesConfiguration {

    // JPA Audit配置
    @Bean
    @ConditionalOnMissingBean
    public AuditorAwareStub auditorAwareStub() {
        return new AuditorAwareStub();
    }

    @Bean
    @ConditionalOnMissingBean
    public DbDateTimeProvider dbDateTimeProvider() {
        return new DbDateTimeProvider();
    }

    // JPA TemplateQuery配置
    @Bean
    @ConditionalOnMissingBean
    public FreemarkerSqlTemplates freemarkerSqlTemplates() {
        return new FreemarkerSqlTemplates();
    }

    // 为了禁止TransactionAutoConfiguration
    @Bean
    public AbstractTransactionManagementConfiguration transactionManagementConfiguration() {
        return new AbstractTransactionManagementConfiguration() {

        };
    }

}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Zimbra\Enum;

/**
 * Operation enum class
 *
 * @package   Zimbra
 * @category  Enum
 * @author    Nguyen Van Nguyen - nguyennv1981@gmail.com
 * @copyright Copyright © 2013 by Nguyen Van Nguyen.
 */
class Operation extends Base
{
    /**
     * Constant for value 'delete'
     * @return string 'delete'
     */
    const DELETE = 'delete';

    /**
     * Constant for value 'modify'
     * @return string 'modify'
     */
    const MODIFY = 'modify';

    /**
     * Constant for value 'rename'
     * @return string 'rename'
     */
    const RENAME = 'rename';

    /**
     * Constant for value 'addOwners'
     * @return string 'addOwners'
     */
    const ADD_OWNERS = 'addOwners';

    /**
     * Constant for value 'removeOwners'
     * @return string 'removeOwners'
     */
    const REMOVE_OWNERS = 'removeOwners';

    /**
     * Constant for value 'setOwners'
     * @return string 'setOwners'
     */
    const SET_OWNERS = 'setOwners';

    /**
     * Constant for value 'grantRights'
     * @return string 'grantRights'
     */
    const GRANT_RIGHTS = 'grantRights';

    /**
     * Constant for value 'revokeRights'
     * @return string 'revokeRights'
     */
    const REVOKE_RIGHTS = 'revokeRights';

    /**
     * Constant for value 'setRights'
     * @return string 'setRights'
     */
    const SET_RIGHTS = 'setRights';

    /**
     * Constant for value 'addMembers'
     * @return string 'addMembers'
     */
    const ADD_MEMBERS = 'addMembers';

    /**
     * Constant for value 'removeMembers'
     * @return string 'removeMembers'
     */
    const REMOVE_MEMBERS = 'removeMembers';

    /**
     * Constant for value 'acceptSubsReq'
     * @return string 'acceptSubsReq'
     */
    const ACCEPT_SUBSREQ = 'acceptSubsReq';

    /**
     * Constant for value 'rejectSubsReq'
     * @return string 'rejectSubsReq'
     */
    const REJECT_SUBSREQ = 'rejectSubsReq';
}


text:
package org.apache.sling.distribution.transport.impl;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.fluent.Executor;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.utils.URIBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpTransportUtils {

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

    public static InputStream fetchNextPackage(Executor executor, URI distributionURI) throws URISyntaxException, IOException {
        URI fetchUri = getFetchUri(distributionURI);
        Request fetchReq = Request.Post(fetchUri).useExpectContinue();
        HttpResponse httpResponse = executor.execute(fetchReq).returnResponse();

        if (httpResponse.getStatusLine().getStatusCode() != 200) {
            return null;
        }

        HttpEntity entity = httpResponse.getEntity();

        return entity.getContent();
    }

    public static boolean deletePackage(Executor executor, URI distributionURI, String remotePackageId) throws URISyntaxException, IOException {

        URI deleteUri = getDeleteUri(distributionURI, remotePackageId);
        Request deleteReq = Request.Post(deleteUri).useExpectContinue();
        HttpResponse httpResponse = executor.execute(deleteReq).returnResponse();

        return httpResponse.getStatusLine().getStatusCode() == 200;
    }

    private static URI getFetchUri(URI uri) throws URISyntaxException {
        URIBuilder uriBuilder = new URIBuilder(uri);
        uriBuilder.addParameter("operation", "fetch");

        return uriBuilder.build();
    }

    private static URI getDeleteUri(URI uri, String id) throws URISyntaxException {
        URIBuilder uriBuilder = new URIBuilder(uri);
        uriBuilder.addParameter("operation", "delete");
        uriBuilder.addParameter("id", id);

        return uriBuilder.build();
    }

}


text:
package org.apache.nifi.rules.handlers;

import org.apache.commons.lang3.StringUtils;
import org.apache.nifi.annotation.documentation.CapabilityDescription;
import org.apache.nifi.annotation.documentation.Tags;
import org.apache.nifi.annotation.lifecycle.OnEnabled;
import org.apache.nifi.components.PropertyDescriptor;
import org.apache.nifi.context.PropertyContext;
import org.apache.nifi.controller.ConfigurationContext;
import org.apache.nifi.controller.ControllerServiceInitializationContext;
import org.apache.nifi.reporting.InitializationException;
import org.apache.nifi.rules.Action;
import org.mvel2.MVEL;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@Tags({"rules", "rules engine", "action", "action handler", "expression language","MVEL","SpEL"})
@CapabilityDescription("Executes an action containing an expression written in MVEL or SpEL. The action " +
"is usually created by a rules engine. Action objects executed with this Handler should contain \"command\" and \"type\" attributes.")
public class ExpressionHandler extends AbstractActionHandlerService {

    enum ExpresssionType {
        MVEL, SPEL;
    }

    public static final PropertyDescriptor DEFAULT_EXPRESSION_LANGUAGE_TYPE = new PropertyDescriptor.Builder()
            .name("default-expression-language-type")
            .displayName("Default Expression Language Type")
            .required(true)
            .description("If an expression language type is not provided as an attribute within an Action, the default expression language that " +
                    "should be used to compile and execute action. Supported languages are MVEL and Spring Expression Language (SpEL).")
            .allowableValues(ExpresssionType.values())
            .defaultValue("MVEL")
            .build();

    private List<PropertyDescriptor> properties;
    private ExpresssionType type;

    @Override
    protected void init(ControllerServiceInitializationContext config) throws InitializationException {
        super.init(config);
        final List<PropertyDescriptor> properties = new ArrayList<>();
        properties.add(DEFAULT_EXPRESSION_LANGUAGE_TYPE);
        properties.add(ENFORCE_ACTION_TYPE);
        properties.add(ENFORCE_ACTION_TYPE_LEVEL);
        this.properties = Collections.unmodifiableList(properties);
    }

    @Override
    @OnEnabled
    public void onEnabled(final ConfigurationContext context) throws InitializationException {
        super.onEnabled(context);
        type = ExpresssionType.valueOf(context.getProperty(DEFAULT_EXPRESSION_LANGUAGE_TYPE).getValue());
    }

    @Override
    protected List<PropertyDescriptor> getSupportedPropertyDescriptors() {
        return properties;
    }

    @Override
    protected void executeAction(PropertyContext propertyContext, Action action, Map<String, Object> facts) {
        executeAction(action, facts);
    }

    @Override
    protected void executeAction(Action action, Map<String, Object> facts) {
        Map<String, String> attributes = action.getAttributes();
        final String command = attributes.get("command");
        if(StringUtils.isNotEmpty(command)) {
            try {
                final String type = attributes.getOrDefault("type",this.type.toString());
                ExpresssionType expresssionType = ExpresssionType.valueOf(type);
                if (expresssionType.equals(ExpresssionType.MVEL)) {
                    executeMVEL(command, facts);
                } else {
                    executeSPEL(command, facts);
                }
            } catch (Exception ex) {
                getLogger().warn("Error occurred when attempting to execute expression. Action: {}, Facts - {}",
                        new Object[]{action, facts}, ex);
            }
        }else{
            getLogger().warn("Command attribute was not provided.  Action: {}, Facts - {}",
                    new Object[]{action, facts});
        }
    }

    private void executeMVEL(String command, Map<String, Object> facts) {
        MVEL.executeExpression(MVEL.compileExpression(command), facts);
        if(getLogger().isDebugEnabled()) {
            getLogger().debug("Expression was executed successfully: {}: {}", new Object[]{type, command});
        }
    }

    private void executeSPEL(String command, Map<String, Object> facts) {
        final ExpressionParser parser = new SpelExpressionParser();
        StandardEvaluationContext context = new StandardEvaluationContext();
        context.setRootObject(facts);
        context.setVariables(facts);
        Expression expression = parser.parseExpression(command);
        Object value = expression.getValue(context);
        if(getLogger().isDebugEnabled()) {
            getLogger().debug("Expression was executed successfully with result: {}. {}: {}", new Object[]{value, type, command});
        }
    }

}


text:
namespace YAF.Pages.Admin
{

    public partial class Digest
    {

        /// <summary>
        /// PageLinks control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::YAF.Web.Controls.PageLinks PageLinks;

        /// <summary>
        /// LocalizedLabel4 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::YAF.Web.Controls.HelpLabel LocalizedLabel4;

        /// <summary>
        /// DigestEnabled control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label DigestEnabled;

        /// <summary>
        /// LocalizedLabel5 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::YAF.Web.Controls.HelpLabel LocalizedLabel5;

        /// <summary>
        /// LastDigestSendLabel control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label LastDigestSendLabel;

        /// <summary>
        /// Button2 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::YAF.Web.Controls.ThemeButton Button2;

        /// <summary>
        /// DigestHtmlPlaceHolder control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.PlaceHolder DigestHtmlPlaceHolder;

        /// <summary>
        /// LocalizedLabel6 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::YAF.Web.Controls.LocalizedLabel LocalizedLabel6;

        /// <summary>
        /// DigestFrame control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.HtmlControls.HtmlIframe DigestFrame;

        /// <summary>
        /// GenerateDigest control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::YAF.Web.Controls.ThemeButton GenerateDigest;

        /// <summary>
        /// LocalizedLabel7 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::YAF.Web.Controls.HelpLabel LocalizedLabel7;

        /// <summary>
        /// TextSendEmail control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox TextSendEmail;

        /// <summary>
        /// TestSend control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::YAF.Web.Controls.ThemeButton TestSend;
    }
}


text:
{% extends './base.html' %}

{% block content %}

	{% include './header.html' %}

			Topics

		<form style="display:none" id="topic-select-form" action="/user/topic-selected/" method="POST" >
			{% csrf_token %}
		</form>

  			{% for topic in topics %}

 {{topic.name}}

  			{% endfor %}

			<button class="dais-fab" data-role="none" >+</button>

	    <form action="/daisadmin/topic-create/" method="POST" >

						Add topic

			  			{% csrf_token %}
			            <input type="text" name="topic_name" id="topic_name" value="" placeholder="Title" data-theme="a">
			            <input type="text" name="topic_desc" value="" placeholder="Description" data-theme="a">
			            <button type="submit" id="submit-topic" class="ui-btn ui-corner-all ui-btn-icon-left ui-icon-check" onclick="createTopic(event, $(this))">Add</button>

	    </form>

	{% include './footer.html' %}

{% endblock %}


text:
#include <aws/redshift/model/DisableLoggingRequest.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>

using namespace Aws::Redshift::Model;
using namespace Aws::Utils;

DisableLoggingRequest::DisableLoggingRequest() :
    m_clusterIdentifierHasBeenSet(false)
{
}

Aws::String DisableLoggingRequest::SerializePayload() const
{
  Aws::StringStream ss;
  ss << "Action=DisableLogging&";
  if(m_clusterIdentifierHasBeenSet)
  {
    ss << "ClusterIdentifier=" << StringUtils::URLEncode(m_clusterIdentifier.c_str()) << "&";
  }

  ss << "Version=2012-12-01";
  return ss.str();
}

void  DisableLoggingRequest::DumpBodyToUrl(Aws::Http::URI& uri ) const
{
  uri.SetQueryString(SerializePayload());
}


text:
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TankScroller.Componentes
{
    public class Tank : Sprite
    {
        private Sprite turret;

        public Tank(ContentManager content) : base(content, "tank_body")
        {
            this.turret = new Sprite(content, "tank_turret");
            this.turret.SetRotation(MathHelper.PiOver4);
        }

        public override void Draw(GameTime gameTime)
        {
            base.Draw(gameTime);
            turret.Draw(gameTime);
        }

        public override void SetCena(Cena cena)
        {
            this.cena = cena;
            turret.SetCena(cena);
        }

        public override void Update(GameTime gameTime)
        {
            KeyboardState state = Keyboard.GetState();
            if (state.IsKeyDown(Keys.W))
            {
                this.position.Y += 0.02f;
            }
            if (state.IsKeyDown(Keys.S))
            {
                this.position.Y -= 0.02f;
            }

            turret.SetPosition(this.position);

            Camara.Target = this.position;

            turret.Update(gameTime);
            base.Update(gameTime);
        }
    }
}


text:
require 'china_region_fu/helpers/utilities'

module ChinaRegionFu
  module SimpleForm
    class RegionInput < ::SimpleForm::Inputs::CollectionInput
      include ChinaRegionFu::Utilities

      def input
        label_method, value_method = detect_collection_methods
        append_region_class(input_html_options)
        set_html_options(object_name, attribute_name, input_html_options, input_options.delete(:sub_region)) if input_options.key?(:sub_region)
        region_collection = collection
        region_collection = [] if region_collection == ::SimpleForm::Inputs::CollectionInput.boolean_collection
        @builder.collection_select(
          attribute_name, region_collection, value_method, label_method,
          input_options, input_html_options
        )
      end
    end
  end
end

::SimpleForm::FormBuilder.map_type :region, to: ChinaRegionFu::SimpleForm::RegionInput


text:
module Tools
   class Base
      def initialize(msg)
          puts 'initialize parent constructor method'+msg
      end
   end
end


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Gallery_model extends CI_Model {

	public function all()
	{
		$result = $this->db->get('gallery');
		return $result;
	}

	public function find($id)
	{
		$row = $this->db->where('id',$id)->limit(1)->get('gallery');
		return $row;
	}

	public function create($data)
	{
		try{
			$this->db->insert('gallery', $data);
			return true;
		}catch(Exception $e){
			return $e;
		}
	}

	public function update($id, $data)
	{
		try{
			$this->db->where('id',$id)->limit(1)->update('gallery', $data);
			return true;
		}catch(Exception $e){
			return $e;
		}
	}

	public function delete($id)
	{
		try {
			$this->db->where('id',$id)->delete('gallery');
			return true;
		}

		//catch exception
		catch(Exception $e) {
		  echo $e->getMessage();
		}
	}

}


text:
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-|
Module      : Game.GoreAndAsh.GLFW.API
Description : Monadic and arrow API for GLFW core module
Copyright   : (c) Anton Gushcha, 2015-2016
License     : BSD3
Maintainer  : ncrashed@gmail.com
Stability   : experimental
Portability : POSIX

The module contains monadic and arrow API of the core module.
-}
module Game.GoreAndAsh.GLFW.API(
    MonadGLFW(..)
  -- * Keyboard API
  , keyStatus
  , keyStatusDyn
  , keyPressed
  , keyPressedDyn
  , keyReleased
  , keyReleasedDyn
  , keyRepeating
  , keyRepeatingDyn
  , keyPressing
  , keyPressingDyn
  -- * Mouse buttons API
  , mouseButton
  , mouseButtonDyn
  , mouseButtonPressed
  , mouseButtonPressedDyn
  , mouseButtonReleased
  , mouseButtonReleasedDyn
  -- * Cursor position
  , mousePosition
  , mousePositionChange
  , mouseXChange
  , mouseYChange
  , mouseDelta
  , mouseDeltaChange
  , mouseDeltaXChange
  , mouseDeltaYChange
  -- * Mouse scroll
  , mouseScroll
  , mouseScrollX
  , mouseScrollY
  -- * Window API
  , windowSize
  , windowClosing
  -- * Reexports
  , Key(..)
  , KeyState(..)
  , MouseButton(..)
  , MouseButtonState(..)
  , ModifierKeys(..)
  ) where

import Prelude hiding (id, (.))
import Control.Wire

import Control.Monad.State.Strict
import Control.Wire.Unsafe.Event
import Graphics.UI.GLFW
import qualified Data.HashMap.Strict as M

import Game.GoreAndAsh
import Game.GoreAndAsh.GLFW.State
import Game.GoreAndAsh.GLFW.Module

-- | Module low-level API
class Monad m => MonadGLFW m where
  -- | Returns state of given keyboard's key
  keyStatusM :: Key -> m (Maybe (KeyState, ModifierKeys))
  -- | Returns state of given mouse button
  mouseButtonM :: MouseButton -> m (Maybe (MouseButtonState, ModifierKeys))
  -- | Returns current position of mouse cursor
  mousePosM :: m (Double, Double)
  -- | Returns current scroll values of mouse
  mouseScrollM :: m [(Double, Double)]
  -- | Returns current size of window
  windowSizeM :: m (Maybe (Double, Double))
  -- | Returns True when close button is pushed
  windowClosingM :: m Bool
  -- | Setups current window for input catch
  setCurrentWindowM :: Maybe Window -> m ()
  -- | Returns current window
  getCurrentWindowM :: m (Maybe Window)
  -- | Setup maximum size of inner buffers for keys, mouse buttons
  setBufferSizeM :: Int -> m ()

instance {-# OVERLAPPING #-} Monad m => MonadGLFW (GLFWT s m) where
  keyStatusM k = do
    GLFWState{..} <- GLFWT get
    return $ M.lookup k glfwKeys

  mouseButtonM b = do
    GLFWState{..} <- GLFWT get
    return $ M.lookup b glfwMouseButtons

  mousePosM = GLFWT $ glfwMousePos <$> get
  mouseScrollM = GLFWT $ glfwScroll <$> get
  windowSizeM = GLFWT $ glfwWindowSize <$> get
  windowClosingM = GLFWT $ glfwClose <$> get

  setCurrentWindowM w = GLFWT $ do
    s <- get
    put $ s {
        glfwWindow = w
      , glfwPrevWindow = glfwWindow s
      }

  getCurrentWindowM = GLFWT $ do
    s <- get
    return . glfwWindow $! s

  setBufferSizeM i = GLFWT $ do
    s <- get
    put $ s {
        glfwBufferSize = i
      }

instance {-# OVERLAPPABLE #-} (Monad (mt m), MonadGLFW m, MonadTrans mt) => MonadGLFW (mt m) where
  keyStatusM = lift . keyStatusM
  mouseButtonM = lift . mouseButtonM
  mousePosM = lift mousePosM
  mouseScrollM = lift mouseScrollM
  windowSizeM = lift windowSizeM
  windowClosingM = lift windowClosingM
  setCurrentWindowM = lift . setCurrentWindowM
  getCurrentWindowM = lift getCurrentWindowM
  setBufferSizeM = lift . setBufferSizeM

-- | Produces event when key state changes
keyStatus :: MonadGLFW m => Key -> GameWire m a (Event (KeyState, ModifierKeys))
keyStatus k = liftGameMonad (maybe2Event <$> keyStatusM k)

-- | Produces event when key state changes, get key as arrow argument
keyStatusDyn :: MonadGLFW m => GameWire m Key (Event (KeyState, ModifierKeys))
keyStatusDyn = liftGameMonad1 $ \k -> do
  ms <- keyStatusM k
  return $ maybe2Event ms

-- | Simple transform from maybe to event
maybe2Event :: Maybe a -> Event a
maybe2Event Nothing = NoEvent
maybe2Event (Just a) = Event a

keyStated :: MonadGLFW m => KeyState -> Key -> GameWire m a (Event ModifierKeys)
keyStated ks k = mapE snd . filterE (\(ks', _) -> ks' == ks) . keyStatus k

keyStatedDyn :: MonadGLFW m => KeyState -> GameWire m Key (Event ModifierKeys)
keyStatedDyn ks = mapE snd . filterE (\(ks', _) -> ks' == ks) . keyStatusDyn

-- | Fires when keyboard key is pressed
keyPressed :: MonadGLFW m => Key -> GameWire m a (Event ModifierKeys)
keyPressed = keyStated KeyState'Pressed

-- | Version of keyPressed that takes key at runtime
keyPressedDyn :: MonadGLFW m => GameWire m Key (Event ModifierKeys)
keyPressedDyn = keyStatedDyn KeyState'Pressed

-- | Fires when keyboard key is released
keyReleased :: MonadGLFW m => Key -> GameWire m a (Event ModifierKeys)
keyReleased = keyStated KeyState'Released

-- | Version of keyReleased that takes key at runtime
keyReleasedDyn :: MonadGLFW m => GameWire m Key (Event ModifierKeys)
keyReleasedDyn = keyStatedDyn KeyState'Released

-- | Fires when keyboard key is entered into repeating mode
keyRepeating :: MonadGLFW m => Key -> GameWire m a (Event ModifierKeys)
keyRepeating = keyStated KeyState'Repeating

-- | Version of keyRepeating that takes key at runtime
keyRepeatingDyn :: MonadGLFW m => GameWire m Key (Event ModifierKeys)
keyRepeatingDyn = keyStatedDyn KeyState'Repeating

-- | Fires event from moment of press until release of given key
keyPressing :: MonadGLFW m => Key -> GameWire m a (Event ModifierKeys)
keyPressing k = go NoEvent
  where
    go !e = mkGen $ \_ _ -> do
      !mks <- keyStatusM k
      return $! case mks of
        Nothing -> (Right e, go e)
        Just (!ks, !mds) -> case ks of
          KeyState'Pressed -> (Right $! Event mds, go $! Event mds)
          KeyState'Released -> (Right NoEvent, go NoEvent)
          _ -> (Right e, go e)

-- | Version of keyPressing that takes key at runtime
keyPressingDyn :: MonadGLFW m => GameWire m Key (Event ModifierKeys)
keyPressingDyn = go NoEvent
  where
    go !e = mkGen $ \_ k -> do
      !mks <- keyStatusM k
      return $! case mks of
        Nothing -> (Right e, go e)
        Just (!ks, !mds) -> case ks of
          KeyState'Pressed -> (Right $! Event mds, go $! Event mds)
          KeyState'Released -> (Right NoEvent, go NoEvent)
          _ -> (Right e, go e)

-- | Produces event when mouse button state changes
mouseButton :: MonadGLFW m => MouseButton -> GameWire m a (Event (MouseButtonState, ModifierKeys))
mouseButton k = liftGameMonad (maybe2Event <$> mouseButtonM k)

-- | Produces event when key state changes, get key as arrow argument
mouseButtonDyn :: MonadGLFW m => GameWire m MouseButton (Event (MouseButtonState, ModifierKeys))
mouseButtonDyn = liftGameMonad1 $ \k -> do
  ms <- mouseButtonM k
  return $ maybe2Event ms

mouseButtonStated :: MonadGLFW m => MouseButtonState -> MouseButton -> GameWire m a (Event ModifierKeys)
mouseButtonStated bs b = mapE snd . filterE (\(bs', _) -> bs == bs') . mouseButton b

mouseButtonStatedDyn :: MonadGLFW m => MouseButtonState -> GameWire m MouseButton (Event ModifierKeys)
mouseButtonStatedDyn bs = mapE snd . filterE (\(bs', _) -> bs == bs') . mouseButtonDyn

-- | Fires when mouse button is pressed
mouseButtonPressed :: MonadGLFW m => MouseButton -> GameWire m a (Event ModifierKeys)
mouseButtonPressed = mouseButtonStated MouseButtonState'Pressed

-- | Version of mouseButtonPressed that takes button at runtime
mouseButtonPressedDyn :: MonadGLFW m => GameWire m MouseButton (Event ModifierKeys)
mouseButtonPressedDyn = mouseButtonStatedDyn MouseButtonState'Pressed

-- | Fires when mouse button is released
mouseButtonReleased :: MonadGLFW m => MouseButton -> GameWire m a (Event ModifierKeys)
mouseButtonReleased = mouseButtonStated MouseButtonState'Released

-- | Version of mouseButtonReleased that takes button at runtime
mouseButtonReleasedDyn :: MonadGLFW m => GameWire m MouseButton (Event ModifierKeys)
mouseButtonReleasedDyn = mouseButtonStatedDyn MouseButtonState'Released

-- | Returns current position of mouse
mousePosition :: MonadGLFW m => GameWire m a (Double, Double)
mousePosition = liftGameMonad mousePosM

-- | Fires event when mouse position changes
mousePositionChange :: MonadGLFW m => GameWire m a (Event (Double, Double))
mousePositionChange = go 0 0
  where
    go !x !y = mkGen $ \_ _-> do
      (!x', !y') <- mousePosM
      return $ if x /= x' || y /= y'
        then (Right $! Event (x', y'), go x' y')
        else (Right NoEvent, go x y)

-- | Fires event when mouse X axis changes
mouseXChange :: MonadGLFW m => GameWire m a (Event Double)
mouseXChange = go 0
  where
    go !x = mkGen $ \_ _-> do
      (!x', _) <- mousePosM
      return $ if x /= x'
        then (Right $! Event x', go x')
        else (Right NoEvent, go x)

-- | Fires event when mouse Y axis changes
mouseYChange :: MonadGLFW m => GameWire m a (Event Double)
mouseYChange = go 0
  where
    go !y = mkGen $ \_ _-> do
      (_, !y') <- mousePosM
      return $ if y /= y'
        then (Right $! Event y', go y')
        else (Right NoEvent, go y)

-- | Returns mouse delta moves
mouseDelta :: MonadGLFW m => GameWire m a (Double, Double)
mouseDelta = go 0 0
  where
    go !x !y = mkGen $ \_ _ -> do
      (!x', !y') <- mousePosM
      let dx = x' - x
          dy = y' - y
          res = Right (dx, dy)
      return $ dx `seq` dy `seq` (res, go x' y')

-- | Fires when mouse moves, holds delta move
mouseDeltaChange :: MonadGLFW m => GameWire m a (Event (Double, Double))
mouseDeltaChange = go 0 0
  where
    go !x !y = mkGen $ \_ _ -> do
      (!x', !y') <- mousePosM
      let dx = x' - x
          dy = y' - y
          res = Right $! Event (dx, dy)
      return $ if x /= x' || y /= y'
        then dx `seq` dy `seq` (res, go x' y')
        else (Right NoEvent, go x y)

-- | Fires when mouse X axis changes, holds delta move
mouseDeltaXChange :: MonadGLFW m => GameWire m a (Event Double)
mouseDeltaXChange = go 0
  where
    go !x = mkGen $ \_ _ -> do
      (!x', _) <- mousePosM
      let dx = x' - x
          res = Right $! Event dx
      return $ if x /= x'
        then dx `seq` (res, go x')
        else (Right NoEvent, go x)

-- | Fires when mouse Y axis changes, holds delta move
mouseDeltaYChange :: MonadGLFW m => GameWire m a (Event Double)
mouseDeltaYChange = go 0
  where
    go !y = mkGen $ \_ _ -> do
      (_, !y') <- mousePosM
      let dy = y' - y
          res = Right $! Event dy
      return $ if y /= y'
        then dy `seq` (res, go y')
        else (Right NoEvent, go y)

-- | Fires when windows size is changed
windowSize :: MonadGLFW m => GameWire m a (Event (Double, Double))
windowSize = go 0 0
  where
    go !x !y = mkGen $ \_ _ -> do
      ms <- windowSizeM
      return $! case ms of
        Nothing -> (Right NoEvent, go x y)
        Just (!x', !y') -> if x /= x' || y /= y'
          then x' `seq` y' `seq` (Right $! Event (x', y'), go x' y')
          else (Right NoEvent, go x y)

-- | Fires when user scrolls
mouseScroll :: MonadGLFW m => GameWire m a (Event (Double, Double))
mouseScroll = mkGen_ $ \_ -> do
  ss <- mouseScrollM
  return . Right $! case ss of
    [] -> NoEvent
    ((!x', !y'):_) -> Event (x', y')

-- | Fires when user scrolls X axis
mouseScrollX :: MonadGLFW m => GameWire m a (Event Double)
mouseScrollX = mapE fst . mouseScroll

-- | Fires when user scrolls Y axis
mouseScrollY :: MonadGLFW m => GameWire m a (Event Double)
mouseScrollY = mapE snd . mouseScroll

-- | Fires when user hits close button of window
windowClosing :: MonadGLFW m => GameWire m a (Event ())
windowClosing = liftGameMonad $ do
  f <- windowClosingM
  return $! if f then Event ()
    else NoEvent


text:
<##############################################################################
Ashley McGlone
Microsoft Premier Field Engineer

Function library for working with Active Directory snapshots and attribute-
level object recovery.

Prerequisites:  PowerShell v2 (v3+ required for Mount-ADSnapshot -Filter)
                Domain controller running AD Web Service (2008 R2+)
                Domain controller with remoting enabled if running remotely

dir function: | ? name -like "*ad*"

CommandType     Name
-----------     ----
Function        Dismount-ADDatabase
Function        Mount-ADDatabase
Function        New-ADSnapshot
Function        Remove-ADSnapshot
Function        Repair-ADAttribute
Function        Repair-ADUserGroup
Function        Show-ADSnapshot

LEGAL DISCLAIMER
This Sample Code is provided for the purpose of illustration only and is not
intended to be used in a production environment.  THIS SAMPLE CODE AND ANY
RELATED INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.  We grant You a
nonexclusive, royalty-free right to use and modify the Sample Code and to
reproduce and distribute the object code form of the Sample Code, provided
that You agree: (i) to not use Our name, logo, or trademarks to market Your
software product in which the Sample Code is embedded; (ii) to include a valid
copyright notice on Your software product in which the Sample Code is embedded;
and (iii) to indemnify, hold harmless, and defend Us and Our suppliers from and
against any claims or lawsuits, including attorneys' fees, that arise or result
from the use or distribution of the Sample Code.

This posting is provided "AS IS" with no warranties, and confers no rights. Use
of included script samples are subject to the terms specified
at http://www.microsoft.com/info/cpyright.htm.
##########################################################################sdg#>

# For PSv2
Import-Module ActiveDirectory

Function New-ADSnapshot {
<#
.SYNOPSIS
   Creates a new Active Directory database snapshot.
.DESCRIPTION
   Uses NTDSUTIL to create a new Active Directory database snapshot.
   NTDSUTIL "Activate Instance NTDS" SNAPSHOT CREATE
.EXAMPLE
   New-ADSnapshot
.NOTES
   This cmdlet targets the local machine.  It must execute locally on a domain controller either through a local or remote PowerShell session.
.LINK
   http://aka.ms/GoateePFE
#>
Param()

    ntdsutil "Activate Instance NTDS" snapshot create quit quit
}

Function Mount-ADDatabase {
<#
.SYNOPSIS
   Mounts an Active Directory snapshot and the database it contains.
.DESCRIPTION
   Uses the NTDSUTIL SNAPSHOT MOUNT command to mount the snapshot.
   Uses DSAMAIN.EXE to mount the database contained in the snapshot.
   Parameters define which snapshot and port to use.
.PARAMETER LDAPPort
   Port for DSAMAIN to advertise the database.
   Must be in the range 1025 to 65535.
   Checks to make sure another database is not already using the port.
   The other ports use (SSL) LDAP+1, (GC) LDAP+2, and (GC-SSL) LDAP+3.
   For more information on DSAMAIN see the TechNet link in the Links portion of this help topic.
.PARAMETER Filter
   Prompts the user for which snapshot to mount.
   Does not work over a remote session.
   Requires PowerShell v3 or above.
.PARAMETER First
   Automatically mounts the first (oldest) snapshot.
.PARAMETER Last
   Automatically mounts the last (newest) snapshot.
.EXAMPLE
   Mount-ADDatabase -Filter -LDAPPort 33389
.EXAMPLE
   Mount-ADDatabase -First -LDAPPort 33389
.EXAMPLE
   Mount-ADDatabase -Last -LDAPPort 33389
.NOTES
   This cmdlet will launch the DSAMAIN process in a separate window.  This window must remain open throughout the snapshot usage.  To close it use the cmdlet Dismount-ADDatabase.
.LINK
   http://aka.ms/GoateePFE
.LINK
   http://technet.microsoft.com/en-us/library/cc772168(v=ws.10).aspx
#>
Param (
    [parameter(Mandatory=$true)]
    [ValidateScript({
        # Must specify an LDAP port not in use
        $x = $null
        Try {$x = Get-ADRootDSE -Server localhost:$_}
        Catch {$null}
        If ($x) {$false} Else {$true}
    })]
    [ValidateRange(1025,65535)]
    [int]
    $LDAPPort,
    [parameter(Mandatory=$true,
               ParameterSetName="Filter")]
    [ValidateScript({$Host.Name -ne 'ServerRemoteHost'})]
    [switch]$Filter,
    [parameter(Mandatory=$true,
               ParameterSetName="First")]
    [switch]$First,
    [parameter(Mandatory=$true,
               ParameterSetName="Last")]
    [switch]$Last
)
    # Parse snapshot list
    $snaps = ntdsutil snapshot "list all" quit quit
    If ($First) {
        # Pick the first snapshot in the list
        # Use @() in case a single row comes back for PSv2
        $ChoiceNumber = (@(($snaps | Select-String -SimpleMatch '/'))[0] -split ':')[0].Trim()
    } ElseIf ($Last) {
        # Pick the last snapshot in the list
        # Use @() in case a single row comes back for PSv2
        $ChoiceNumber = (@(($snaps | Select-String -SimpleMatch '/'))[-1] -split ':')[0].Trim()
    } Else {
        $Choice = $snaps | Select-String -SimpleMatch '/' |
            Select-Object -ExpandProperty Line |
            Out-GridView -Title 'Select the snapshot to mount' -OutputMode Single
        If ($Choice -eq $null) {
            # What if the user hits the Cancel button in the OGV?
            Exit
        } Else {
            $ChoiceNumber = ($Choice -split ':')[0].Trim()
        }
    }

    # Mount Snapshot
    $Mount = ntdsutil snapshot "list all" "mount $ChoiceNumber" quit quit
    # If already mounted, will return "Snapshot {1753bd1a-7905-4e2b-a976-254198a3fe3e} is already mounted."
    $MountPath = (($Mount | Select-String -SimpleMatch 'mounted as') -split 'mounted as')[-1].Trim()
    $DITPath = (Get-Item -Path "HKLM:\SYSTEM\CurrentcontrolSet\Services\NTDS\Parameters").GetValue("DSA Database File").SubString(2)
    $NTDSdit = Join-Path -Path $MountPath -ChildPath $DITPath

    # Mounted snapshots show up in the ExposedName column
    $MountedWMI  = Get-WmiObject Win32_ShadowCopy | Select-Object Id, Installdate, OriginatingMachine, ClientAccessible, NoWriters, ExposedName
    $MountedNTDS = ntdsutil snapshot "list mounted" quit quit

    # Mount the database in the snapshot
    # Start in its own process, because it must continue to run in the background.
    Write-Host 'Mounting database: .' -NoNewline
    $DSAMAIN = Start-Process -FilePath dsamain.exe -ArgumentList "-dbpath $NTDSdit -ldapport $LDAPPort" -PassThru

    # Wait for database mount to complete
    # Get-ADRootDSE does not seem to obey the ErrorAction parameter
    $ErrorActionPreference = 'SilentlyContinue'
    $d = $null
    Do {
        $d = Get-ADRootDSE -Server localhost:$LDAPPort
        Start-Sleep -Seconds 1
        Write-Host '.' -NoNewline
    }
    Until ($d)
    Write-Host '.'
    $ErrorActionPreference = 'Continue'

    If ($Verbose) {
        $MountedWMI | Format-Table Id, Installdate, OriginatingMachine, ClientAccessible, NoWriters, ExposedName -AutoSize
        $MountedNTDS
        $DSAMAIN
    }
}

Function Dismount-ADDatabase {
<#
.SYNOPSIS
   Dismounts the Active Directory database and the snapshot that contained it.
.DESCRIPTION
   Uses NTDSUTIL to dismount the Active Directory database and the snapshot that contained it.
   This is a two-step process:
   1. Stop the DSAMAIN instance of the database.
   2. Unmount the snapshot using NTDSUTIL SNAPSHOT UNMOUNT.
.EXAMPLE
   Dismount-ADDatabase
.NOTES
   This cmdlet will dismount all currently-mounted Active Directory database snapshots.
.LINK
   http://aka.ms/GoateePFE
#>
Param()
    # Dismount the database
    Get-Process dsamain -ErrorAction SilentlyContinue | Stop-Process

    # Unmount snapshot
    # $ChoiceNumber no longer cooresponds here, because the list is different
    ntdsutil snapshot "list mounted" "unmount *" quit quit

}

Function Show-ADSnapshot {
<#
.SYNOPSIS
   Lists the snapshots available on the Active Directory domain controller.
.DESCRIPTION
   Lists the snapshots using one of two methods:
   1. (Default) NTDSUTIL SNAPSHOT LIST ALL
   2. Get-WMIObject Win32_ShadowCopy
.PARAMETER WMI
   Switch to display output from WMI instead of NTDSUTIL.
.EXAMPLE
   Show-ADSnapshot
.EXAMPLE
   Show-ADSnapshot -WMI
.NOTES
   Either view will designate snapshots that are already mounted.
   The WMI version will show VolumeShadow backups outside of NTDSUTIL SNAPSHOT as ClientAccessible=True.
   These are reported as FYI and out-of-scope for NTDSUTIL Active Directory snapshots.
.LINK
   http://aka.ms/GoateePFE
#>
Param (
    [switch]$WMI
)
    If ($WMI) {
        Get-WmiObject Win32_ShadowCopy | Select-Object Id,  @{name='Install_Date';expression={$_.ConvertToDateTime($_.InstallDate)}}, OriginatingMachine, ClientAccessible, NoWriters, ExposedName | Sort-Object Install_Date
    } Else {
        ntdsutil snapshot "list all" quit quit
    }
}

Function Remove-ADSnapshot {
<#
.SYNOPSIS
   Deletes local Active Directory database snapshots.
.DESCRIPTION
   Uses NTDSUTIL to delete local Active Directory database snapshots.
   NTDSUTIL SNAPSHOT DELETE
.PARAMETER All
   Delete all snapshots.
.PARAMETER Keep
   Specify a number of snapshots to keep and delete the remainder.
.PARAMETER First
   Keeps the first (oldest) snapshots.
.PARAMETER Last
   Keeps the last (newest) snapshots.
.EXAMPLE
   Remove-ADSnapshot -Keep 5 -First
.EXAMPLE
   Remove-ADSnapshot -Keep 5 -Last
.EXAMPLE
   Remove-ADSnapshot -All
.NOTES
   If Active Directory snapshots are scheduled on a regular basis according to best practice, then they must also be pruned to prevent disk space issues.
   Run this cmdlet before or after New-ADSnapshot to remove older snapshots.
.LINK
   http://aka.ms/GoateePFE
#>
Param(
    [parameter(Mandatory=$true,
               ParameterSetName="All")]
    [switch]$All,
    [parameter(Mandatory=$true,
               ParameterSetName="First")]
    [parameter(Mandatory=$true,
               ParameterSetName="Last")]
    [int]$Keep,
    [parameter(Mandatory=$true,
               ParameterSetName="First")]
    [switch]$First,
    [parameter(Mandatory=$true,
               ParameterSetName="Last")]
    [switch]$Last
)

    If ($All) {
        ntdsutil snapshot "list all" "delete *" quit quit
    } Else {
        # Decide which array index to delete, first or last.
        # If keeping first x, then trim last.
        # If keeping last x,  then trim first.
        $snaps = ntdsutil snapshot "list all" quit quit
        $snapsArray = @(($snaps | Select-String -SimpleMatch '/'))
        If ($snapsArray.Count -gt $Keep) {
            If ($First) {$DeleteMe = -1} Else {$DeleteMe = 0}
            While ($snapsArray.count -gt $Keep) {
                $ChoiceNumber = ($snapsArray[$DeleteMe] -split ':')[0].Trim()
                ntdsutil snapshot "list all" "delete $ChoiceNumber" quit quit
                $snaps = ntdsutil snapshot "list all" quit quit
                $snapsArray = @(($snaps | Select-String -SimpleMatch '/'))
            }
        } Else {
            "No snapshots to delete in that range."
        }
    }

}

Function Repair-ADAttribute {
<#
.SYNOPSIS
   Copies one or more object attributes from the database snapshot version into the same attribute in the live copy of the Active Directory database.
.DESCRIPTION
   Effectively this cmdlet does an attribute-level restore for an object by rewriting the old values over the new values.
.PARAMETER Property
   One or more Active Directory attribute names delimited by commas.
   The attribute name must be valid and must be writable.
   Supports single-value and multi-value attributes.
.PARAMETER ObjectGUID
   ObjectGUID of the Active Directory object for attribute recovery.
   It is preferred to pipe this from another cmdlet (Get-ADUser, Get-ADObject, etc.).
   This parameter accepts pipeline input and can run against multiple objects.
   ObjectGUID is used instead of DistinguishedName in case the object path has changed since the snapshot.
.PARAMETER LDAPPort
   Must be the LDAPPort of a previously-mounted database snapshot.
   Must be in the range 1025 to 65535.
.EXAMPLE
   Get-ADUser Guest | Repair-ADAttribute -Property Description -LDAPPort 33389
.EXAMPLE
   Get-ADUser -filter {name -like "G*"} | Repair-ADAttribute -Property Department,Description -LDAPPort 33389
.EXAMPLE
   Get-ADUser -filter {name -like "*bad_data*"} | Repair-ADAttribute -Property Department,Description -LDAPPort 33389
.EXAMPLE
   Get-ADUser -filter {name -like "*good_data*"} -Server Localhost:33389 | Repair-ADAttribute -Property Department,Description -LDAPPort 33389
.EXAMPLE
   Get-ADComputer Server1 | Repair-ADAttribute -Property ServicePrincipalName -LDAPPort 33389
.EXAMPLE
   Get-ADComputer -Filter * | Repair-ADAttribute -Property Description,ServicePrincipalName -LDAPPort 33389
.EXAMPLE
   Get-ADGroup "Domain Admins" | Repair-ADAttribute -Property member -LDAPPort 33389
.INPUTS
   Active Directory object(s) containing the ObjectGUID attribute.
.OUTPUTS
   PowerShell custom object for logging with these properties:
     ObjGUID   : ObjectGUID attribute of the object for repair
     NewObject : DistinguishedName of the object located in the current database
     OldObject : DistinguishedName of the object located in the snapshot database
     NewValue  : Value of the property in the current database
     OldValue  : Value of the property in the snapshot database
     Property  : AD attribute name for repair
     Action    : Describes the repair action taken: Added, Removed, Replaced, Not Found
     Moved     : Is the DistinguishedName of the two object copies different? IE. Was it moved or renamed between the snapshot and current?
.NOTES
   This cmdlet compares snapshot (old) and current (new) values for the specified property or properties.  There are four possible outcomes:
   1.  Values are equal.  No change.
   2.  Values are not equal.  Change the current value to match the snapshot value.
   3.  Snapshot object is not found in current database.  No change.
   4.  Current object is not found in snapshot database.  No change.
   Items number 3 and 4 may occur if the object has been deleted or created since the snapshot.

   When you pipe to this cmdlet the source of objects will come from either the snapshot or the current database.  There are multiple ways to use it.  Here are some examples:
   -Get corrupted objects from the current database.  Filter on the known bad data.  Pipe to this cmdlet.
   -Get known good objects from the snapshot database.  Filter on the known good data.  Pipe to this cmdlet.
.LINK
   http://aka.ms/GoateePFE
#>
[CmdletBinding(SupportsShouldProcess=$true)]
Param(
    [parameter(Mandatory=$true)]
    [String[]]
    $Property,
    [parameter(Mandatory=$true,
               ValueFromPipelineByPropertyName=$true)]
    [String]
    $ObjectGUID,
    [parameter(Mandatory=$true)]
    [ValidateScript({
        # Must specify an LDAP snapshot port in use
        $x = $null
        Try {$x = Get-ADRootDSE -Server localhost:$_}
        Catch {$null}
        If ($x) {$true} Else {$false}
    })]
    [ValidateRange(1025,65535)]
    [int]
    $LDAPPort
)

Begin {}

Process {
    # Query the mounted database snapshot
    # Compare old and current values for property
    # Possible outcomes:
    #  -match
    #  -notmatch
    #  -object no longer exists in snapshot (Object piped in from current)
    #  -object no longer exists in current  (Object piped in from snapshot query)

    # User ObjectGUID to locate the objects, because the DistinguishedName path
    # could change by the object being moved, renamed, or deleted.
    $Identity  = $_.ObjectGUID

    # We don't know where the object is piped from (snaphot or current).
    # We cannot guarantee that it exists in both places.
    # Does the object exist in both the snapshot and the current directory?
    # OLD
    try   { $OldObject = Get-ADObject -Identity $Identity -Properties $Property -Server localhost:$LDAPPort }
    catch { $OldObject = $null }
    # NEW
    try   { $NewObject = Get-ADObject -Identity $Identity -Properties $Property -Server localhost }
    catch { $NewObject = $null }

    If (($OldObject -eq $null) -or ($NewObject -eq $null)) {

        # Which database is missing the object?
        # If both, then default to reporting only Current (bad input, rare).
        If ($OldObject) {$Database = 'Current'} Else {$Database = 'Snapshot'}

        # Old object not present in new database
        New-Object -TypeName PSObject -Property @{
            ObjGUID   = $Identity
            OldObject = $OldObject.DistinguishedName
            NewObject = $NewObject.DistinguishedName
            Moved     = ($OldObject.DistinguishedName -ne $NewObject.DistinguishedName)
            Property  = $null
            OldValue  = $null
            NewValue  = $null
            Action    = "Not Found in $Database"
        }

    } Else {

        # Found in both databases

        # Loop through each property in the list
        ForEach ($PropertyEach in $Property) {

            # Get the old property value
            try {
                # If the property value returns null, then Select-Object -ExpandProperty errors.
                # Select-Object does not seem to obey when you specify -ErrorAction SilentlyContinue.
                $OldValue = $null = $OldObject | Select-Object -ExpandProperty $PropertyEach
                #$OldValue = $OldObject.Item($PropertyEach)
            } catch {
                $OldValue = $null
            }

            try {
                # If the property value returns null, then Select-Object -ExpandProperty errors.
                # Select-Object does not seem to obey when you specify -ErrorAction SilentlyContinue.
                $NewValue = $null = $NewObject | Select-Object -ExpandProperty $PropertyEach
                #$NewValue = $NewObject.Item($PropertyEach)
            } catch {
                $NewValue = $null
            }

            If ($OldValue -eq $NewValue) {

                # Matching values
                # PSv2 New-Object for compatibility instead of [PSCustomObject] in v3+
                New-Object -TypeName PSObject -Property @{
                    ObjGUID   = $Identity
                    OldObject = $OldObject.DistinguishedName
                    NewObject = $NewObject.DistinguishedName
                    Moved     = ($OldObject.DistinguishedName -ne $NewObject.DistinguishedName)
                    Property  = $PropertyEach
                    OldValue  = $OldValue
                    NewValue  = $NewValue
                    Action    = 'No Change'
                }

            } Else {

                # Is this a multi-value attribute?
                $PropertyDefinition = $OldObject | Get-Member -MemberType Property | Where-Object {$_.Name -eq $PropertyEach} | Select-Object -ExpandProperty Definition
                If ($PropertyDefinition -like "*Microsoft.ActiveDirectory.Management.ADPropertyValueCollection*") {

                    # MULTI-VALUE
                    # Do a proper true-up of individual multi-values.
                    # Multivalue attributes cannot be directly compared as whole values,
                    # because the individual values are listed in different orders,
                    # making the two object properties always look different.
                    # If either of the values are NULL, then Compare-Object will error.
                    # If there are values on both sides and it is multivalue, then we want to surgically add/remove the respective individual values.
                    # For example, this can become a big deal when working with groups containing 1000s of users.  We don't want to rebuild the entire group membership.

                    If ($OldValue -eq $null) {
                        $ToRemove = $NewValue
                    } ElseIf ($NewValue -eq $null) {
                        $ToAdd    = $OldValue
                    } Else {
                        $Compare  = Compare-Object -ReferenceObject $OldValue -DifferenceObject $NewValue
                        $ToRemove = $Compare | Where-Object {$_.SideIndicator -eq '=>'} | Select-Object -ExpandProperty InputObject
                        $ToAdd    = $Compare | Where-Object {$_.SideIndicator -eq '<='} | Select-Object -ExpandProperty InputObject
                    }

                    If ($ToRemove -or $ToAdd) {

                        If ($ToRemove) { # If block added for PSv2 compatibility.

                            # Remove new values that were added
                            ForEach ($Value in $ToRemove) {
                                Set-ADObject -Identity $Identity -Remove @{$PropertyEach="$Value"}
                                New-Object -TypeName PSObject -Property @{
                                    ObjGUID   = $Identity
                                    OldObject = $OldObject.DistinguishedName
                                    NewObject = $NewObject.DistinguishedName
                                    Moved     = ($OldObject.DistinguishedName -ne $NewObject.DistinguishedName)
                                    Property  = $PropertyEach
                                    OldValue  = $null
                                    NewValue  = $Value
                                    Action    = 'Removed'
                                }
                            }
                        }

                        If ($ToAdd) {  # If block added for PSv2 compatibility.

                            # Add back old values that were deleted
                            ForEach ($Value in $ToAdd) {
                                Set-ADObject -Identity $Identity -Add @{$PropertyEach="$Value"}
                                New-Object -TypeName PSObject -Property @{
                                    ObjGUID   = $Identity
                                    OldObject = $OldObject.DistinguishedName
                                    NewObject = $NewObject.DistinguishedName
                                    Moved     = ($OldObject.DistinguishedName -ne $NewObject.DistinguishedName)
                                    Property  = $PropertyEach
                                    OldValue  = $Value
                                    NewValue  = $null
                                    Action    = 'Added'
                                }
                            }

                        }

                    } Else {

                        # Nothing to remove or add, so the two lists match.
                        # This is an equal multi-value property comparison.
                        # It is possible the multi-value property contents were already matched earlier
                        # in the logic if the data in each attribute was listed in the same order.
                        New-Object -TypeName PSObject -Property @{
                            ObjGUID   = $Identity
                            OldObject = $OldObject.DistinguishedName
                            NewObject = $NewObject.DistinguishedName
                            Moved     = ($OldObject.DistinguishedName -ne $NewObject.DistinguishedName)
                            Property  = $PropertyEach
                            OldValue  = $OldValue
                            NewValue  = $NewValue
                            Action    = 'No Change'
                        }

                    }

                } Else {

                    # Different values
                    If ($OldValue -eq $null) {
                        # -Replace cannot set a null value. Must use -Clear in that case.
                        #Set-ADObject -Server localhost -Identity $NewObject -Clear $PropertyEach
                        Set-ADObject -Server localhost -Identity $Identity -Clear $PropertyEach
                    } Else {
                        # This one line is the heart of the script.
                        # If only it all could have been this easy!  :-)
                        #Set-ADObject -Server localhost -Identity $NewObject -Replace @{$PropertyEach=$OldValue}
                        Set-ADObject -Server localhost -Identity $Identity -Replace @{"$PropertyEach"="$OldValue"}
                    }

                    New-Object -TypeName PSObject -Property @{
                        ObjGUID   = $Identity
                        OldObject = $OldObject.DistinguishedName
                        NewObject = $NewObject.DistinguishedName
                        Moved     = ($OldObject.DistinguishedName -ne $NewObject.DistinguishedName)
                        Property  = $PropertyEach
                        OldValue  = $OldValue
                        NewValue  = $NewValue
                        Action    = 'Replaced'
                    }

                } # End If Multi-value

            } # End If Old Equals New

        } # End ForEach

    } # End If

} # End Process

End {}

}

Function Repair-ADUserGroup {
<#
.SYNOPSIS
   Rewrites the MemberOf computed backlinks for a user's group memberships.
.DESCRIPTION
   Puts the user back into the groups where they were in the snapshot copy of the database.
.PARAMETER DistinguishedName
   DistinguishedName of the user to repair group membership.
.PARAMETER LDAPPort
   Must be the LDAPPort of a previously-mounted database snapshot.
   Must be in the range 1025 to 65535.
.EXAMPLE
   Get-ADUser Guest | Repair-ADUserGroup -LDAPPort 33389 -WhatIf
.EXAMPLE
   Get-ADUser Guest | Repair-ADUserGroup -LDAPPort 33389
.EXAMPLE
   Get-ADUser Guest | Repair-ADUserGroup -LDAPPort 33389 -Confirm:$False
.EXAMPLE
   Get-ADUser -Filter {Name -like "B*"} | Repair-ADUserGroup -LDAPPort 33389
.INPUTS
   It is preferred to query for a user or users and pipe them into the cmdlet.
.NOTES
   The MemberOf attribute is computed, and it is not an editable attribute.  In order to repair group memberships the user must be added or removed directly on each group object.
   This only works on groups in the same domain.  If you want to modify the code, then you must target a GC for Domain Local and other domain groups.  Then you must figure out the authentication to those other DCs.  You will need to adjust the -Server connection ports to hit GC 3268 and snapshot port +2 for snapshot GC port.
.LINK
   http://aka.ms/GoateePFE
#>
[CmdletBinding(SupportsShouldProcess=$true)]
Param(
    [parameter(Mandatory=$true,
               ValueFromPipelineByPropertyName=$true)]
    [String]
    $DistinguishedName,
    [parameter(Mandatory=$true)]
    [ValidateScript({
        # Must specify an LDAP snapshot port in use
        $x = $null
        Try {$x = Get-ADRootDSE -Server localhost:$_}
        Catch {$null}
        If ($x) {$true} Else {$false}
    })]
    [ValidateRange(1025,65535)]
    [int]
    $LDAPPort
)

    Begin {}

    Process {
        $OldGroups = Get-ADUser $_ -Properties memberOf -Server localhost:$LDAPPort | Select-Object -ExpandProperty MemberOf
        $NewGroups = Get-ADUser $_ -Properties memberOf -Server localhost | Select-Object -ExpandProperty MemberOf

        If ($OldGroups -eq $null) {
            $GroupsToRemove = $NewValue
        } ElseIf ($NewGroups -eq $null) {
            $GroupsToAdd    = $OldValue
        } Else {
            $Compare   = Compare-Object -ReferenceObject $OldGroups -DifferenceObject $NewGroups
            $GroupsToRemove = $Compare | Where-Object {$_.SideIndicator -eq '=>'} | Select-Object -ExpandProperty InputObject
            $GroupsToAdd    = $Compare | Where-Object {$_.SideIndicator -eq '<='} | Select-Object -ExpandProperty InputObject
        }

        If ($GroupsToRemove) { # If block added for PSv2 compatibility.
            ForEach ($Group in $GroupsToRemove) {
                Remove-ADGroupMember -Identity $Group -Members $_
                New-Object -TypeName PSObject -Property @{
                    Identity = $_
                    Group    = $Group
                    Action   = 'Removed'
                }
            }
        }

        If ($GroupsToAdd) { # If block added for PSv2 compatibility.
            ForEach ($Group in $GroupsToAdd) {
                Add-ADGroupMember -Identity $Group -Members $_
                New-Object -TypeName PSObject -Property @{
                    Identity = $_
                    Group    = $Group
                    Action   = 'Added'
                }
            }
        }

    }

    End {}

}


text:
package jpa.bean;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "\"test_entities\"")
public class Greeting {

	public Greeting() {
	}

	@Id
	@Column(name = "\"id\"", unique = true, nullable = false)
	private long id;

	@Column(name = "\"text\"")
	private String content;

	public Greeting(long id, String content) {
		this.id = id;
		this.content = content;
	}

	public long getId() {
		return id;
	}

	public String getContent() {
		return content;
	}
}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenTK.Graphics.OpenGL4;

namespace LightClaw.Engine.Graphics.OpenGL
{
    /// <summary>
    /// Represents a read-only OpenGL buffer, data in video memory.
    /// </summary>
    [ContractClass(typeof(IReadOnlyBufferContracts))]
    public interface IReadOnlyBuffer : IBindable, IGLObject
    {
        /// <summary>
        /// Gets the length of the buffer.
        /// </summary>
        int Length { get; }

        /// <summary>
        /// Gets the <see cref="BufferUsageHint"/>.
        /// </summary>
        BufferUsageHint Hint { get; }

        /// <summary>
        /// Gets the <see cref="BufferTarget"/> the <see cref="IBuffer"/> will be bound to..
        /// </summary>
        BufferTarget Target { get; }

        /// <summary>
        /// Binds the buffer.
        /// </summary>
        /// <returns>A <see cref="Binding"/> to release the buffer.</returns>
        Binding Bind();

        /// <summary>
        /// Gets all the data in the buffer.
        /// </summary>
        /// <remarks>
        /// This operation cannot be done asynchronously, thus it may seriously affect performance if called repeatedly!
        /// </remarks>
        /// <typeparam name="T">The <see cref="Type"/> to get the data as.</typeparam>
        /// <returns>The data inside the buffer as structs of the specified <see cref="Type"/>.</returns>
        T[] Get<T>() where T : struct;

        /// <summary>
        /// Gets a range of the buffers data.
        /// </summary>
        /// <remarks>
        /// This operation cannot be done asynchronously, thus it may seriously affect performance if called repeatedly!
        /// </remarks>
        /// <typeparam name="T">The <see cref="Type"/> to get the data as.</typeparam>
        /// <param name="offset">The offset (in bytes).</param>
        /// <param name="count">The amount of bytes to receive.</param>
        /// <returns>The data inside the buffer as structs of the specified <see cref="Type"/>.</returns>
        T[] GetRange<T>(int offset, int count) where T : struct;
    }

    [ContractClassFor(typeof(IReadOnlyBuffer))]
    abstract class IReadOnlyBufferContracts : IReadOnlyBuffer
    {
        int IReadOnlyBuffer.Length
        {
            get
            {
                return 0;
            }
        }

        int IGLObject.Handle
        {
            get
            {
                return 0;
            }
        }

        BufferUsageHint IReadOnlyBuffer.Hint
        {
            get
            {
                return 0;
            }
        }

        BufferTarget IReadOnlyBuffer.Target
        {
            get
            {
                return 0;
            }
        }

        Binding IReadOnlyBuffer.Bind()
        {
            return default(Binding);
        }

        T[] IReadOnlyBuffer.Get<T>()
        {
            Contract.Ensures(Contract.Result<T[]>() != null);

            return null;
        }

        T[] IReadOnlyBuffer.GetRange<T>(int offset, int count)
        {
            Contract.Requires<ArgumentOutOfRangeException>(offset >= 0);
            Contract.Requires<ArgumentOutOfRangeException>(count >= 0);
            Contract.Ensures(Contract.Result<T[]>() != null);

            return null;
        }

        void IBindable.Unbind() { }

        void IDisposable.Dispose() { }
    }
}


text:
class Blog < ActiveRecord::Base
  include Searchable
end


text:
#ifndef PAGESPEED_KERNEL_HTTP_HEADERS_H_
#define PAGESPEED_KERNEL_HTTP_HEADERS_H_

#include <map>
#include <utility>

#include "pagespeed/kernel/base/basictypes.h"
#include "pagespeed/kernel/base/proto_util.h"
#include "pagespeed/kernel/base/scoped_ptr.h"
#include "pagespeed/kernel/base/string.h"
#include "pagespeed/kernel/base/string_util.h"

namespace net_instaweb {

class MessageHandler;
class NameValue;
class StringMultiMapInsensitive;
class Writer;

// Read/write API for HTTP headers (shared base class)
template <class Proto>
class Headers {
 public:
  // typedef's for manipulating the cookie multimap.
  typedef std::pair<StringPiece, StringPiece> ValueAndAttributes;
  typedef std::multimap<StringPiece, ValueAndAttributes> CookieMultimap;
  typedef std::multimap<StringPiece, ValueAndAttributes>::const_iterator
      CookieMultimapConstIter;

  Headers();
  virtual ~Headers();

  virtual void Clear();

  int major_version() const;
  bool has_major_version() const;
  int minor_version() const;
  void set_major_version(int major_version);
  void set_minor_version(int major_version);

  // Raw access for random access to attribute name/value pairs.
  int NumAttributes() const;
  const GoogleString& Name(int i) const;
  const GoogleString& Value(int i) const;
  void SetValue(int i, StringPiece value);

  // Lookup attributes with provided name. Attribute values are stored in
  // values. Returns true iff there were any attributes with provided name.
  // Attributes that normally appear as a comma-separated header list
  // (Cache-Control, Accept, etc.) will yield multiple entries in *values.
  // Multiple occurrences of a header (Cookie, etc.) will also yield multiple
  // entries in *values.  In most cases (but not Cookies) the semantics are
  // equivalent either way.  See:
  //   http://tools.ietf.org/html/draft-ietf-httpbis-p1-messaging-26#section-3.2.2
  //
  // Note that Lookup, though declared const, is NOT thread-safe.  This
  // is because it lazily generates a map.
  // TODO(jmarantz): this is a problem waiting to happen, but I believe it
  // will not be a problem in the immediate future.  We can refactor our way
  // around this problem by moving the Map to an explicit separate class that
  // can be instantiated to assist with Lookups and Remove.  But that should
  // be done in a separate CL from the one I'm typing into now.
  bool Lookup(const StringPiece& name, ConstStringStarVector* values) const;

  // Synthesize a string that represents what all the values a header would
  // serialize to.  Returns "" if the header isn't present.
  //
  // Same constness warnings as for ResponseHeaders::Lookup() apply.
  GoogleString LookupJoined(StringPiece name) const;

  // Looks up a single attribute value.  Returns NULL if the attribute is not
  // found, or if more than one attribute is found (either multiple
  // comma-separated entries, or multiple copies of the header).
  const char* Lookup1(const StringPiece& name) const;

  // Does there exist a header with given name.
  bool Has(const StringPiece& name) const;

  // Is value one of the values in Lookup(name)?
  bool HasValue(const StringPiece& name, const StringPiece& value) const;

  // NumAttributeNames is also const but not thread-safe.
  int NumAttributeNames() const;

  // Remove all instances of cookie_name in all the cookie headers.
  // Empty cookie headers will be removed.
  // It might be better for performance if this function is called after
  // checking that the cookie is present.
  // CAVEAT: Double quoted values are not necessarily treated as one token.
  // Please refer to the test cases in headers_cookie_util_test.cc for more
  // details.
  void RemoveCookie(const StringPiece& cookie_name);

  // Adds a new header, even if a header with the 'name' exists already.  Note
  // that this does *not* add a new entry to a comma-separated list for headers
  // that are ordinarily represented that way, but that the semantics will be
  // the same.
  void Add(const StringPiece& name, const StringPiece& value);

  // Remove headers by name and value. Return true if anything was removed.
  // Note: If the original headers were:
  // attr: val1
  // attr: val2
  // attr: val3
  // and you Remove(attr, val2), your new headers will be:
  // attr: val1, val3 (if attr is a comma-separated field)
  // and -
  // attr: val1
  // attr: val3 (otherwise).
  //
  // All instances of 'value' will be removed from 'name'.
  bool Remove(const StringPiece& name, const StringPiece& value);

  // Removes all headers by name.  Return true if anything was removed.
  bool RemoveAll(const StringPiece& name);

  // Removes all headers whose name is in |names|, which must be in
  // case-insensitive sorted order.
  bool RemoveAllFromSortedArray(const StringPiece* names, int names_size);

  // Removes all headers whose name is in |names|, which must be in
  // string-insensitive sorted order.  Returns true if anything was
  // removed.
  template <class StringType>
  static bool RemoveFromHeaders(const StringType* names, int names_size,
                                protobuf::RepeatedPtrField<NameValue>* headers);

  // Removes all headers whose name starts with prefix.  Returns true if
  // anything was removed.
  bool RemoveAllWithPrefix(const StringPiece& prefix);

  // Removes any headers from this that are not in 'keep', considering both
  // names and values.  Returns true if anything was removed.
  bool RemoveIfNotIn(const Headers& keep);

  // Similar to RemoveAll followed by Add.  Note that the attribute
  // order may be changed as a side effect of this operation.
  virtual void Replace(const StringPiece& name, const StringPiece& value);

  // Merge headers. Replaces all headers specified both here and in
  // other with the version in other. Useful for updating headers
  // when recieving 304 Not Modified responses.
  // Note: This is order-scrambling.
  virtual void UpdateFrom(const Headers<Proto>& other);

  // Serialize HTTP header to a binary stream.
  virtual bool WriteAsBinary(Writer* writer, MessageHandler* message_handler);

  // Read HTTP header from a binary string.
  virtual bool ReadFromBinary(const StringPiece& buf, MessageHandler* handler);

  // Serialize HTTP headers in HTTP format so it can be re-parsed
  virtual bool WriteAsHttp(Writer* writer, MessageHandler* handler) const;

  // Copy protobuf representation to "proto".
  void CopyToProto(Proto* proto) const;

  // Check the given vector of name[=value] strings for an entry with the given
  // name, returning true iff found and setting optional_retval iff it is not
  // NULL and there is a value assigned (there is an '=' in the string).
  // Note: only the value of the first occurence of name is returned.
  // Note: the return value is trimmed of leading and trailing whitespace.
  // Note: the return value might be assigned to even if we return false.
  static bool FindValueForName(const StringPieceVector& name_equals_value_vec,
                               StringPiece name_to_find,
                               StringPiece* optional_retval);

  // Parse a name[=value] string and extract the name and value (if the given
  // argument isn't NULL) with leading and trailing whitespace removed.
  // Returns true if a value was assigned (specifically, an '=' was found),
  // else false.
  static bool ExtractNameAndValue(StringPiece input, StringPiece* name,
                                  StringPiece* optional_retval);

 protected:
  // You need to know what you're doing to use these, so for subclasses only.
  void SetProto(Proto* proto);  // Takes ownership of the argument.
  void CopyProto(const Proto& proto);

  void PopulateMap() const;  // const is a lie, mutates map_.

  // Populates the cookies map and returns a const pointer to it. 'name' is
  // the name of the header to lookup: either "Cookie" for request headers or
  // "Set-Cookie" for response headers. The header is assumed to contain semi-
  // colon separated name=value pairs. For "Set-Cookie" headers, the first pair
  // is the name and value of the cookie and subsequent pairs are attributes of
  // that cookie - the value will be the 'first' part of the pair in the map,
  // all the attributes will be the 'second' part (as a single string of semi-
  // colon separated name=value pairs). For "Cookie" headers, each pair is an
  // independent cookie and is put into the map separately.
  // Note that const is a lie: cookies_ is mutated.
  const CookieMultimap* PopulateCookieMap(StringPiece header_name) const;

  // Called whenever a mutation occurrs.  Subclasses may override to update
  // any local copies of data.
  virtual void UpdateHook();

  // Subclasses need to manipulate the proto_ member as its type and use is
  // specific to the subclass.
  const Proto* proto() const { return proto_.get(); }
  Proto* mutable_proto() { return proto_.get(); }

 private:
  // If name is a comma-separated field (above), then split value at commas,
  // and add name, val for each of the comma-separated values
  // (removing whitespace and commas).
  // Otherwise, add the name, value pair to the map_.
  // const is a lie
  // NOTE: the map will contain the comma-split values, but the protobuf
  // will contain the original pairs including comma-separated values.
  void AddToMap(const StringPiece& name, const StringPiece& value) const;

  // We have two representations for the name/value pairs.  Proto contains a
  // simple string-pair vector, but lacks a fast associative lookup.  So we
  // will build structures for associative lookup lazily, and keep them
  // up-to-date if they are present.
  mutable std::unique_ptr<StringMultiMapInsensitive> map_;
  std::unique_ptr<Proto> proto_;

  // Furthermore, we also have a map of cookie names to <value, attributes>.
  // It is lazilyloaded by PopulateCookieMap as/when required. The keys and
  // values all point into the map_ data element. We cater for the same cookie
  // being set multiple times though we don't necessarily handle that correctly.
  mutable std::unique_ptr<CookieMultimap> cookies_;

  DISALLOW_COPY_AND_ASSIGN(Headers);
};

}  // namespace net_instaweb

#endif  // PAGESPEED_KERNEL_HTTP_HEADERS_H_


text:
package com.sujeet.snmp.common;

public class VarBind {

	private String oid;

	private String value;

	public String getOid() {
		return oid;
	}

	public void setOid(String oid) {
		this.oid = oid;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

	@Override
	public String toString() {
		return "[OID: " + getOid() + ", Value: " + getValue() + "]";
	}

}


text:
require "tco"

module Scriptster
  # This module contains the logging function and related configuration.
  module Logger
    # The name of the script.
    @@name = nil

    # The IO object to log to.
    @@file = nil

    # Show timestamps flag.
    @@timestamps = false

    # Supported message types.
    @@message_types = {
      :info => "info",
      :warn => "WARN",
      :err  => "ERR!",
      :debug => "dbg?"
    }

    # The default verobosity level.
    @@verbosity = :verbose

    # Supported verbosity levels.
    @@verbosity_levels = {
      :quiet => 0,
      :essential => 1,
      :important => 2,
      :informative => 3,
      :verbose => 4
    }

    @@format = "%{timestamp} %{name} %{type} %{message}"

    # A setter for the script name.
    #
    # @param [String] name  Desired script name.
    def self.set_name(name)
      @@name = name
    end

    # A setter for for logger verbosity.
    #
    # @param [Symbol] level  Desired verbosity level.
    def self.set_verbosity(level)
      msg = "Message verbosity level not recognised (#{})."
      raise msg unless @@verbosity_levels.has_key? level.to_sym

      @@verbosity = level.to_sym
    end

    # A setter for the log file.
    #
    # @param [String, StringIO, File] file  A path or an IO object.
    def self.set_file(file)
      @@file.close if @@file
      @@file = nil

      case
        when file.is_a?(String) then @@file = File.open file, "w"
        when file.is_a?(File) then @@file = file
        when file.is_a?(StringIO) then @@file = file
        else
          raise "Not a vailid file"
      end
    end

    # Specify the format of each line in the logs.
    #
    # The template can reference the following keys:
    #   * timestamp
    #   * name
    #   * type
    #   * message
    #
    # @example
    #   Logger::set_format "%{timestamp} %{name} %{type} %{message}"
    #
    # @param [String] format  The format template.
    def self.set_format(format)
      @@format = format
    end

    # Log a string.
    #
    # The message will be written to both stdout and the log file if configured.
    #
    # @param [Symbol] msg_type  Type of the message.
    # @param [String] msg  The contents of the log message.
    # @param [Symbol] verbosity  Desired verbosity level of this message.
    def self.log(msg_type, msg, verbosity=:informative)
      # arguments sanity checks
      unless @@message_types.include? msg_type
        raise ArgumentError, "Unknown message type :#{msg_type}"
      end

      unless @@verbosity_levels.include?(verbosity) and verbosity != :quiet
        raise ArgumentError, "You can't use the :#{verbosity.to_s} verbosity level"
      end

      if @@verbosity_levels[verbosity] <= @@verbosity_levels[@@verbosity]
          ts = Time.now.strftime("%Y-%m-%d %H:%M:%S").style("timestamp")

        name = if @@name != nil && @@name.length > 0
          @@name.style("name")
        else
          ""
        end

        msg.chomp!
        msg = Tco::parse msg, Tco::get_style("#{msg_type.to_s}-message")

        line = @@format % {
          timestamp: ts,
          name: name,
          type: @@message_types[msg_type].style(msg_type.to_s),
          message: msg
        }

        puts line
        STDOUT.flush

        if @@file
          # Strip colours from the message before writing to a file
          @@file.puts line.gsub(/\033\[[0-9]+(;[0-9]+){0,2}m/, "")
        end
      end
    end

    # Instance method wrapper for when the module is included.
    #
    # @see Logger.log
    def log(msg_type, msg, verbosity=:informative)
      Logger::log msg_type, msg, verbosity
    end
  end
end


text:
[![CircleCI](https://circleci.com/gh/science-periodicals/graph-rdfa-processor.svg?style=svg)](https://circleci.com/gh/science-periodicals/graph-rdfa-processor)

Note: this module is auto published to npm on CircleCI. Only run `npm version
patch|minor|major` and let CI do the rest.

Green turtle GraphRdfaProcessor extracted and available as a
standalone commonJS / ES2015 module.

All credits are due to Alex Milowski for
[green-turtle](https://github.com/alexmilowski/green-turtle).

Aside from the adaptation to ES2015, some little changes were made to
make it compatible with [jsdom](https://github.com/tmpvar/jsdom). Also
proper Errors are now thrown instead of plain strings.

For convenience, a high level API has been added:

```js
import getRdfaGraph from graph-rdfa-processor;

let opts = {baseURI: 'http://example.com'};
let graph = getRdfaGraph(documentOrNode, opts);
console.log(graph.toString());
```

See the tests for a full example.

## RDFa to JSON-LD

see
[jsonld-rdfa-parser](https://github.com/science-periodicals/jsonld-rdfa-parser)
(using this module to extract the RDFa graph.


text:
<menu
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".Person.PersonMain">

    <item
        android:id="@+id/action_info"
        android:orderInCategory="200"
        android:title="Info"
        android:icon="@drawable/fpp_info"
        app:showAsAction="ifRoom"
        />
    <item
        android:id="@+id/action_back"
        android:orderInCategory="300"
        android:title="Back"
        app:showAsAction="ifRoom"
        />
    <item
        android:id="@+id/action_ok"
        android:orderInCategory="400"
        android:title="Ok"
        app:showAsAction="ifRoom"
        />

</menu>


text:
layout: data_model
title: AttackPatternType
this_version: 1.1
---

  Heads up! These docs are for STIX 1.1, which is not the latest version (1.2). View the latest!

AttackPatternTypeTTP Schema

Captures prose information about an individual attack pattern as well as a CAPEC reference.

In addition to capturing basic information, this type is intended to be extended to enable the structured description of an attack pattern instance using the XML Schema extension feature. The STIX default extension uses the Common Attack Pattern Enumeration and Classification (CAPEC) schema to do so. The extension that defines this is captured in the CAPEC2.7InstanceType in the http://stix.mitre.org/extensions/AP#CAPEC2.7-1 namespace. This type is defined in the extensions/attack_pattern/capec_2.7_attack_pattern.xsd file or at the URL http://stix.mitre.org/XMLSchema/extensions/attack_pattern/capec_2.7/1.0/capec_2.7_attack_pattern.xsd.

      <form id="nav-version">
        <select>

            <option value="1.2" >STIX 1.2</option>

            <option value="1.1.1" >STIX 1.1.1</option>

            <option value="1.1" selected="selected">STIX 1.1</option>

            <option value="1.0.1" >STIX 1.0.1</option>

            <option value="1.0" >STIX 1.0</option>

        </select>
      </form>

Fields

      Field Name
      Type
      Description

      @idoptional

          QName

Specifies a unique ID for this Attack Pattern.

      @idrefoptional

          QName

Specifies a reference to the ID for this Attack Pattern specified elsewhere.

      @capec_idoptional

          @capec_idInlineType

This field specifies a reference to a particular entry within the Common Attack Pattern Enumeration and Classification (CAPEC)

      Title0..1

          string

The Title field provides a simple title for an individual Attack Pattern.

      Description0..1

          StructuredTextType

The Description field is optional and provides an unstructured, text description of an individual Attack Pattern.

      Short_Description0..1

          StructuredTextType

The Short_Description field is optional and provides a short, unstructured, text description of an individual Attack Pattern.


text:
#ifndef __APP_H
#define __APP_H

/* app support api */
void apps_init(void); /* one time setup */

/* app entry point */
struct app_descriptor;
typedef void (*app_init)(const struct app_descriptor *);
typedef void (*app_entry)(const struct app_descriptor *, void *args);

/* app startup flags */
#define APP_FLAG_DONT_START_ON_BOOT 0x1

/* each app needs to define one of these to define its startup conditions */
struct app_descriptor {
	const char *name;
	app_init  init;
	app_entry entry;
	unsigned int flags;
};

#define APP_START(appname) struct app_descriptor _app_##appname __SECTION(".apps") = { .name = #appname,
#define APP_END };

#endif


text:
module PostmarkRails
  class Railtie < Rails::Railtie
    initializer 'postmark-rails', :before => 'action_mailer.set_configs' do
      ActiveSupport.on_load :action_mailer do
        PostmarkRails.install
      end
    end
  end
end


text:
webpageimagecrawler
===================

Download image from a given valid URL

![alt tag](https://raw.githubusercontent.com/johndavedecano/webpageimagecrawler/master/statics/thumbnail.png)

INSTALLATION:

1. From your server directory,git clone https://github.com/johndavedecano/webpageimagecrawler.git
2. Then composer install
3. Browse the page.

SPECIAL THANKS TO:

1. Slim Framework
2. PHP Unit
3. JQuery
4. PHP - Rasmus Lerdorf
5. My Neighbors
4. and myself.


text:
package gov.va.cpe.vpr.web;

import gov.va.cpe.vpr.NotFoundException;

public class UidNotFoundException extends NotFoundException {
    private Class domainClass;
    private String uid;

    public UidNotFoundException(final Class domainClass, final String uid) {
        super(domainClass.getName() + " with uid '" + uid + "' not found".toString());
        this.domainClass = domainClass;
        this.uid = uid;
    }

    public Class getDomainClass() {
        return domainClass;
    }

    public String getUid() {
        return uid;
    }
}


text:
#import "base/RTCVideoDecoderFactory.h"
#import "base/RTCVideoEncoderFactory.h"
#import "components/video_codec/RTCDefaultVideoDecoderFactory.h"
#import "components/video_codec/RTCDefaultVideoEncoderFactory.h"


text:
@interface AppDelegate ()

@end

@implementation AppDelegate

@synthesize tabbarLastTimeSelectedIndex;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    [ShareSDK registerApp:@"617d5f809a84"];//字符串api20为您的ShareSDK的AppKey

//    //添加新浪微博应用 注册网址 http://open.weibo.com
//    [ShareSDK connectSinaWeiboWithAppKey:@"568898243"
//                               appSecret:@"38a4f8204cc784f81f9f0daaf31e02e3"
//                             redirectUri:@"http://www.sharesdk.cn"];
//    //当使用新浪微博客户端分享的时候需要按照下面的方法来初始化新浪的平台
//    [ShareSDK  connectSinaWeiboWithAppKey:@"568898243"
//                                appSecret:@"38a4f8204cc784f81f9f0daaf31e02e3"
//                              redirectUri:@"http://www.sharesdk.cn"
//                              weiboSDKCls:[WeiboSDK class]];

//    //添加腾讯微博应用 注册网址 http://dev.t.qq.com
//    [ShareSDK connectTencentWeiboWithAppKey:@"801307650"
//                                  appSecret:@"ae36f4ee3946e1cbb98d6965b0b2ff5c"
//                                redirectUri:@"http://www.sharesdk.cn"
//                                   wbApiCls:[WeiboApi class]];

    //添加QQ空间应用  注册网址  http://connect.qq.com/intro/login/
    [ShareSDK connectQZoneWithAppKey:@"1104569708"
                           appSecret:@"GKMIeeBE49IXBMGS"
                   qqApiInterfaceCls:[QQApiInterface class]
                     tencentOAuthCls:[TencentOAuth class]];

    //添加QQ应用  注册网址  http://open.qq.com/
    [ShareSDK connectQQWithQZoneAppKey:@"1104569708"
                     qqApiInterfaceCls:[QQApiInterface class]
                       tencentOAuthCls:[TencentOAuth class]];

    //添加微信应用 注册网址 http://open.weixin.qq.com
    [ShareSDK connectWeChatWithAppId:@"wxee618bcd7c2295f5"
                           wechatCls:[WXApi class]];
    //微信登陆的时候需要初始化
    [ShareSDK connectWeChatWithAppId:@"wxee618bcd7c2295f5"
                           appSecret:@"fcea6cf6b2fcd4264fb3ffa6968245ef"
                           wechatCls:[WXApi class]];

//    //添加人人网应用 注册网址  http://dev.renren.com
//    [ShareSDK connectRenRenWithAppId:@"226427"
//                              appKey:@"fc5b8aed373c4c27a05b712acba0f8c3"
//                           appSecret:@"f29df781abdd4f49beca5a2194676ca4"
//                   renrenClientClass:[RennClient class]];

    //检测网络状态

    NSURL *baseURL = [NSURL URLWithString:@"http://www.baidu.com/"];
    AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:baseURL];

    NSOperationQueue *operationQueue = manager.operationQueue;
    [manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWWAN:
            case AFNetworkReachabilityStatusReachableViaWiFi:
                [operationQueue setSuspended:NO];
                break;
            case AFNetworkReachabilityStatusNotReachable:
            default:
                [operationQueue setSuspended:YES];
                break;
        }
    }];

    [manager.reachabilityManager startMonitoring];

    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
    }];

    // Required
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [APService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                       UIUserNotificationTypeSound |
                                                       UIUserNotificationTypeAlert)
                                           categories:nil];
    } else {
        //categories 必须为nil
        [APService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                       UIRemoteNotificationTypeSound |
                                                       UIRemoteNotificationTypeAlert)
                                           categories:nil];
    }
#else
    //categories 必须为nil
    [APService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                   UIRemoteNotificationTypeSound |
                                                   UIRemoteNotificationTypeAlert)
                                       categories:nil];
#endif
    // Required
    [APService setupWithOption:launchOptions];

    return YES;
}

//禁止旋转屏幕
-(NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    return UIInterfaceOrientationMaskPortrait;
}

- (BOOL)application:(UIApplication *)application
      handleOpenURL:(NSURL *)url
{
    return [ShareSDK handleOpenURL:url
                        wxDelegate:self];
}

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    //支付返回
    if ([url.host isEqualToString:@"safepay"]) {
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result1 = %@",resultDic);
        }];
        return YES;
    }
    if ([url.host isEqualToString:@"platformapi"]){//支付宝钱包快登授权返回 authCode
        [[AlipaySDK defaultService] processAuthResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result2 = %@",resultDic);
        }];
        return YES;
    }

    return [ShareSDK handleOpenURL:url
                 sourceApplication:sourceApplication
                        annotation:annotation
                        wxDelegate:self];
}

//推送的三个方法
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {

    // Required
    [APService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {

    // Required
    [APService handleRemoteNotification:userInfo];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {

    // IOS 7 Support Required
    [APService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

//

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

    //取消桌面图标上的信息显示
     [[UIApplication sharedApplication]setApplicationIconBadgeNumber:0];

}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.

    //取消桌面图标上的信息显示
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];

}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "xyzx5u.Ocean" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Ocean" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }

    // Create the coordinator and store

    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Ocean.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return _persistentStoreCoordinator;
}

- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] init];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

@end