text:
"use strict";
/**
 * Each module has a <moduleName>.module.js file.  This file contains the angular module declaration -
 * angular.module("moduleName", []);
 * The build system ensures that all the *.module.js files get included prior to any other .js files, which
 * ensures that all module declarations occur before any module references.
 */
(function (app) {
  app.config(function ($stateProvider, $urlRouterProvider) {
    //
    // For any unmatched url, redirect to /state1
    $urlRouterProvider.otherwise("/state1");
    //
    // Now set up the states
    $stateProvider
      .state('state1', {
        url: "/state1",
        template: "partials/state1.html"
      })
      .state('state2', {
        url: "/state2",
        data: {
          resource: 'user.account'
        },
        template: "partials/state2.html"
      }).state('state3', {
        url: "/state3",
        template: "partials/state3.html"
      });
  });
  app.controller("AppController", ['$scope', '$rootScope', '$timeout', 'acl', function ($scope, $rootScope, $timeout, acl) {
    $scope.message = false;
    var cleanup = $rootScope.$on('$stateChangeStart', function (event) {
      if (!event.defaultPrevented) {
        $scope.message = "";
      }
    });
    var cleanup2 = $rootScope.$on('acl.stateChangeDenied', function () {
      $scope.message = "State change not authorized";
    });
    $scope.$on('$destroy', function () {
      cleanup();
      cleanup2();
    });
    var userIdentity = {
      isGuest: false,
      resources: {
        allowed: ["**"],
        denied: ["admin.**", 'user.account']
      }
    };

    acl.init(userIdentity);
  }]);

  // The name of the module, followed by its dependencies (at the bottom to facilitate enclosure)
}(angular.module("app", ['ngAcl', 'ngAcl.states'])));


text:
<?php
/**
 * DO NOT EDIT THIS FILE!
 *
 * This file was automatically generated from external sources.
 *
 * Any manual change here will be lost the next time the SDK
 * is updated. You've been warned!
 */

namespace DTS\eBaySDK\Trading\Types;

/**
 *
 * @property boolean $BusinessSeller
 * @property boolean $RestrictedToBusiness
 * @property double $VATPercent
 * @property string $VATSite
 * @property string $VATID
 */
class VATDetailsType extends \DTS\eBaySDK\Types\BaseType
{
    /**
     * @var array Properties belonging to objects of this class.
     */
    private static $propertyTypes = [
        'BusinessSeller' => [
            'type' => 'boolean',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'BusinessSeller'
        ],
        'RestrictedToBusiness' => [
            'type' => 'boolean',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'RestrictedToBusiness'
        ],
        'VATPercent' => [
            'type' => 'double',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'VATPercent'
        ],
        'VATSite' => [
            'type' => 'string',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'VATSite'
        ],
        'VATID' => [
            'type' => 'string',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'VATID'
        ]
    ];

    /**
     * @param array $values Optional properties and values to assign to the object.
     */
    public function __construct(array $values = [])
    {
        list($parentValues, $childValues) = self::getParentValues(self::$propertyTypes, $values);

        parent::__construct($parentValues);

        if (!array_key_exists(__CLASS__, self::$properties)) {
            self::$properties[__CLASS__] = array_merge(self::$properties[get_parent_class()], self::$propertyTypes);
        }

        if (!array_key_exists(__CLASS__, self::$xmlNamespaces)) {
            self::$xmlNamespaces[__CLASS__] = 'xmlns="urn:ebay:apis:eBLBaseComponents"';
        }

        $this->setValues(__CLASS__, $childValues);
    }
}

redpajama_set_name: RedPajamaGithub


text:
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#pragma once

#include "ModuleManager.h"
#include "Editor/SceneOutliner/Public/SceneOutlinerModule.h"

typedef TTextFilter< const TSharedPtr< FLayerViewModel >& > LayerTextFilter;

namespace ELayerBrowserMode
{
	enum Type
	{
		Layers,
		LayerContents,

		Count
	};
}

/**
 *
 */
class SLayerBrowser : public SCompoundWidget
{
public:

	SLATE_BEGIN_ARGS( SLayerBrowser ) {}
	SLATE_END_ARGS()

	~SLayerBrowser()
	{
		LayerCollectionViewModel->OnLayersChanged().RemoveAll( this );
		LayerCollectionViewModel->OnSelectionChanged().RemoveAll( this );
		LayerCollectionViewModel->OnRenameRequested().RemoveAll( this );
		LayerCollectionViewModel->RemoveFilter( SearchBoxLayerFilter.ToSharedRef() );
	}

	/**
	 * Construct this widget.  Called by the SNew() Slate macro.
	 *
	 * @param	InArgs				Declaration used by the SNew() macro to construct this widget
	 * @param	InViewModel			The UI logic not specific to slate
	 */
	void Construct( const FArguments& InArgs );

protected:

	/** Overridden from SWidget: Called when a key is pressed down */
	FReply OnKeyDown( const FGeometry& MyGeometry, const FKeyEvent& InKeyEvent ) override
	{
		if( InKeyEvent.GetKey() == EKeys::Escape && Mode == ELayerBrowserMode::LayerContents )
		{
			SetupLayersMode();
			return FReply::Handled();
		}

		return FReply::Unhandled();
	}

	/**
	 * Called during drag and drop when the drag leaves a widget.
	 *
	 * @param DragDropEvent   The drag and drop event.
	 */
	virtual void OnDragLeave( const FDragDropEvent& DragDropEvent ) override
	{
		TSharedPtr< FActorDragDropGraphEdOp > DragActorOp = DragDropEvent.GetOperationAs< FActorDragDropGraphEdOp >();
		if(DragActorOp.IsValid())
		{
			DragActorOp->ResetToDefaultToolTip();
		}
	}

	/**
	 * Called during drag and drop when the the mouse is being dragged over a widget.
	 *
	 * @param MyGeometry      The geometry of the widget receiving the event.
	 * @param DragDropEvent   The drag and drop event.
	 *
	 * @return A reply that indicated whether this event was handled.
	 */
	virtual FReply OnDragOver( const FGeometry& MyGeometry, const FDragDropEvent& DragDropEvent ) override
	{
		TSharedPtr< FActorDragDropGraphEdOp > DragActorOp = DragDropEvent.GetOperationAs< FActorDragDropGraphEdOp >();
		if (!SelectedLayerViewModel->GetDataSource().IsValid() || !DragActorOp.IsValid())
		{
			return FReply::Unhandled();
		}

		const FGeometry LayerContentsHeaderGeometry = SWidget::FindChildGeometry( MyGeometry, LayerContentsHeader.ToSharedRef() );
		bool bValidDrop = LayerContentsHeaderGeometry.IsUnderLocation( DragDropEvent.GetScreenSpacePosition() );

		if( !bValidDrop && Mode == ELayerBrowserMode::LayerContents )
		{
			const FGeometry LayerContentsSectionGeometry = SWidget::FindChildGeometry( MyGeometry, LayerContentsSection.ToSharedRef() );
			bValidDrop = LayerContentsSectionGeometry.IsUnderLocation( DragDropEvent.GetScreenSpacePosition() );
		}

		if( !bValidDrop )
		{
			return FReply::Unhandled();
		}

		if ( !DragActorOp.IsValid() || DragActorOp->Actors.Num() == 0 )
		{
			return FReply::Unhandled();
		}

		bool bCanAssign = false;
		FText Message;
		if( DragActorOp->Actors.Num() > 1 )
		{
			bCanAssign = SelectedLayerViewModel->CanAssignActors( DragActorOp->Actors, OUT Message );
		}
		else
		{
			bCanAssign = SelectedLayerViewModel->CanAssignActor( DragActorOp->Actors[ 0 ], OUT Message );
		}

		if ( bCanAssign )
		{
			DragActorOp->SetToolTip( FActorDragDropGraphEdOp::ToolTip_CompatibleGeneric, Message );
		}
		else
		{
			DragActorOp->SetToolTip( FActorDragDropGraphEdOp::ToolTip_IncompatibleGeneric, Message );
		}

		// We leave the event unhandled so the children of the ListView get a chance to grab the drag/drop
		return FReply::Unhandled();
	}

	/**
	 * Called when the user is dropping something onto a widget; terminates drag and drop.
	 *
	 * @param MyGeometry      The geometry of the widget receiving the event.
	 * @param DragDropEvent   The drag and drop event.
	 *
	 * @return A reply that indicated whether this event was handled.
	 */
	virtual FReply OnDrop( const FGeometry& MyGeometry, const FDragDropEvent& DragDropEvent ) override
	{
		TSharedPtr< FActorDragDropGraphEdOp > DragActorOp = DragDropEvent.GetOperationAs< FActorDragDropGraphEdOp >();

		if (!SelectedLayerViewModel->GetDataSource().IsValid() || !DragActorOp.IsValid())
		{
			return FReply::Unhandled();
		}

		const FGeometry LayerContentsHeaderGeometry = SWidget::FindChildGeometry( MyGeometry, LayerContentsHeader.ToSharedRef() );
		bool bValidDrop = LayerContentsHeaderGeometry.IsUnderLocation( DragDropEvent.GetScreenSpacePosition() );

		if( !bValidDrop && Mode == ELayerBrowserMode::LayerContents )
		{
			const FGeometry LayerContentsSectionGeometry = SWidget::FindChildGeometry( MyGeometry, LayerContentsSection.ToSharedRef() );
			bValidDrop = LayerContentsSectionGeometry.IsUnderLocation( DragDropEvent.GetScreenSpacePosition() );
		}

		if( !bValidDrop )
		{
			return FReply::Unhandled();
		}

		SelectedLayerViewModel->AddActors( DragActorOp->Actors );

		return FReply::Handled();
	}

private:

	void RemoveActorsFromSelectedLayer( const TArray< TWeakObjectPtr< AActor > >& Actors )
	{
		SelectedLayerViewModel->RemoveActors( Actors );
	}

	TSharedRef< ISceneOutlinerColumn > CreateCustomLayerColumn( ISceneOutliner& SceneOutliner ) const
	{
		return MakeShareable( new FSceneOutlinerLayerContentsColumn( SelectedLayerViewModel.ToSharedRef() ) );
	}

	FSlateColor GetInvertedForegroundIfHovered() const
	{
		static const FName InvertedForegroundName("InvertedForeground");
		return ( ToggleModeButton.IsValid() && ( ToggleModeButton->IsHovered() || ToggleModeButton->IsPressed() ) ) ? FEditorStyle::GetSlateColor(InvertedForegroundName): FSlateColor::UseForeground();
	}

	const FSlateBrush* GetToggleModeButtonImageBrush() const
	{
		static const FName ExploreLayerContents("LayerBrowser.ExploreLayerContents");
		static const FName ReturnToLayersList("LayerBrowser.ReturnToLayersList");
		return ( Mode == ELayerBrowserMode::Layers ) ? FEditorStyle::GetBrush( ExploreLayerContents ) : FEditorStyle::GetBrush( ReturnToLayersList );
	}

	FText GetLayerContentsHeaderText() const;

	/**	Returns the visibility of the See Contents label */
	EVisibility IsVisibleIfModeIs( ELayerBrowserMode::Type DesiredMode ) const
	{
		return ( Mode == DesiredMode ) ? EVisibility::Visible : EVisibility::Collapsed;
	}

	EVisibility GetLayerContentsHeaderVisibility() const
	{
		return ( SelectedLayerViewModel->GetDataSource().IsValid() ) ? EVisibility::Visible : EVisibility::Collapsed;
	}

	FReply ToggleLayerContents()
	{
		switch( Mode )
		{
		default:
		case ELayerBrowserMode::Layers:
			SetupLayerContentsMode();
			break;

		case ELayerBrowserMode::LayerContents:
			SetupLayersMode();
			break;
		}

		return FReply::Handled();
	}

	void SetupLayersMode()
	{
		ContentAreaBox->ClearChildren();
		ContentAreaBox->AddSlot()
		.FillHeight( 1.0f )
		[
			LayersSection.ToSharedRef()
		];

		ContentAreaBox->AddSlot()
		.AutoHeight()
		.VAlign( VAlign_Bottom )
		.MaxHeight( 23 )
		[
			LayerContentsHeader.ToSharedRef()
		];

		Mode = ELayerBrowserMode::Layers;
	}

	void SetupLayerContentsMode()
	{
		ContentAreaBox->ClearChildren();
		ContentAreaBox->AddSlot()
		.AutoHeight()
		.VAlign( VAlign_Top )
		.MaxHeight( 23 )
		[
			LayerContentsHeader.ToSharedRef()
		];

		ContentAreaBox->AddSlot()
		.AutoHeight()
		.FillHeight( 1.0f )
		[
			LayerContentsSection.ToSharedRef()
		];

		Mode = ELayerBrowserMode::LayerContents;
	}

	void TransformLayerToString( const TSharedPtr< FLayerViewModel >& Layer, OUT TArray< FString >& OutSearchStrings ) const
	{
		if( !Layer.IsValid() )
		{
			return;
		}

		OutSearchStrings.Add( Layer->GetName() );
	}

	void UpdateLayerContentsFilter()
	{
		TArray< FName > LayerNames;
		LayerCollectionViewModel->GetSelectedLayerNames( LayerNames );
		SelectedLayersFilter->SetLayers( LayerNames );
	}

	void UpdateSelectedLayer()
	{
		UpdateLayerContentsFilter();

		if( LayerCollectionViewModel->GetSelectedLayers().Num() == 1 )
		{
			const auto Layers = LayerCollectionViewModel->GetSelectedLayers();
			check( Layers.Num() == 1 );
			SelectedLayerViewModel->SetDataSource( Layers[ 0 ]->GetDataSource() );
		}
		else
		{
			SelectedLayerViewModel->SetDataSource( NULL );
		}
	}

	void OnLayersChanged( const ELayersAction::Type Action, const TWeakObjectPtr< ULayer >& ChangedLayer, const FName& ChangedProperty )
	{
		if( Action != ELayersAction::Reset && Action != ELayersAction::Delete )
		{
			if( !ChangedLayer.IsValid() || SelectedLayerViewModel->GetDataSource() == ChangedLayer )
			{
				UpdateLayerContentsFilter();
			}

			return;
		}

		UpdateSelectedLayer();

		if( Mode == ELayerBrowserMode::LayerContents && !SelectedLayerViewModel->GetDataSource().IsValid() )
		{
			SetupLayersMode();
		}
	}

	/** Callback when layers want to be renamed */
	void OnRenameRequested()
	{
		LayersView->RequestRenameOnSelectedLayer();
	}

	TSharedPtr< SWidget > ConstructLayerContextMenu()
	{
		return SNew( SLayersCommandsMenu, LayerCollectionViewModel.ToSharedRef() );
	}

	void OnFilterTextChanged( const FText& InNewText );

private:

	/** */
	TSharedPtr< SButton > ToggleModeButton;

	/**	 */
	TSharedPtr< SVerticalBox > ContentAreaBox;

	/**	 */
	TSharedPtr< SBorder > LayersSection;

	/**	 */
	TSharedPtr< SBorder > LayerContentsSection;

	/**	 */
	TSharedPtr< SBorder > LayerContentsHeader;

	/** */
	TSharedPtr< class SSearchBox> SearchBoxPtr;

	/**	 */
	TSharedPtr< LayerTextFilter > SearchBoxLayerFilter;

	/**	 */
	TSharedPtr< FActorsAssignedToSpecificLayersFilter > SelectedLayersFilter;

	/**	 */
	TSharedPtr< FLayerCollectionViewModel > LayerCollectionViewModel;

	/**	 */
	ELayerBrowserMode::Type Mode;

	/**	 */
	TSharedPtr< FLayerViewModel > SelectedLayerViewModel;

	/** The layer view widget, displays all the layers in the level */
	TSharedPtr< SLayersView > LayersView;
};


text:
class CalendarsController < ApplicationController
  before_filter :load_user_by_login

  def index
    @year = (params[:year] || Time.now.year).to_i
    @observations = @selected_user.observations.on(@year).all(:select => "id, observed_on")
    @observations_by_month = @observations.group_by {|o| o.observed_on.month}
  end

  def show
    @year   = params[:year] if params[:year].to_i != 0
    @month  = params[:month].to_s.rjust(2, '0') if params[:month].to_i != 0
    @day    = params[:day].to_s.rjust(2, '0') if params[:day].to_i != 0
    @date = [@year, @month, @day].compact.join('-')
    begin
      Date.parse(@date)
    rescue ArgumentError
      respond_to do |format|
        format.html do
          flash[:notice] = t(:thats_not_a_real_date)
          redirect_back_or_default calendar_path(@login)
        end
      end
      return
    end
    @observations = @selected_user.observations.
      on(@date).
      page(1).
      per_page(200).
      order_by("observed_on")
    if @day
      @observations = @observations.includes(:taxon => :taxon_names, :observation_photos => :photo)
      @taxa = @observations.map{|o| o.taxon}.uniq.compact
      @taxa_count = @taxa.size
      @taxa_by_iconic_taxon_id = @taxa.group_by{|t| t.iconic_taxon_id}
      @iconic_taxon_counts = Taxon::ICONIC_TAXA.map do |iconic_taxon|
        next unless @taxa_by_iconic_taxon_id[iconic_taxon.id]
        [iconic_taxon.id, @taxa_by_iconic_taxon_id[iconic_taxon.id].size]
      end.compact
    else
      iconic_counts_conditions = Observation.conditions_for_date("o.observed_on", @date)
      iconic_counts_conditions[0] += " AND o.user_id = ?"
      iconic_counts_conditions << @selected_user
      @iconic_counts = Taxon.count(
        :joins => "JOIN observations o ON o.taxon_id = taxa.id",
        :conditions => iconic_counts_conditions,
        :group => "taxa.iconic_taxon_id")
    end

    @life_list_firsts = @selected_user.life_list.listed_taxa.all(
      :conditions => ["first_observation_id IN (?)", @observations]
    ).sort_by{|lt| lt.ancestry.to_s + '/' + lt.id.to_s}

    unless @observations.blank?
      scope = Observation.where("ST_Intersects(place_geometries.geom, observations.private_geom)")
      # without this there can be performance problems with very large places.
      # 6 is around the max size for a US county
      scope = scope.where("st_area(place_geometries.geom) < 6")
      scope = scope.where("places.id = place_geometries.place_id")
      scope = scope.where("observations.user_id = ? ", @selected_user)
      scope = scope.where(Observation.conditions_for_date("observations.observed_on", @date))
      place_name_counts = scope.count(
        :from => "observations, places, place_geometries",
        :group => "(places.display_name || '-' || places.id)")
      @places = Place.where("id IN (?)", place_name_counts.map{|n,c| n.to_s.split('-').last})
      @place_name_counts = @places.sort_by(&:bbox_area).map do |place|
        n = "#{place.display_name}-#{place.id}"
        [n, place_name_counts[n]]
      end
      @previous = @selected_user.observations.first(:conditions => ["observed_on < ?", @observations.first.observed_on], :order => "observed_on DESC")
      @next = @selected_user.observations.first(:conditions => ["observed_on > ?", @observations.first.observed_on], :order => "observed_on ASC")
    end

    @observer_provider_authorizations = @selected_user.provider_authorizations

    respond_to do |format|
      format.html
    end
  end

  def compare
    @dates = params[:dates].split(',')
    if @dates.blank?
      flash[:notice] = t(:you_must_select_dates_to_compare)
      redirect_back_or_default(calendar_path(@login))
    end
    @observations_by_date_by_taxon_id = {}
    @taxon_ids = []
    @taxon = Taxon.find_by_id(params[:taxon_id].to_i) unless params[:taxon_id].blank?
    scope = Observation.includes(:iconic_taxon).scoped
    scope = scope.of(@taxon) if @taxon
    scope = scope.at_or_below_rank(params[:rank]) if params[:rank]
    @dates.each do |date|
      observations = scope.by(@selected_user).on(date).all
      @taxon_ids += observations.map{|o| o.taxon_id}
      @observations_by_date_by_taxon_id[date] = observations.group_by{|o| o.taxon_id}
    end
    @taxa = Taxon.all(:conditions => ["id IN (?)", @taxon_ids.uniq.compact], :include => [:taxon_names])
    @taxa = Taxon.sort_by_ancestry(@taxa)
  end
end


text:
module Main where

-- We'd like to use OpenGL's Position unqualified
import Data.IORef
import Graphics.UI.GLUT

import Callbacks
import Types

main = do
    (progName, args) <- getArgsAndInitialize

    initialDisplayMode $= [RGBAMode, WithAlphaComponent, DoubleBuffered, WithDepthBuffer]
    window <- createWindow "Gol3d"

    depthFunc $= Just Lequal
    cursor $= None
    globalKeyRepeat $= GlobalKeyRepeatOff
    cullFace $= Just Back

    stateR <- newIORef defaultState

    idleCallback $= Just (idleHandler stateR)
    keyboardMouseCallback $= Just (inputHandler stateR)
    mouseCallback $= Just (mouseHandler stateR)
    passiveMotionCallback $= Just (motionHandler stateR)

    displayCallback $= display stateR

    mainLoop


text:
package de.eric_wiltfang.dictionary;

import java.io.IOException;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.Properties;
import java.util.ResourceBundle;

/**
 * Localisation.
 *
 * @author Christian LaCourt
 */
public class Localisation {
  /**
   * Read JavaDocs. Automatically falls back.
   */
  private static ResourceBundle strings;
  private final static String BUNDLE_NAME = "dictionary";
  private Locale locale;

  Localisation(Properties settings){
    if(settings.containsKey("locale")){
      locale = Locale.forLanguageTag(settings.getProperty("locale"));
    }else{
      locale = Locale.getDefault();
    }
    try{
      strings = Util.getCustomResourceBundle(settings.getProperty("locale"));
    }catch(MissingResourceException | IOException e){
      try{
        strings = ResourceBundle.getBundle(BUNDLE_NAME, locale);
      }catch(Exception e2){
        die(e2);
      }
    }
  }

  public String get(String key){
    try{
      return strings.getString(key);
    }catch(MissingResourceException e){
      DictionaryMainWindow.getLogger().warning("Failed to find localisation key: " + key);
      return "???";
    }
  }

  private static void die(Exception e){
    DictionaryMainWindow.getInstance().die("Failed to load language file or fallbacks: " + e.getMessage());
  }

  public Locale getLocale(){
    return strings.getLocale();
  }
}


text:
#include "Coordinates2D.h"
#include <vector>
using std::vector;

struct AStarResult
{
	vector<Coordinates2D> ShortestPath;
	vector<Coordinates2D> ExpandedNodes;
};

#endif


text:
"""
Copyright (c) 2014,掌阅科技
All rights reserved.

摘    要: client.py
创 建 者: WangLichao
创建日期: 2014-10-24
"""
# pylint: disable=invalid-name,superfluous-parens
import functools
# third
from redis import Redis as _RedisClient
from redis.exceptions import ResponseError
# self
from zyredis import types
from zyredis.utils import mkey
from zyredis.utils import LOG
from zyredis.serialization import JSON
from zyredis.exceptions import NotSupportCommandError

# codis不支持的命令
NOT_SUPPORT_COMMANDS = frozenset([
    'KEYS', 'MOVE', 'OBJECT', 'RENAME', 'RENAMENX', 'SORT', 'SCAN',
    'BITOP', 'MSETNX', 'BLPOP', 'BRPOP', 'BRPOPLPUSH', 'PSUBSCRIBE', 'PUBLISH',
    'PUNSUBSCRIBE', 'SUBSCRIBE', 'UNSUBSCRIBE', 'DISCARD', 'EXEC', 'MULTI',
    'UNWATCH', 'WATCH', 'AUTH', 'ECHO', 'SELECT', 'BGREWRITEAOF', 'BGSAVE',
    'DBSIZE', 'FLUSHALL', 'FLUSHDB', 'INFO', 'LASTSAVE', 'MONITOR', 'SAVE',
    'SHUTDOWN', 'SLAVEOF', 'SLOWLOG', 'SYNC', 'TIME'
])

class Client(object):

    """Redis Client
    Attributes:
        host: redis 服务器地址,默认localhost
        port: redis 端口,默认6379
        db: 数据库名称
        serializer: 使用的序列化方式
    """

    host = "localhost"
    port = 6379
    db = 0
    serializer = JSON()

    def __init__(self, host=None, port=None, db=0,
                 serializer=None, transaction=False, **kwargs):
        self.host = host or self.host
        self.port = port or self.port
        self.transaction = transaction # codis不支持事务机制
        self.serializer = serializer or self.serializer
        self.db = db or self.db
        # 将redis的超时设置统一处理
        socket_timeout = kwargs.get("socket_timeout", 1)
        socket_connect_timeout = kwargs.get("socket_connect_timeout", 1)
        # 使用长连接
        socket_keepalive = kwargs.get("socket_keepalive", True)
        retry_on_timeout = kwargs.get("retry_on_timeout", True)
        self.api = _RedisClient(self.host,
                                self.port,
                                self.db,
                                socket_timeout=socket_timeout,
                                socket_connect_timeout=socket_connect_timeout,
                                socket_keepalive=socket_keepalive,
                                retry_on_timeout=retry_on_timeout,
                                connection_pool=None,
                                **kwargs)

    def List(self, name, initial=None, auto_slice=True):
        """list 类型
        Args:
            name: redis key
            initial: 初始化值(list类型)
        Returns:
            返回支持Python list操作的对象
        """
        return types.List(name, self.api, initial=initial, auto_slice=auto_slice)

    def Set(self, name, initial=None):
        """set 类型
        Args:
            name: redis key
            initial: 初始化值(set类型)
        Returns:
            返回支持Python set操作的对象
        """
        return types.Set(name, self.api, initial)

    def SortedSet(self, name, initial=None, auto_slice=True):
        """sorted set类型
        Args:
            name: redis key
            initial: 初始化值(ZSet类型,自定义类型)
        Returns:
            返回SortedSet对象
        """
        return types.SortedSet(name, self.api, initial, auto_slice=auto_slice)

    def Dict(self, name, initial=None, auto_slice=True, **extra):
        """Hash 类型
        Args:
            name: redis key
            initial: 初始化值(dict类型,自定义类型)
        Returns:
            返回支持python dict操作的对象
        """
        return types.Dict(name, self.api, initial=initial, auto_slice=auto_slice, **extra)

    def Queue(self, name, initial=None, maxsize=None):
        """queue队列
        Args:
            name: The name of the queue.
            initial: Initial items in the queue.
        """
        return types.Queue(name, self.api, initial=initial, maxsize=maxsize)

    def LifoQueue(self, name, initial=None, maxsize=None):
        """后进先出队列类型,部分命令codis不支持
        Args:
            name: string The name of the queue.
            initial: Initial items in the queue.
        """
        return types.LifoQueue(name, self.api,
                               initial=initial, maxsize=maxsize)

    def prepare_value(self, value):
        """编码
        Args:
            value: 需要编码的值
        """
        return self.serializer.encode(value)

    def value_to_python(self, value):
        """解码"""
        return self.serializer.decode(value)

    def dbsize(self):
        """获取dbsize数量,改命令不支持codis
        """
        if self.transaction:
            return self.api.dbsize()
        LOG.warning("dbsize is not supported by codis")

    def info(self):
        """获取info信息,该命令不支持codis
        """
        if self.transaction:
            return self.api.info()
        LOG.warning("info is not supported by codis")

    def clear(self):
        """清理所有的key,该命令不支持codis
        """
        if self.transaction:
            return self.api.flushdb()
        LOG.warning("flushdb is not supported by codis")

    def update(self, mapping):
        """使用key/values批量更新"""
        return self.api.mset(dict((key, self.prepare_value(value))
                                  for key, value in mapping.items()))

    def rename(self, old_name, new_name):
        """重命名redis的key
        Args:
            old_name: 旧版本key
            new_name: 新key
        Returns:
            False: 如果key不存在
            True: key存在并且设置成功
        """
        try:
            self.api.rename(mkey(old_name), mkey(new_name))
            return True
        except ResponseError as exc:
            LOG.error("zyredis rename error, error info=%s", exc)
            return False

    def keys(self, pattern="*"):
        '''获取所有的key,不建议使用,codis本身也不支持
        Args:
            pattern: 正则
        Returns:
            list类型key的列表
        '''
        if self.transaction:
            return self.api.keys(pattern)
        LOG.warning("keys is not supported by codis")

    def iterkeys(self, pattern="*"):
        '''使用迭代器遍历key
        '''
        if self.transaction:
            return iter(self.keys(pattern))
        LOG.warning("keys is not supported by codis")

    def iteritems(self, pattern="*"):
        '''使用迭代器获取所有的key和value
        '''
        if self.transaction:
            for key in self.keys(pattern):
                yield (key, self[key])

    def items(self, pattern="*"):
        '''获取所有的key/value对
        '''
        if self.transaction:
            return list(self.iteritems(pattern))

    def itervalues(self, pattern="*"):
        '''获取所有的value
        '''
        if self.transaction:
            for key in self.keys(pattern):
                yield self[key]

    def values(self, pattern="*"):
        """values
        """
        if self.transaction:
            return list(self.itervalues(pattern))

    def pop(self, name):
        """Get and remove key from database (atomic)."""
        name = mkey(name)
        temp = mkey((name, "__poptmp__"))
        self.rename(name, temp)
        value = self[temp]
        del(self[temp])
        return value

    def get(self, key, default=None):
        """Returns the value at ``key`` if present, otherwise returns
        ``default`` (``None`` by default.)"""
        try:
            return self[key]
        except KeyError:
            return default

    def expire(self, key, time):
        """设置key的过期时间
        Args:
            time: int or timedelta object
            key: string
        """
        return self.api.expire(key, time)

    def expireat(self, key, when):
        """设置过期标记
        Args:
            key: string
            when: unixtime or datetime object
        """
        return self.api.expireat(key, when)

    def mget(self, keys):
        """批量获取redis的key
        Args:
            keys: list 输入多个key
        Returns:
            返回list,如果不存在则为None
            ['xxx', None, ...]
        """
        return self.api.mget(keys)

    def mset(self, mapping):
        """批量set
        Args:
            key_value_list: list 多个key,value的list
        Returns:
            True or False
        """
        return self.api.mset(dict((key, self.prepare_value(value))
                                  for key, value in mapping.items()))

    def getset(self, key, value):
        """如果key存在返回key的值并设置value
        如果key不存在返回空并设置value
        Args:
            key: string
            value: string
        """
        return self.api.getset(key, value)

    def exists(self, key):
        """验证key是否存在
        """
        return self.api.exists(key)

    def set(self, name, value):
        """x.set(name, value) <==> x[name] = value"""
        return self.api.set(mkey(name), self.prepare_value(value))

    def __getitem__(self, name):
        """``x.__getitem__(name) <==> x[name]``"""
        name = mkey(name)
        value = self.api.get(name)
        if value is None:
            return None
        return self.value_to_python(value)

    def __setitem__(self, name, value):
        """``x.__setitem(name, value) <==> x[name] = value``"""
        return self.api.set(mkey(name), self.prepare_value(value))

    def __delitem__(self, name):
        """``x.__delitem__(name) <==> del(x[name])``
        Returns:
            True: delete success
            False: key is not exists
        """
        name = mkey(name)
        if not self.api.delete(name):
            return False
        return True

    def __len__(self):
        """``x.__len__() <==> len(x)``"""
        if self.transaction:
            return self.api.dbsize()
        LOG.warning("dbsize is not supported by codis")

    def __contains__(self, name):
        """``x.__contains__(name) <==> name in x``"""
        return self.api.exists(mkey(name))

    def __repr__(self):
        """``x.__repr__() <==> repr(x)``"""
        return "<RedisClient: {}:{}/{}>".format(self.host,
                                                self.port,
                                                self.db or "")

    def _wrap(self, method, *args, **kwargs):
        """对执行的命令进行验证
        Args:
            method: redis的方法
        """
        LOG.debug("redis adapter execute method:%s, args=%s, kwargs=%s", method, args, kwargs)
        try:
            key = args[0]
        except IndexError:
            raise ValueError('method %s requires a key param as the first argument' % method)
        if method.upper() in NOT_SUPPORT_COMMANDS:
            LOG.error('%s is not supported by codis', method)
            raise NotSupportCommandError('method %s is not supported by codis, key=%s' % (method, key))
        codis_func = getattr(self.api, method)
        return codis_func(*args, **kwargs)

    def __getattr__(self, method):
        """用于适配未定义的redis client的函数
        """
        LOG.debug("in __getattr__ method")
        return functools.partial(self._wrap, method)

    def pipeline(self):
        '''转换为自定义pipeline
        '''
        return Pipeline(self, self.transaction)

class Pipeline(object):

    '''自定义pipeline
    '''

    def __init__(self, client, transaction=False):
        self.codis_pipeline = client.api.pipeline(transaction=transaction)

    def _wrap(self, method, *args, **kwargs):
        '''打包pipeline的方法
        Args:
            method: pipeline要执行的方法
            args: pipeline执行方法的参数
            kwargs: pipeline字典参数
        '''
        LOG.debug("pipeline execute method:%s, args=%s, kwargs=%s", method, args, kwargs)
        try:
            key = args[0]
        except:
            raise ValueError("'%s' requires a key param as the first argument" % method)
        if not self.transaction and method.upper() in NOT_SUPPORT_COMMANDS:
            LOG.error('%s is not supported by codis', method)
            raise NotSupportCommandError('method %s is not supported by codis, key=%s' % (method, key))
        # 执行codis
        f = getattr(self.codis_pipeline, method)
        f(*args, **kwargs)

    def execute(self):
        '''提交pipeline执行
        '''
        LOG.debug("pipeline execute flag")
        return self.codis_pipeline.execute()

    def __getattr__(self, method):
        return functools.partial(self._wrap, method)


text:
package org.matrix.androidsdk.rest.model.sync;

import java.util.Map;

// RoomsSyncResponse represents the rooms list in server sync v2 response.
public class RoomsSyncResponse {

    /**
     * Joined rooms: keys are rooms ids.
     */
    public Map<String, RoomSync> join;

    /**
     * Invitations. The rooms that the user has been invited to: keys are rooms ids.
     */
    public Map<String, InvitedRoomSync> invite;

    /**
     * Left rooms. The rooms that the user has left or been banned from: keys are rooms ids.
     */
    public Map<String, RoomSync> leave;
}


text:
<!DOCTYPE html "http://example.com/found">
<html>
<head>
<meta charset="UTF-8">
<title>HTML DOCTYPE With Full URL</title>
</head>
<body>
</body>
</html>


text:
/*
    Simple udp client
*/
#include "../../lib/platform_abstraction/socket/socket.hpp"
#define SERVER "127.0.0.1"
#define BUFLEN 512 //Max length of buffer
#define PORT 8888  //The port on which to send data

void die(char *s)
{
  perror(s);
  exit(1);
}

int main(void)
{
  // Socket is an abstraction class that we have built. This makes it so Unix
  // specific code can live in only one place. As well as allowing us to not
  // litter gross C code everywhere. You can find the source in
  // lib/PA_Socket/socket.hpp
  Socket s;

  while (true)
  {
    std::string message;
    std::cout << "Enter message to send: " << std::endl;
    std::cin >> message;
    bool result = s.send(SERVER, PORT, (uint8_t *)message.c_str(), strlen(message.c_str()));
    if (result)
    {
      std::cout << "Message successfully sent" << std::endl;
      std::cout << "Message: " << message << std::endl;
    }
    else
    {
      std::cout << "Message was not sent..." << std::endl;
    }
  }

  return 0;
}

/*
    Simple udp client example code from the interwebs
*/
/**
 * Our code basically wraps this socket API
 */

// #include<stdio.h> //printf
// #include<string.h> //memset
// #include<stdlib.h> //exit(0);
// #include<arpa/inet.h>
// #include<sys/socket.h>
//
// #define SERVER "127.0.0.1"
// #define BUFLEN 512  //Max length of buffer
// #define PORT 8888   //The port on which to send data
//
// void die(char *s)
// {
//     perror(s);
//     exit(1);
// }
//
// int main(void)
// {
//     struct sockaddr_in si_other;
//     int s, i, slen=sizeof(si_other);
//     char buf[BUFLEN];
//     char message[BUFLEN];
//
//     if ( (s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
//     {
//         die("socket");
//     }
//
//     memset((char *) &si_other, 0, sizeof(si_other));
//     si_other.sin_family = AF_INET;
//     si_other.sin_port = htons(PORT);
//
//     if (inet_aton(SERVER , &si_other.sin_addr) == 0)
//     {
//         fprintf(stderr, "inet_aton() failed\n");
//         exit(1);
//     }
//
//     while(1)
//     {
//         printf("Enter message : ");
//         gets(message);
//
//         //send the message
//         if (sendto(s, message, strlen(message) , 0 , (struct sockaddr *) &si_other, slen)==-1)
//         {
//             die("sendto()");
//         }
//
//         //receive a reply and print it
//         //clear the buffer by filling null, it might have previously received data
//         memset(buf,'\0', BUFLEN);
//         //try to receive some data, this is a blocking call
//         if (recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen) == -1)
//         {
//             die("recvfrom()");
//         }
//
//         puts(buf);
//     }
//
//     close(s);
//     return 0;
// }


text:
=====
Usage
=====

.. py:module:: osm_field

Model Layer
===========

You need to add three model fields to your model:

1. :class:`~fields.OSMField`
2. :class:`~fields.LatitudeField`
3. :class:`~fields.LongitudeField`

**django-osm-field** expects them to have a certain name schema: The
:class:`~fields.OSMField` defines the base name, the
:class:`~fields.LatitudeField` and :class:`~fields.LongitudeField` have the
same name appended with ``_lat`` and ``_lon`` respectively. See the following
example to get an idea:

.. code-block:: python

    from django.db import models

    from osm_field.fields import LatitudeField, LongitudeField, OSMField

    class MyModel(models.Model):
        location = OSMField()
        location_lat = LatitudeField()
        location_lon = LongitudeField()

It is possible, though, to overwrite the default naming for latitude and
longitude fields by giving their names as arguments to the
:class:`~fields.OSMField`:

.. code-block:: python

    class MyModel(models.Model):
        location = OSMField(lat_field='latitude', lon_field='longitude')
        latitude = LatitudeField()
        longitude = LongitudeField()

Form Layer
==========

.. code-block:: python

    from django import forms

    from .models import MyModel

    class MyModelForm(forms.ModelForm):

        class Meta:
            fields = ('location', 'location_lat', 'location_lon', )
            model = MyModel

View Layer
==========

.. code-block:: python

    from django.views.generic import CreateView

    from .forms import MyModelForm
    from .models import MyModel

    class MyCreateView(CreateView):
        form_class = MyModelForm
        model = MyModel

.. _usage-template-layer:

Template Layer
==============

**django-osm-field** shipps with a minimized `jQuery`_ version. To access it in a template use the ``static`` templatetag:

.. code-block:: django

    <script type="text/javascript" src="{% static "js/vendor/jquery-2.1.0.min.js" %}"></script>

You can of course load `jQuery`_ from a CDN as well:

.. code-block:: django

    <script type="text/javascript" src="//code.jquery.com/jquery-2.1.0.min.js"></script>

To get the front-end to work, you also need to include some CSS and JavaScript files. You can do this by simply using ``{{ form.media }}`` or by adding those lines explicitly:

.. code-block:: django

    <link href="{% static "css/vendor/leaflet.css" %}" type="text/css" media="screen" rel="stylesheet" />
    <link href="{% static "css/osm_field.css" %}" type="text/css" media="screen" rel="stylesheet" />
    <script type="text/javascript" src="{% static "js/vendor/leaflet.js" %}"></script>
    <script type="text/javascript" src="{% static "js/osm_field.js" %}"></script>

In the end your template should look similar to this:

.. code-block:: django

    {% load static %}<!DOCTYPE HTML>
    <html>
      <head>
        <title></title>
        <link rel="stylesheet" href="{% static "css/example.css" %}">
        <!-- Either serve jQuery yourself -->
        <script type="text/javascript" src="{% static "js/vendor/jquery-2.1.0.min.js" %}"></script>
        <!-- or from a CDN -->
        <script type="text/javascript" src="//code.jquery.com/jquery-2.1.0.min.js"></script>
      </head>
      <body>
        {{ form.media }}
        <form action="" method="post">
          {% csrf_token %}
          {{ form.as_p }}
          <input type="submit" value="Save" />
        </form>
      </body>
    </html>

.. _jQuery: http://jquery.com/download/


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution
{
    static void Main(String[] args)
    {
        int[] input = Console.ReadLine().Split(' ').Select(x => int.Parse(x)).ToArray<int>();
        int[] road = Console.ReadLine().Split(' ').Select(x => int.Parse(x)).ToArray<int>();
        for (int i = 0; i < input[1]; i++)
        {
            int[] query = Console.ReadLine().Split(' ').Select(x => int.Parse(x)).ToArray<int>();
            Console.WriteLine(road.Skip(query[0]).Take((query[1] - query[0]) + 1).ToArray<int>().Min());
        }
        Console.ReadLine();
    }
}


text:
#include "GruCompute.h"
#include "hl_recurrent_apply.cuh"
#include "paddle/legacy/function/GruFunctor.h"
#include "paddle/legacy/utils/Util.h"

namespace paddle {

void GruCompute::init(LayerConfig &config) {
  activeNode_ = hlActiveType(config.active_type());
  activeGate_ = hlActiveType(config.active_gate_type());
}

template <>
void GruCompute::forward<0>(hl_gru_value value, int frameSize, int batchSize) {
  GruFunctor<DEVICE_TYPE_CPU, real>::compute(hppl::forward::gru_resetOutput(),
                                             hppl::forward::gru_finalOutput(),
                                             value,
                                             frameSize,
                                             batchSize,
                                             activeNode_,
                                             activeGate_);
}

template <>
void GruCompute::backward<0>(hl_gru_value value,
                             hl_gru_grad grad,
                             int frameSize,
                             int batchSize) {
  GruGradFunctor<DEVICE_TYPE_CPU, real>::compute(
      hppl::backward::gru_stateGrad(),
      hppl::backward::gru_resetGrad(),
      value,
      grad,
      frameSize,
      batchSize,
      activeNode_,
      activeGate_);
}

}  // namespace paddle


text:
'use strict';

var db = require('../models/sequelize');

var PSW_RESET_TOKEN_VALID_FOR = 3; //hours
var ONE_HOUR = 3600000;
var repo = {};

function getEmailFromGithubProfile(profile) {
  var email;

  if(profile.emails && profile.emails.length > 0 && profile.emails[0].value)
    email = profile.emails[0].value;
  else
    email = profile.id + '@github.com';

  return email;
}

function addAvatarToProfile(provider, url, profile) {
  if(!profile.avatars)
    profile.avatars = {};

  if(!url || url.length < 1)
    return;

  profile.avatars[provider] = url;
  if(!profile.picture)
    profile.picture = url;
}

repo.getUserById = function(id) {
  return db.User.findById(id);
};

repo.createUser = function(user) {
  return db.User.count({ where: { email: user.email } })
    .then(function(c) {
      if (c > 0)
        throw 'Account with that email address already exists.';

      var dbUser = db.User.build(user);

      dbUser.set('tokens', {});
      dbUser.set('profile', {});

      return dbUser.save();
    });
};

repo.assignResetPswToken = function(email, token) {
  return db.User.findOne({ where: { email: email } })
    .then(function(user) {
      if(!user)
        throw 'No account with that email address exists.';

      user.resetPasswordToken = token;
      user.resetPasswordExpires = Date.now() + PSW_RESET_TOKEN_VALID_FOR * ONE_HOUR;

      return user.save();
    });
};

repo.changeProfileData = function(userId, reqBody) {
  return db.User.findById(userId)
    .then(function(user) {
      user.email = reqBody.email || '';
      user.profile.name = reqBody.name || '';
      user.profile.gender = reqBody.gender || '';
      user.profile.location = reqBody.location || '';
      user.profile.website = reqBody.website || '';
      user.set('profile', user.profile);

      if(user.changed('email')) {
        return db.User.count({ where: { email: user.email } })
          .then(function(c) {
            if(c > 0)
              throw 'Cannot change e-mail address, because address ' + user.email + ' already exists';

            return user.save();
          });
      }
      return user.save();
    });
};

repo.findUserByResetPswToken = function(token) {
  return db.User.findOne({
    where: {
      resetPasswordToken: token,
      resetPasswordExpires: { $gt: new Date() }
    }
  });
};

repo.removeUserById = function(userId) {
  return db.User.destroy({ where: { id: userId } });
};

repo.changeUserPassword = function(userId, newPassword) {
  return db.User.findById(userId)
    .then(function(user) {
      if(!user)
        throw 'Account not found';

      user.password = newPassword;

      return user.save();
    });
};

repo.changeUserPswAndResetToken = function(token, newPassword) {
  if(!token || token.length < 1)
    throw 'Token cannot be empty!';

  return db.User.findOne({
      where: {
        resetPasswordToken: token,
        resetPasswordExpires: { $gt: new Date() }
      }
    })
    .then(function(user) {
      if(!user)
        throw 'User was not found.';

      user.password = newPassword;
      user.set('resetPasswordToken', null);
      user.set('resetPasswordExpires', null);

      return user.save();
    });
};

repo.unlinkProviderFromAccount = function(provider, userId) {
  return db.User.findById(userId)
    .then(function(user) {
      if(!user)
        throw 'User was not found.';

      var attrInfo = {};
      attrInfo[provider + 'Id'] = null;
      attrInfo.tokens = user.tokens || {};
      attrInfo.tokens[provider.toLowerCase()] = null;
      if(provider === 'twitter')
        attrInfo.tokens.twitterSecret = null;

      return user.updateAttributes(attrInfo);
    });
};

/**
 * Facebook
 */
repo.linkFacebookProfile = function(userId, accessToken, refreshToken, profile) {
  var profileId = profile.id.toString();

  return db.User.findOne({ where: { facebookId: profileId } })
    .then(function(existingUser) {
      if (existingUser)
        throw 'There is already a Facebook account that belongs to you. Sign in with that account or delete it, then link it with your current account.';

      return db.User.findById(userId);
    })
    .then(function(user) {
      user.facebookId = profileId;
      if(!user.tokens) user.tokens = {};
      if(!user.profile) user.profile = {};
      user.tokens.facebook = accessToken;
      user.profile.name = user.profile.name || profile.displayName;
      user.profile.gender = user.profile.gender || profile._json.gender;
      addAvatarToProfile('facebook', 'https://graph.facebook.com/' + profileId + '/picture?type=large', user.profile);
      user.set('tokens', user.tokens);
      user.set('profile', user.profile);

      return user.save();
    });
};

repo.createAccFromFacebook = function(accessToken, refreshToken, profile) {
  if(!profile._json) {
    throw 'Facebook profile is missing _json property!';
  }
  var profileId = profile.id.toString();

  return db.User.findOne({ where: { facebookId: profileId } })
    .then(function(existingUser) {
      if (existingUser)
        return existingUser;

      return db.User.findOne({ where: { email: profile._json.email } })
        .then(function(emailUser) {
          if (emailUser)
            throw 'There is already an account using this email address. Sign in to that account and link it with Facebook manually from Account Settings.';

          var user = db.User.build({ facebookId: profileId });
          user.email = profile._json.email || ( profileId + '@facebook.com' );
          user.tokens = { facebook: accessToken };
          user.profile = {
            name: profile.displayName,
            gender: profile.gender
          };
          addAvatarToProfile('facebook', 'https://graph.facebook.com/' + profileId + '/picture?type=large', user.profile);
          return user.save();
        });
    });
};

/**
 * GitHub
 */
repo.linkGithubProfile = function(userId, accessToken, tokenSecret, profile) {
  var profileId = profile.id.toString();

  return db.User.findOne({ where: { githubId: profileId } })
    .then(function(existingUser) {
      if (existingUser)
        throw 'There is already a GitHub account that belongs to you. Sign in with that account or delete it, then link it with your current account.';

      return db.User.findById(userId);
    })
    .then(function(user) {
      user.githubId = profileId;
      if(!user.tokens) user.tokens = {};
      if(!user.profile) user.profile = {};
      user.tokens.github = accessToken;
      user.profile.name = user.profile.name || profile.displayName;
      user.profile.location = user.profile.location || profile._json.location;
      user.profile.website = user.profile.website || profile._json.blog;
      addAvatarToProfile('github', profile._json.avatar_url, user.profile);
      user.set('tokens', user.tokens);
      user.set('profile', user.profile);

      return user.save();
    });
};

repo.createAccFromGithub = function(accessToken, tokenSecret, profile) {
  var profileId = profile.id.toString();
  var email = getEmailFromGithubProfile(profile);

  if(!profile._json)
    profile._json = {};

  return db.User.findOne({ where: { githubId: profileId } })
    .then(function(existingUser) {
      if (existingUser)
        return existingUser;

      return db.User.findOne({ where: { email: email } })
        .then(function(emailUser) {
          if (emailUser)
            throw 'There is already an account using this email address. Sign in to that account and link it with GitHub manually from Account Settings.';

          var user = db.User.build({ githubId: profileId });
          user.email = email;
          user.tokens = { github: accessToken };
          user.profile = {
            name: profile.displayName,
            location: profile._json.location,
            website: profile._json.blog
          };
          addAvatarToProfile('github', profile._json.avatar_url, user.profile);
          return user.save();
        });
    });
};

/**
 * Twitter
 */
repo.linkTwitterProfile = function(userId, accessToken, tokenSecret, profile) {
  return db.User.findOne({ where: { twitterId: profile.id.toString() } })
    .then(function(existingUser) {
      if (existingUser)
        throw 'There is already a Twitter account that belongs to you. Sign in with that account or delete it, then link it with your current account.';

      return db.User.findById(userId);
    })
    .then(function(user) {
      user.twitterId = profile.id.toString();
      if(!user.tokens) user.tokens = {};
      if(!user.profile) user.profile = {};
      user.tokens.twitter = accessToken;
      user.tokens.twitterSecret = tokenSecret;
      user.profile.name = user.profile.name || profile.displayName;
      user.profile.location = user.profile.location || profile._json.location;
      addAvatarToProfile('twitter', profile._json.profile_image_url_https, user.profile);
      user.set('tokens', user.tokens);
      user.set('profile', user.profile);

      return user.save();
    });
};

repo.createAccFromTwitter = function(accessToken, tokenSecret, profile) {
  return db.User.findOne({ where: { twitterId: profile.id.toString() } })
    .then(function(existingUser) {
      if (existingUser)
        return existingUser;

      var user = db.User.build({ twitterId: profile.id.toString() });
      user.email = profile.username + "@twitter.com";
      user.tokens = { twitter: accessToken, twitterSecret: tokenSecret };
      user.profile = {
        name: profile.displayName,
        location: profile._json.location
      };
      addAvatarToProfile('twitter', profile._json.profile_image_url_https, user.profile);
      return user.save();
    });
};

/**
 * Google
 */
repo.linkGoogleProfile = function(userId, accessToken, tokenSecret, profile) {
  return db.User.findOne({ where: { googleId: profile.id.toString() } })
    .then(function(existingUser) {
      if (existingUser)
        throw 'There is already a Google account that belongs to you. Sign in with that account or delete it, then link it with your current account.';

      return db.User.findById(userId);
    })
    .then(function(user) {
      user.googleId = profile.id.toString();
      if(!user.tokens) user.tokens = {};
      if(!user.profile) user.profile = {};
      user.tokens.google = accessToken;
      user.profile.name = user.profile.name || profile.displayName;
      user.profile.gender = user.profile.gender || profile.gender;
      addAvatarToProfile('google', (profile._json.image ? profile._json.image.url : ''), user.profile);
      user.set('tokens', user.tokens);
      user.set('profile', user.profile);

      return user.save();
    });
};

repo.createAccFromGoogle = function(accessToken, tokenSecret, profile) {
  return db.User.findOne({ where: { googleId: profile.id.toString() } })
    .then(function(existingUser) {
      if (existingUser)
        return existingUser;

      return db.User.findOne({ where: { email: profile.emails[0].value } })
        .then(function(existingEmailUser) {
          if (existingEmailUser)
            throw 'There is already an account using this email address. Sign in to that account and link it with Google manually from Account Settings.';

          var user = db.User.build({ googleId: profile.id.toString() });
          user.email = profile.emails[0].value;
          user.tokens = { google: accessToken };
          user.profile = {
            name: profile.displayName,
            gender: profile.gender
          };
          addAvatarToProfile('google', (profile._json.image ? profile._json.image.url : ''), user.profile);
          return user.save();
        });
    });
};

/**
 * LinkedIn
 */
repo.linkLinkedInProfile = function(userId, accessToken, tokenSecret, profile) {
  return db.User.findOne({ where: { linkedInId: profile.id.toString() } })
    .then(function(existingUser) {
      if (existingUser)
        throw 'There is already a LinkedIn account that belongs to you. Sign in with that account or delete it, then link it with your current account.';

      return db.User.findById(userId);
    })
    .then(function(user) {
      user.linkedInId = profile.id.toString();
      if(!user.tokens) user.tokens = {};
      if(!user.profile) user.profile = {};
      user.tokens.linkedin = accessToken;
      user.profile.name = user.profile.name || profile.displayName;
      user.profile.location = user.profile.location || (profile._json.location) ? profile._json.location.name : '';
      addAvatarToProfile('linkedin', profile._json.pictureUrl, user.profile);
      user.profile.website = user.profile.website || profile._json.publicProfileUrl;
      user.set('tokens', user.tokens);
      user.set('profile', user.profile);

      return user.save();
    });
};

repo.createAccFromLinkedIn = function(accessToken, tokenSecret, profile) {
  return db.User.findOne({ where: { linkedInId: profile.id.toString() } })
    .then(function(existingUser) {
      if (existingUser)
        return existingUser;

      return db.User.findOne({ where: { email: profile._json.emailAddress } })
        .then(function(existingEmailUser) {
          if (existingEmailUser)
            throw 'There is already an account using this email address. Sign in to that account and link it with LinkedIn manually from Account Settings.';

          var user = db.User.build({ linkedInId: profile.id.toString() });
          user.email = profile._json.emailAddress;
          user.tokens = { linkedin: accessToken };
          user.profile = {
            name: profile.displayName,
            location: (profile._json.location) ? profile._json.location.name : '',
            website: profile._json.publicProfileUrl
          };
          addAvatarToProfile('linkedin', profile._json.pictureUrl, user.profile);
          return user.save();
        });
    });
};

module.exports = repo;


text:
#include <aws/s3-crt/model/GetObjectTorrentResult.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>

#include <utility>

using namespace Aws::S3Crt::Model;
using namespace Aws::Utils::Stream;
using namespace Aws::Utils;
using namespace Aws;

GetObjectTorrentResult::GetObjectTorrentResult() :
    m_requestCharged(RequestCharged::NOT_SET)
{
}

GetObjectTorrentResult::GetObjectTorrentResult(GetObjectTorrentResult&& toMove) :
    m_body(std::move(toMove.m_body)),
    m_requestCharged(toMove.m_requestCharged)
{
}

GetObjectTorrentResult& GetObjectTorrentResult::operator=(GetObjectTorrentResult&& toMove)
{
   if(this == &toMove)
   {
      return *this;
   }

   m_body = std::move(toMove.m_body);
   m_requestCharged = toMove.m_requestCharged;

   return *this;
}

GetObjectTorrentResult::GetObjectTorrentResult(Aws::AmazonWebServiceResult<ResponseStream>&& result) :
    m_requestCharged(RequestCharged::NOT_SET)
{
  *this = std::move(result);
}

GetObjectTorrentResult& GetObjectTorrentResult::operator =(Aws::AmazonWebServiceResult<ResponseStream>&& result)
{
  m_body = result.TakeOwnershipOfPayload();

  const auto& headers = result.GetHeaderValueCollection();
  const auto& requestChargedIter = headers.find("x-amz-request-charged");
  if(requestChargedIter != headers.end())
  {
    m_requestCharged = RequestChargedMapper::GetRequestChargedForName(requestChargedIter->second);
  }

   return *this;
}


text:
import os
import os.path
import stat

from rez.package_copy import copy_package
from rez.exceptions import ContextBundleError
from rez.utils.logging_ import print_info, print_warning
from rez.utils.yaml import save_yaml
from rez.utils.platform_ import platform_
from rez.utils.filesystem import is_subdirectory
from rez.util import which

def bundle_context(context, dest_dir, force=False, skip_non_relocatable=False,
                   quiet=False, patch_libs=False, verbose=False):
    """Bundle a context and its variants into a relocatable dir.

    This creates a copy of a context with its variants retargeted to a local
    package repository containing only the variants the context uses. The
    generated file structure looks like so:

        /dest_dir/
            /context.rxt
            /packages/
                /foo/1.1.1/package.py
                          /...(payload)...
                /bah/4.5.6/package.py
                          /...(payload)...

    Args:
        context (`ResolvedContext`): Context to bundle
        dest_dir (str): Destination directory. Must not exist.
        force (bool): If True, relocate package even if non-relocatable. Use at
            your own risk. Overrides `skip_non_relocatable`.
        skip_non_relocatable (bool): If True, leave non-relocatable packages
            unchanged. Normally this will raise a `PackageCopyError`.
        quiet (bool): Suppress all output
        patch_libs (bool): If True, modify libs and executables within the
            bundle to patch any references to external packages back to their
            equivalents within the bundle. See the wiki for more details on this.
        verbose (bool): Verbose mode (quiet will override)
    """
    bundler = _ContextBundler(
        context=context,
        dest_dir=dest_dir,
        force=force,
        skip_non_relocatable=skip_non_relocatable,
        patch_libs=patch_libs,
        quiet=quiet,
        verbose=verbose
    )

    bundler.bundle()

class _ContextBundler(object):
    """Performs context bundling.
    """
    def __init__(self, context, dest_dir, force=False, skip_non_relocatable=False,
                 quiet=False, patch_libs=False, verbose=False):
        if quiet:
            verbose = False
        if force:
            skip_non_relocatable = False

        self.context = context
        self.dest_dir = dest_dir
        self.force = force
        self.skip_non_relocatable = skip_non_relocatable
        self.quiet = quiet
        self.patch_libs = patch_libs
        self.verbose = verbose

        self.logs = []

        # dict with:
        # key: package name
        # value: (Variant, Variant) (src and dest variants)
        self.copied_variants = {}

    def bundle(self):
        if os.path.exists(self.dest_dir):
            raise ContextBundleError("Dest dir must not exist: %s" % self.dest_dir)

        if not self.quiet:
            label = self.context.load_path or "context"
            print_info("Bundling %s into %s...", label, self.dest_dir)

        # initialize the bundle
        self._init_bundle()

        # copy the variants from the context into the bundle
        relocated_package_names = self._copy_variants()

        # write a copy of the context, with refs changed to bundled variants
        self._write_retargeted_context(relocated_package_names)

        # apply patching to retarget dynamic linker to bundled packages
        if self.patch_libs:
            self._patch_libs()

        # finalize the bundle
        self._finalize_bundle()

    @property
    def _repo_path(self):
        return os.path.join(self.dest_dir, "packages")

    def _info(self, msg, *nargs):
        self.logs.append("INFO: %s" % (msg % nargs))

    def _verbose_info(self, msg, *nargs):
        if self.verbose:
            print_info(msg, *nargs)

    def _warning(self, msg, *nargs):
        print_warning(msg, *nargs)
        self.logs.append("WARNING: %s" % (msg % nargs))

    def _init_bundle(self):
        os.mkdir(self.dest_dir)
        os.mkdir(self._repo_path)

        # bundle.yaml needs to be written even though it's currently empty.
        # This file is used to detect that this is a bundle when the rxt is
        # written (which is needed so variant handle location paths can be made
        # relative).
        #
        bundle_metafile = os.path.join(self.dest_dir, "bundle.yaml")
        with open(bundle_metafile, 'w'):
            pass

        # Bundled repos are always memcached disabled because they're on local disk
        # (so access should be fast); but also, local repo paths written to shared
        # memcached instance could easily clash.
        #
        settings_filepath = os.path.join(self._repo_path, "settings.yaml")
        save_yaml(settings_filepath, disable_memcached=True)

    def _finalize_bundle(self):
        # write metafile
        bundle_metafile = os.path.join(self.dest_dir, "bundle.yaml")
        save_yaml(bundle_metafile, logs=self.logs)

    def _copy_variants(self):
        relocated_package_names = []

        for variant in self.context.resolved_packages:
            package = variant.parent

            if self.skip_non_relocatable and not package.is_relocatable:
                self._warning(
                    "Skipped bundling of non-relocatable package %s",
                    package.qualified_name
                )
                continue

            result = copy_package(
                package=package,
                dest_repository=self._repo_path,
                variants=[variant.index],
                force=self.force,
                keep_timestamp=True,
                verbose=self.verbose
            )

            assert "copied" in result
            assert len(result["copied"]) == 1
            src_variant, dest_variant = result["copied"][0]

            self.copied_variants[package.name] = (src_variant, dest_variant)
            self._info("Copied %s to %s", src_variant.uri, dest_variant.uri)

            relocated_package_names.append(package.name)

        return relocated_package_names

    def _write_retargeted_context(self, relocated_package_names):
        rxt_filepath = os.path.join(self.dest_dir, "context.rxt")

        bundled_context = self.context.retargeted(
            package_paths=[self._repo_path],
            package_names=relocated_package_names,
            skip_missing=True
        )

        bundled_context.save(rxt_filepath)
        self._verbose_info("Bundled context written to to %s", rxt_filepath)

    def _patch_libs(self):
        # TODO
        if platform_.name in ("osx", "windows"):
            return

        self._patch_libs_linux()

    def _patch_libs_linux(self):
        """Fix elfs that reference elfs outside of the bundle.

        Finds elf files, inspects their runpath/rpath, then looks to see if
        those paths map to packages also inside the bundle. If they do, those
        rpath entries are remapped to form "$ORIGIN/{relative-path}".
        """
        from rez.utils.elf import get_rpaths, patch_rpaths

        elfs = self._find_files(
            executable=True,
            filename_substrs=(".so", ".so.", ".so-")
        )

        if not elfs:
            self._info("No elfs found, thus no patching performed")
            return

        readelf = which("readelf")
        patchelf = which("patchelf")

        if not readelf:
            self._warning(
                "Could not patch %d files: cannot find 'readelf' utility.",
                len(elfs)
            )
            return

        for elf in elfs:
            try:
                rpaths = get_rpaths(elf)
            except RuntimeError as e:

                # there can be lots of false positives (not an elf) due to
                # executable shebanged scripts. Ignore these.
                #
                msg = str(e)
                if "Not an ELF file" in msg or \
                        "Failed to read file header" in msg:
                    continue

                self._warning(msg)
                continue

            if not rpaths:
                continue  # nothing to do

            # remap rpath entries where equivalent bundled path is found
            new_rpaths = []

            for rpath in rpaths:

                # leave relpaths as-is, can't do sensible remapping.
                # Note that os.path.isabs('$ORIGIN/...') equates to False
                #
                if not os.path.isabs(rpath):
                    new_rpaths.append(rpath)
                    continue

                new_rpath = None

                for (src_variant, dest_variant) in self.copied_variants.values():
                    if is_subdirectory(rpath, src_variant.root):

                        # rpath is within the payload of another package that
                        # is present in the bundle. Here we remap to
                        # '$ORIGIN/{relpath}' form
                        #
                        relpath = os.path.relpath(rpath, src_variant.root)
                        new_rpath_abs = os.path.join(dest_variant.root, relpath)

                        elfpath = os.path.dirname(elf)
                        new_rel_rpath = os.path.relpath(new_rpath_abs, elfpath)

                        new_rpath = os.path.join("$ORIGIN", new_rel_rpath)
                        break

                if new_rpath:
                    new_rpaths.append(new_rpath)
                    self._info(
                        "Remapped rpath %s in file %s to %s",
                        rpath, elf, new_rpath
                    )
                else:
                    new_rpaths.append(rpath)

            if new_rpaths == rpaths:
                self._info(
                    "Left rpaths unchanged in %s: [%s]",
                    elf, ':'.join(rpaths)
                )
                continue

            # use patchelf to replace rpath
            if not patchelf:
                self._warning(
                    "Could not patch rpaths in %s from [%s] to [%s]: cannot "
                    "find 'patchelf' utility.",
                    elf, ':'.join(rpaths), ':'.join(new_rpaths)
                )
                continue

            try:
                patch_rpaths(elf, new_rpaths)
            except RuntimeError as e:
                self._warning(str(e))
                continue

            self._info(
                "Patched rpaths in file %s from [%s] to [%s]",
                elf, ':'.join(rpaths), ':'.join(new_rpaths)
            )

    def _find_files(self, executable=False, filename_substrs=None):
        found_files = []

        # iterate over payload of each package
        for (_, dest_variant) in self.copied_variants.values():
            for root, _, files in os.walk(dest_variant.root):
                self._verbose_info("Searching for elfs to patch in %s...", root)

                for filename in files:
                    filepath = os.path.join(root, filename)
                    if os.path.islink(filepath):
                        continue

                    if executable:
                        st = os.stat(filepath)
                        if st.st_mode & (stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH):
                            found_files.append(filepath)
                            continue

                    for substr in (filename_substrs or []):
                        if substr in filename:
                            found_files.append(filepath)
                            break

        return found_files


text:
var parent = require('../../stable/number/parse-int');

module.exports = parent;


text:
require 'spec_helper'

module Spree
  describe Api::StockLocationsController, :type => :controller do
    render_views

    let!(:stock_location) { create(:stock_location) }
    let!(:attributes) { [:id, :name, :address1, :address2, :city, :state_id, :state_name, :country_id, :zipcode, :phone, :active] }

    before do
      stub_authentication!
    end

    context "as a user" do
      describe "#index" do
        it "can see active stock locations" do
          api_get :index
          expect(response).to be_success
          stock_locations = json_response['stock_locations'].map { |sl| sl['name'] }
          expect(stock_locations).to include stock_location.name
        end

        it "cannot see inactive stock locations" do
          stock_location.update_attributes!(active: false)
          api_get :index
          expect(response).to be_success
          stock_locations = json_response['stock_locations'].map { |sl| sl['name'] }
          expect(stock_locations).not_to include stock_location.name
        end
      end

      describe "#show" do
        it "can see active stock locations" do
          api_get :show, id: stock_location.id
          expect(response).to be_success
          expect(json_response['name']).to eq stock_location.name
        end

        it "cannot see inactive stock locations" do
          stock_location.update_attributes!(active: false)
          api_get :show, id: stock_location.id
          expect(response).to be_not_found
        end
      end

      describe "#create" do
        it "cannot create a new stock location" do
          params = {
            stock_location: {
              name: "North Pole",
              active: true
            }
          }

          api_post :create, params
          response.status.should == 401
        end
      end

      describe "#update" do
        it "cannot update a stock location" do
          api_put :update, :stock_location => { :name => "South Pole" }, :id => stock_location.to_param
          response.status.should == 401
        end
      end

      describe "#destroy" do
        it "cannot delete a stock location" do
          api_put :destroy, :id => stock_location.to_param
          response.status.should == 401
        end
      end
    end

    context "as an admin" do
      sign_in_as_admin!

      describe "#index" do
        it "can see active stock locations" do
          api_get :index
          expect(response).to be_success
          stock_locations = json_response['stock_locations'].map { |sl| sl['name'] }
          expect(stock_locations).to include stock_location.name
        end

        it "can see inactive stock locations" do
          stock_location.update_attributes!(active: false)
          api_get :index
          expect(response).to be_success
          stock_locations = json_response['stock_locations'].map { |sl| sl['name'] }
          expect(stock_locations).to include stock_location.name
        end

        it "gets stock location information" do
          api_get :index
          json_response['stock_locations'].first.should have_attributes(attributes)
          json_response['stock_locations'].first['country'].should_not be_nil
          json_response['stock_locations'].first['state'].should_not be_nil
        end

        it 'can control the page size through a parameter' do
          create(:stock_location)
          api_get :index, per_page: 1
          json_response['count'].should == 1
          json_response['current_page'].should == 1
          json_response['pages'].should == 2
        end

        it 'can query the results through a paramter' do
          expected_result = create(:stock_location, name: 'South America')
          api_get :index, q: { name_cont: 'south' }
          json_response['count'].should == 1
          json_response['stock_locations'].first['name'].should eq expected_result.name
        end

      end

      describe "#show" do
        it "can see active stock locations" do
          api_get :show, id: stock_location.id
          expect(response).to be_success
          expect(json_response['name']).to eq stock_location.name
        end

        it "can see inactive stock locations" do
          stock_location.update_attributes!(active: false)
          api_get :show, id: stock_location.id
          expect(response).to be_success
          expect(json_response['name']).to eq stock_location.name
        end
      end

      describe "#create" do
        it "can create a new stock location" do
          params = {
            stock_location: {
              name: "North Pole",
              active: true
            }
          }

          api_post :create, params
          response.status.should == 201
          json_response.should have_attributes(attributes)
        end
      end

      describe "#update" do
        it "can update a stock location" do
          params = {
            id: stock_location.to_param,
            stock_location: {
              name: "South Pole"
            }
          }

          api_put :update, params
          response.status.should == 200
          json_response['name'].should eq 'South Pole'
        end
      end

      describe "#destroy" do
        it "can delete a stock location" do
          api_delete :destroy, id: stock_location.to_param
          response.status.should == 204
          lambda { stock_location.reload }.should raise_error(ActiveRecord::RecordNotFound)
        end
      end
    end
  end
end


text:
>**Disclaimer**: It's a prototype full of unexpected behavior like throwing nondescript errors when using single quotes when it expects double quotes. I fully intend to rip out the prototype code and replace it with proper salt template rendering code. Just have to find the time to dig into it.

![jinjabread](http://i.imgur.com/HbGvgSj.png)

![resizable](http://i.imgur.com/LYyvrSj.gif)

**Jinjabread** is a very simple jinja syntax checking tool for creating [SaltStack](https://www.saltstack.com) states.

It's divided into 4 windows, *Grains*, *Pillar*, *State* and *Output*, assuming you're familiar with SaltStack this does not require much explanation. If none of that makes sense, SaltStack is a *Remote Execution Framework* with *Configuration Management* capabilities. If you're a sysadmin/devops/ITguy supporting IT infrastructure of any size, SaltStack is great and you should check it out.

**Essentially**, you type in the *grains* and *pillar* data you want, write your *state* template with your *jinja2*, press `ctrl+b` or click the render button.

If things go well, it produces the *state* in the *output* to make sure it rendered correctly. If an error has occured it should tell you with relative accuracy where it went wrong.

***But, why?***

Figuring out where and why your state broke can be an arduous task,
especially if you are just starting out with SaltStack for the first time.
This tool aims to help either getting started writing *states*,
or just debugging that one state you just can't seem to fix.

I hope you enjoy it

[Try a demo at jinjabread.christopherbaklid.com](http://jinjabread.christopherbaklid.com/)

----------------------------------------------------------------------

Features
=============================

#### Current
- Renders Jinja2 and YAML

#### Future

- Shareable links *to share with others for help*
- Proper salt integration, to use salt modules

#### Improvements

- Support for multiline comments `{# multiline comment #}` *throws some confusing `yaml` syntax errors*

#### Known issues

- Does not work in *Internet Explorer*

Dependencies
=============================

python 3.5+
pipenv 2018+

Usage
=============================

```bash
git clone https://github.com/Inveracity/jinjabread.git
cd jinjabread
pip install pipenv
pipenv sync
pipenv run start
```

Browse to `localhost:5000`

Docker
=============================

#### Build container

```bash
pipenv run build
```

#### Test container

```bash
docker run -d -p 80:80 --name jinjabread jinjabread:latest
```

Browse to `localhost/`

Acknowledgements
=============================

[SaltStack](https://www.saltstack.com) - Extensive use of their code from github

[Codemirror](https://codemirror.net) - Code highlighting in textarea

[Bootstrap3](https://getbootstrap.com) - general styling

[jqueryUI](https://jqueryui.com/) - Resizable divs

[PersistState](https://github.com/togakangaroo/persistState) - persist jqueryUI through refresh


text:
var config = require(__dirname+'/config.js');
var r = require(__dirname+'/../lib')(config);
var util = require(__dirname+'/util/common.js');
var assert = require('assert');

var uuid = util.uuid;
var It = util.It;

var uuid = util.uuid;
var dbName, tableName, result;

It("ReqlResourceError", function* (done) {
  try {
    result = yield r.expr([1,2,3,4]).run({arrayLimit: 2});
  }
  catch(e) {
    assert.equal(e.name, 'ReqlResourceError');
    done()
  }
})
It("ReqlLogicError", function* (done) {
  try {
    result = yield r.expr(1).add("foo").run();
  }
  catch(e) {
    assert.equal(e.name, 'ReqlLogicError');
    done()
  }
})

It("ReqlOpFailedError", function* (done) {
  try {
    result = yield r.db('DatabaseThatDoesNotExist').tableList().run();
  }
  catch(e) {
    assert.equal(e.name, 'ReqlOpFailedError');
    done()
  }
})

It("ReqlUserError", function* (done) {
  try {
    result = yield r.branch(r.error('a'), 1, 2).run()
  }
  catch(e) {
    assert.equal(e.name, 'ReqlUserError');
    done()
  }
})

// Missing tests for ReqlInternalError and ReqlOpIndeterminateError
// as there are no easy way to trigger those


text:
layout: page
title: About
permalink: /about/
---

### Moi en 7 mots et 2 chiffres

Développeur de 28 ans récemment déménagé à Bordeaux.

### Contact

[fabien.lamarque+blog@gmail.com](mailto:fabien.lamarque+blog@gmail.com)


text:
/** @jsx h */

import h from '../../../helpers/h'

export default function (change) {
  change.toggleMark({
    type: 'bold',
    data: { thing: 'value' }
  })
}

export const input = (
  <state>
    <document>
      <paragraph>
        <anchor /><b thing="value">w</b><focus />ord
      </paragraph>
    </document>
  </state>
)

export const output = (
  <state>
    <document>
      <paragraph>
        <anchor />w<focus />ord
      </paragraph>
    </document>
  </state>
)


text:
/**
 * Implements an example of Selection sort.
 *
 * In English, here's how the algorithm works:
 * Iterate left to right over the array, finding the smallest value. Swap
 * smallest value with leftmost unsorted value. Repeat on remaining unsorted
 * region of the array (shrinks towards the right).
 **/

object SelectionSort {
  def main(args: Array[String]) {
    var mess = Array(3, 9, 8, 13, 2, 5, 4);

    sort(mess)

    mess.foreach( println )
  }

  /**Implements Selection sort algorithm.*/
  def sort(a: Array[Int]): Unit = {
    val n = a.length
    for (i <- 0 until n) {
      var min = i
      for (j <- i+1 until n) {
        if (a(j) < a(min)) min = j
      }

      if (min != i) swap(a, min, i)
    }
  }

  /**Swaps two elements of an array.*/
  def swap(a: Array[Int], i: Int, j: Int): Unit = {
    val staging = a(i)
    a(i) = a(j)
    a(j) = staging
  }

}


text:
layout: post
microblog: true
date: 2017-04-28 21:50 -0400
guid: http://jack.micro.blog/2017/04/29/finished-a-giant.html
---
Finished a giant bottle of Founders' "Lizard of Koz" and it made me happy. It's my favorite beer at the moment but at 10.5% one should not drink a whole bottle.


text:
from StringIO import StringIO
import csv
from hashlib import md5

from aludel.database import get_engine
from aludel.service import (
    service, handler, get_url_params, get_json_params, set_request_id,
    APIError, BadRequestParams,
)

from twisted.internet.defer import inlineCallbacks, returnValue

from .models import (
    UniqueCodePool, CannotRedeemUniqueCode, NoUniqueCodePool, AuditMismatch,
)

@service
class UniqueCodeServiceApp(object):
    def __init__(self, conn_str, reactor):
        self.engine = get_engine(conn_str, reactor)

    def handle_api_error(self, failure, request):
        if failure.check(NoUniqueCodePool):
            raise APIError('Unique code pool does not exist.', 404)
        if failure.check(AuditMismatch):
            raise BadRequestParams(
                "This request has already been performed with different"
                " parameters.")
        return failure

    @handler(
        '/<string:unique_code_pool>/redeem/<string:request_id>',
        methods=['PUT'])
    @inlineCallbacks
    def redeem_unique_code(self, request, unique_code_pool, request_id):
        set_request_id(request, request_id)
        params = get_json_params(
            request, ['transaction_id', 'user_id', 'unique_code'])
        audit_params = {
            'request_id': request_id,
            'transaction_id': params.pop('transaction_id'),
            'user_id': params.pop('user_id'),
        }
        conn = yield self.engine.connect()
        pool = UniqueCodePool(unique_code_pool, conn)
        try:
            unique_code = yield pool.redeem_unique_code(
                params['unique_code'], audit_params)
        except CannotRedeemUniqueCode as e:
            # This is a normal condition, so we still return a 200 OK.
            raise APIError('Cannot redeem unique code: %s' % (e.reason,), 200)
        finally:
            yield conn.close()

        returnValue({
            'unique_code': unique_code['unique_code'],
            'flavour': unique_code['flavour'],
        })

    @handler('/<string:unique_code_pool>/audit_query', methods=['GET'])
    @inlineCallbacks
    def audit_query(self, request, unique_code_pool):
        params = get_url_params(
            request, ['field', 'value'], ['request_id'])
        if params['field'] not in [
                'request_id', 'transaction_id', 'user_id', 'unique_code']:
            raise BadRequestParams('Invalid audit field.')

        conn = yield self.engine.connect()
        pool = UniqueCodePool(unique_code_pool, conn)
        try:
            query = {
                'request_id': pool.query_by_request_id,
                'transaction_id': pool.query_by_transaction_id,
                'user_id': pool.query_by_user_id,
                'unique_code': pool.query_by_unique_code,
            }[params['field']]
            rows = yield query(params['value'])
        finally:
            yield conn.close()

        results = [{
            'request_id': row['request_id'],
            'transaction_id': row['transaction_id'],
            'user_id': row['user_id'],
            'request_data': row['request_data'],
            'response_data': row['response_data'],
            'error': row['error'],
            'created_at': row['created_at'].isoformat(),
        } for row in rows]
        returnValue({'results': results})

    @handler('/<string:unique_code_pool>', methods=['PUT'])
    @inlineCallbacks
    def create_pool(self, request, unique_code_pool):
        conn = yield self.engine.connect()
        pool = UniqueCodePool(unique_code_pool, conn)
        try:
            already_exists = yield pool.exists()
            if not already_exists:
                request.setResponseCode(201)
                yield pool.create_tables()
        finally:
            yield conn.close()

        returnValue({'created': not already_exists})

    @handler(
        '/<string:unique_code_pool>/import/<string:request_id>',
        methods=['PUT'])
    @inlineCallbacks
    def import_unique_codes(self, request, unique_code_pool, request_id):
        set_request_id(request, request_id)
        content_md5 = request.requestHeaders.getRawHeaders('Content-MD5')
        if content_md5 is None:
            raise BadRequestParams("Missing Content-MD5 header.")
        content_md5 = content_md5[0].lower()
        content = request.content.read()
        if content_md5 != md5(content).hexdigest().lower():
            raise BadRequestParams(
                "Content-MD5 header does not match content.")

        reader = csv.DictReader(StringIO(content))
        row_iter = lowercase_row_keys(reader)

        conn = yield self.engine.connect()
        pool = UniqueCodePool(unique_code_pool, conn)
        try:
            yield pool.import_unique_codes(request_id, content_md5, row_iter)
        finally:
            yield conn.close()

        request.setResponseCode(201)
        returnValue({'imported': True})

    @handler(
        '/<string:unique_code_pool>/unique_code_counts', methods=['GET'])
    @inlineCallbacks
    def unique_code_counts(self, request, unique_code_pool):
        # This sets the request_id on the request object.
        get_url_params(request, [], ['request_id'])

        conn = yield self.engine.connect()
        pool = UniqueCodePool(unique_code_pool, conn)
        try:
            rows = yield pool.count_unique_codes()
        finally:
            yield conn.close()

        results = [{
            'flavour': row['flavour'],
            'used': row['used'],
            'count': row['count'],
        } for row in rows]
        returnValue({'unique_code_counts': results})

def lowercase_row_keys(rows):
    for row in rows:
        yield dict((k.lower(), v) for k, v in row.iteritems())


text:
(function () {
  var setup = function () {
    questionsIdx.version = lunr.version

    var store = lunr.TokenStore.load(questionsIdx.tokenStore)
  }

  bench('tokenStore#getNode', function () {
    store.getNode('javascript')
  }, { setup: setup })

  bench('tokenStore#has non existant term', function () {
    store.has('qwertyuiop')
  }, { setup: setup })

  bench('tokenStore#has term exists', function () {
    store.has('javascript')
  }, { setup: setup })

})()


text:
//
//  Author:
//    Chronium Silver (Andrei Dimitriu) onlivechronium@gmail.com
//
//  Copyright (c) 2015, Chronium @ ChronoStudios
//
//  All rights reserved.
//
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
//   list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.Scripting.Hosting;
using IronPython.Hosting;

namespace ChronosEngine.Scripting {
	public class ScriptManager {
		/// <summary>
		/// Gets the scripts.
		/// </summary>
		/// <value>The scripts.</value>
		public Dictionary<string, Script> Scripts { get; }
		/// <summary>
		/// Gets the scripting engine.
		/// </summary>
		/// <value>The scripting engine.</value>
		public ScriptEngine ScriptingEngine { get; }

		/// <summary>
		/// Gets the scripting scope.
		/// </summary>
		/// <value>The scripting scope.</value>
		public ScriptScope ScriptScope { get; }

		/// <summary>
		/// Initializes a new instance of the <see cref="ChronosEngine.Scripting.ScriptManager"/> class.
		/// </summary>
		public ScriptManager() {
			this.Scripts = new Dictionary<string, Script>();
			ScriptingEngine = Python.CreateEngine();
			var paths = ScriptingEngine.GetSearchPaths();
			paths.Add("Assets/Scripts");
			ScriptingEngine.SetSearchPaths(paths);
			ScriptScope = ScriptingEngine.CreateScope();
		}

		/// <summary>
		/// Adds a new script.
		/// </summary>
		/// <param name="script">Script name.</param>
		public void AddScript(string scriptName) {
			try {
				Scripts[scriptName] = new Script("Assets/Scripts/" + scriptName + ".py", this);
			} catch (FileNotFoundException e) {
				Console.WriteLine("Script \"{0}\" could not be found", scriptName);
				Console.WriteLine(e);
			}
		}

		public Script this[string script] {
			get {
				return this.Scripts[script];
			}
		}
	}
}


text:
export default (app) => {
    class ShareService {
        constructor() {
            this.showingAnnotations = false;
            this.callbacks = {
                toggleShowingAnnotations: {}
            };
        }

        toggleShowingAnnotations(value = !this.showingAnnotations) {
            this.showingAnnotations = value;
            Object.values(this.callbacks.toggleShowingAnnotations).forEach(c => c(value));
        }

        addCallback(key, callback) {
            const id = new Date().getTime();
            this.callbacks[key][id] = callback;
            return id;
        }

        removeCallback(key, id) {
            delete this.callbacks[key][id];
        }
    }

    app.service('shareService', ShareService);
};


text:
<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Page_Tracker_Tickets extends Abstract_Controller_Hyla_Page {

	public function action_list()
	{
		$this->view
			->bind('project', $project);

		$project = Couch_Model::factory('project', $this->couchdb)
			->find_by_slug($this->request->param('slug'));

		if ( ! $project->loaded())
			throw new HTTP_Exception_404;
	}

	public function action_new()
	{
		$this->view
			->bind('project', $project)
			->bind('ticket', $ticket)
			->bind('values', $values)
			->bind('errors', $errors);

		$project = Couch_Model::factory('project', $this->couchdb)
			->find_by_slug($this->request->param('slug'));

		if ( ! $project->loaded())
			throw new HTTP_Exception_404;

		if ($this->request->post())
		{
			$values = $this->request->post();

			try
			{
				$ticket = Couch_Model::factory('ticket', $this->couchdb);
				$ticket->values($values, array('title', 'description'));
				$ticket->set('project_id', $project->get('_id'));
				$ticket->set('created_by', $this->auth->get('_id'));
				$ticket->create();

				$this->request->redirect(Route::url('hyla/tickets', array(
					'slug' => $project->get('slug'),
				)));
			}
			catch (Validation_Exception $e)
			{
				$errors = $e->array->errors('validation');
			}
		}
	}

	public function action_view()
	{
		$this->view
			->bind('project', $project)
			->bind('ticket', $ticket);

		$project = Couch_Model::factory('project', $this->couchdb)
			->find_by_slug($this->request->param('slug'));

		$request = Request::factory(Route::get('hyla/api/tickets')->uri(array(
			'id' => $this->request->param('ticket'),
		)));
		$response = $this->oauth_client->execute($request);

		$ticket = Arr::get(json_decode($response->body(), TRUE), 'ticket');

		if ( ! $project->loaded() OR empty($ticket['_id']))
			throw new HTTP_Exception_404;
	}

	public function action_update()
	{
		$this->view
			->bind('project', $project)
			->bind('ticket', $ticket)
			->bind('values', $values)
			->bind('errors', $errors);

		$project = Couch_Model::factory('project', $this->couchdb)
			->find_by_slug($this->request->param('slug'));

		$request = Request::factory(Route::get('hyla/api/tickets')->uri(array(
			'id' => $this->request->param('ticket'),
		)));
		$response = $this->oauth_client->execute($request);

		$ticket = Arr::get(json_decode($response->body(), TRUE), 'ticket');

		if ( ! $project->loaded() OR empty($ticket['_id']))
			throw new HTTP_Exception_404;

		if ($this->request->post())
		{
			$comment = $this->request->post('comment');

			try
			{
				$ticket->add_comment($this->auth->get('_id'), $comment);
				$ticket->update();

				$this->request->redirect(Route::url('hyla/tickets', array(
					'action' => 'view',
					'slug'   => $project->get('slug'),
					'ticket' => $ticket->get('_id'),
				)));
			}
			catch (Validation_Exception $e)
			{
				$errors = $e->array->errors('validation');
			}
		}
	}

	public function action_delete()
	{
		$project = Couch_Model::factory('project', $this->couchdb)
			->find_by_slug($this->request->param('slug'));

		if ($this->request->post())
		{
			$request = Request::factory(Route::get('hyla/api/tickets')
			->uri(array(
				'id' => $this->request->param('ticket'),
			)))
			->method(Request::DELETE);
			$response = $this->oauth_client->execute($request);

			$this->request->redirect(Route::url('hyla/tickets', array(
					'slug' => $project->get('slug'),
				)));
		}

		throw new HTTP_Exception_404;
	}
}


text:
'use strict'
import * as React from 'react'
import { openDialog } from '../common/Dialog'
import { } from '../common/'
import * as CSSModules from 'react-css-modules';
import {Link} from 'react-router'
import styles from './Lecture.css'

export interface LectureProps {
	slug: string
	courseSlug: string
	title: string
	contentAccessLevel: string
	userAccessLevel: string
	time: string
	approved: boolean
}

class Lecture extends React.Component<LectureProps, {}> {
	render() {
		return this.props.approved ? this.approved() : this.denied()
	}

	approved() {
		const { courseSlug, slug, title, time } = this.props
		return (

				<Link to={`/lecture/${courseSlug}/${slug}`}>

						{title}
						{this.props.userAccessLevel == "guest" &&
						Preview}
						{time}

				</Link>

		);
	}

	denied() {
		const { courseSlug, slug, title, time } = this.props
		if(this.props.contentAccessLevel == "free") {
			return (

					 openDialog(e, "signup")}>

							{title}{time}

			);
		} else {
			return (

					<Link to="/pricing">

								{title}Gold{time}

					</Link>

			);
		}
	}

	constructor(props) {
		super(props)

		this.approved = this.approved.bind(this)
		this.denied = this.denied.bind(this)
	}
}

export default CSSModules(Lecture, styles)

function accessLevelCode(level) {
	switch(level) {
		case "guest":	return 0
		case "free":	return 1
		case "gold":	return 2
		default:		return 0
	}
}


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('login', '0002_follower'),
        ('points', '0007_auto_20160220_1118'),
    ]

    operations = [
        migrations.CreateModel(
            name='Trip',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('date_from', models.DateTimeField(auto_now_add=True)),
                ('date_to', models.DateTimeField(auto_now_add=True)),
                ('created', models.DateTimeField(auto_now_add=True)),
                ('author', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='login.BaseUser')),
                ('route', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='points.Route')),
            ],
        ),
        migrations.CreateModel(
            name='TripFollower',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('follower', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='login.BaseUser')),
                ('trip', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='points.Trip')),
            ],
        ),
    ]


text:
# parse_ft_gfx_xml

**Retrieve tags from Rockwell FactoryTalk gfx-xml file(s)**

If you had ever the task to collect or better retrieve the tags used in a FactoryTalk View Display because the tags are scattered all over the PLC program this is the right tool for you.

**How it works**

Export the displays in question to gfx-xml: Right click the Display node inside your FactoryTalk project and follow the instruction given by FactoryTalk to export one or more displays to any folder you like.

Open the command prompt and run the programm with the path to the folder which contains the xml-files:

```
Retrieve the tags of one or more FactoryTalk View Display(s) by running parse_gfx_xml from the command line with the path to the xml-files as argument (in this case "c:\temp"):

> parse_gfx_xml c:\temp

You will find the windows exe-file here: parse_ft_gfx_xml/public/
```

You can run the tool with cargo as well:

```
Clone the project and build it with cargo. Afterwards run the project with cargo:

> cargo run c:\temp
```

All xml-files will be processed one by one and for each processed xml-file a new file which only contains the retrieved tags is generated and saved in the same folder. The files which will contain the tags have the file extension ".txt".

**Dependency**

quick-xml: [Rust high performance xml reader and writer](https://github.com/tafia/quick-xml.git)

clap: [A full featured, fast Command Line Argument Parser for Rust](https://clap.rs)