text:
{-# language CPP #-}
{-# language QuasiQuotes #-}
{-# language TemplateHaskell #-}

#if __GLASGOW_HASKELL__ >= 800
{-# options_ghc -Wno-redundant-constraints #-}
#endif

module OpenCV.Photo
  ( InpaintingMethod(..)
  , inpaint
  , denoise_TVL1
  , fastNlMeansDenoisingColored
  , fastNlMeansDenoisingColoredMulti
  ) where

import "base" Data.Int ( Int32 )
import "base" Data.Word ( Word8 )
import qualified "inline-c" Language.C.Inline as C
import qualified "inline-c-cpp" Language.C.Inline.Cpp as C
import "this" OpenCV.Internal.C.Inline ( openCvCtx )
import "this" OpenCV.Internal.C.Types ( withPtr )
import "this" OpenCV.Internal.Exception
import "this" OpenCV.Internal.Photo.Constants
import "this" OpenCV.Internal.Core.Types.Mat
import "this" OpenCV.Internal.Core.Types ( withArrayPtr )
import "this" OpenCV.TypeLevel

import qualified "vector" Data.Vector as V

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

C.context openCvCtx

C.include "opencv2/core.hpp"
C.include "opencv2/photo.hpp"
C.using "namespace cv"

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

data InpaintingMethod
   = InpaintNavierStokes
     -- ^ Navier-Stokes based method.
   | InpaintTelea
     -- ^ Method by Alexandru Telea.
     deriving Show

marshalInpaintingMethod :: InpaintingMethod -> Int32
marshalInpaintingMethod = \case
  InpaintNavierStokes -> c'INPAINT_NS
  InpaintTelea        -> c'INPAINT_TELEA

{- | Restores the selected region in an image using the region neighborhood.

Example:

@
inpaintImg
    :: forall h h2 w w2 c d
     . ( Mat (ShapeT [h, w]) ('S c) ('S d) ~ Bikes_512x341
       , h2 ~ ((*) h 2)
       , w2 ~ ((*) w 2)
       )
    => Mat ('S ['S h2, 'S w2]) ('S c) ('S d)
inpaintImg = exceptError $ do
    maskInv <- bitwiseNot mask
    maskBgr <- cvtColor gray bgr maskInv
    damaged <- bitwiseAnd bikes_512x341 maskBgr
    repairedNS <- inpaint 3 InpaintNavierStokes damaged mask
    repairedT  <- inpaint 3 InpaintTelea        damaged mask
    withMatM
      (Proxy :: Proxy [h2, w2])
      (Proxy :: Proxy c)
      (Proxy :: Proxy d)
      black $ \imgM -> do
        matCopyToM imgM (V2 0 0) damaged Nothing
        matCopyToM imgM (V2 w 0) maskBgr Nothing
        matCopyToM imgM (V2 0 h) repairedNS Nothing
        matCopyToM imgM (V2 w h) repairedT  Nothing
  where
    mask = damageMask

    w = fromInteger $ natVal (Proxy :: Proxy w)
    h = fromInteger $ natVal (Proxy :: Proxy h)
@

<<doc/generated/examples/inpaintImg.png inpaintImg>>
-}
inpaint
   :: (channels `In` [1, 3])
   => Double
      -- ^ inpaintRadius - Radius of a circular neighborhood of each
      -- point inpainted that is considered by the algorithm.
   -> InpaintingMethod
   -> Mat ('S [h, w]) ('S channels) ('S Word8) -- ^ Input image.
   -> Mat ('S [h, w]) ('S 1) ('S Word8) -- ^ Inpainting mask.
   -> CvExcept (Mat ('S [h, w]) ('S channels) ('S Word8)) -- ^ Output image.
inpaint inpaintRadius method src inpaintMask = unsafeWrapException $ do
    dst <- newEmptyMat
    handleCvException (pure $ unsafeCoerceMat dst) $
      withPtr src         $ \srcPtr         ->
      withPtr inpaintMask $ \inpaintMaskPtr ->
      withPtr dst         $ \dstPtr         ->
      [cvExcept|
        cv::inpaint( *$(Mat * srcPtr)
                   , *$(Mat * inpaintMaskPtr)
                   , *$(Mat * dstPtr)
                   , $(double c'inpaintRadius)
                   , $(int32_t c'method)
                   );
      |]
  where
    c'method = marshalInpaintingMethod method
    c'inpaintRadius = realToFrac inpaintRadius

{- | Perform fastNlMeansDenoising function for colored images. Denoising is not
     per channel but in a different colour space

Example:

@
fastNlMeansDenoisingColoredImg
    :: forall h w w2 c d
     . ( Mat (ShapeT [h, w]) ('S c) ('S d) ~ Lenna_512x512
       , w2 ~ ((*) w 2)
       )
    => Mat ('S ['S h, 'S w2]) ('S c) ('S d)
fastNlMeansDenoisingColoredImg = exceptError $ do
    denoised <- fastNlMeansDenoisingColored 3 10 7 21 lenna_512x512
    withMatM
      (Proxy :: Proxy [h, w2])
      (Proxy :: Proxy c)
      (Proxy :: Proxy d)
      black $ \imgM -> do
        matCopyToM imgM (V2 0 0) lenna_512x512 Nothing
        matCopyToM imgM (V2 w 0) denoised Nothing
  where
    w = fromInteger $ natVal (Proxy :: Proxy w)
@

<<doc/generated/examples/fastNlMeansDenoisingColoredImg.png fastNlMeansDenoisingColoredImg>>
-}

fastNlMeansDenoisingColored
   :: Double -- ^ Parameter regulating filter strength for luminance component.
             -- Bigger h value perfectly removes noise but also removes image
             -- details, smaller h value preserves details but also preserves
             -- some noise
   -> Double -- ^ The same as h but for color components. For most images value
             -- equals 10 will be enough to remove colored noise and do not
             -- distort colors
   -> Int32  -- ^ templateWindowSize Size in pixels of the template patch that
             -- is used to compute weights.
             -- Should be odd. Recommended value 7 pixels
   -> Int32  -- ^ searchWindowSize. Size in pixels of the window that is used
             -- to compute weighted average for given pixel. Should be odd.
             -- Affect performance linearly: greater searchWindowsSize
             -- - greater denoising time. Recommended value 21 pixels
   -> Mat ('S [h, w]) ('S 3) ('S Word8) -- ^ Input image 8-bit 3-channel image.
   -> CvExcept (Mat ('S [h, w]) ('S 3) ('S Word8))
             -- ^ Output image same size and type as input.
fastNlMeansDenoisingColored h hColor templateWindowSize searchWindowSize src =
  unsafeWrapException $ do
    dst <- newEmptyMat
    handleCvException (pure $ unsafeCoerceMat dst) $
      withPtr src         $ \srcPtr         ->
      withPtr dst         $ \dstPtr         ->
      [cvExcept|
        cv::fastNlMeansDenoisingColored( *$(Mat * srcPtr)
                                       , *$(Mat * dstPtr)
                                       , $(double c'h)
                                       , $(double c'hColor)
                                       , $(int32_t templateWindowSize)
                                       , $(int32_t searchWindowSize)
                                       );
      |]
  where
    c'h = realToFrac h
    c'hColor = realToFrac hColor

{- | Perform fastNlMeansDenoisingColoredMulti function for colored images.
     Denoising is not pre channel but in a different colour space.
     This wrapper differs from the original OpenCV version by using all input
     images and denoising the middle one. The original version would allow
     to have some arbitrary length vector and slide window over it. As we have
     to copy the haskell vector before we can use it as `std::vector` on the cpp
     side it is easier to trim the vector before sending and use all frames.

Example:

@
fastNlMeansDenoisingColoredMultiImg
    :: forall h w w2 c d
     . ( Mat (ShapeT [h, w]) ('S c) ('S d) ~ Lenna_512x512
       , w2 ~ ((*) w 2)
       )
    => Mat ('S ['S h, 'S w2]) ('S c) ('S d)
fastNlMeansDenoisingColoredMultiImg = exceptError $ do
    denoised <- fastNlMeansDenoisingColoredMulti 3 10 7 21 (V.singleton lenna_512x512)
    withMatM
      (Proxy :: Proxy [h, w2])
      (Proxy :: Proxy c)
      (Proxy :: Proxy d)
      black $ \imgM -> do
        matCopyToM imgM (V2 0 0) lenna_512x512 Nothing
        matCopyToM imgM (V2 w 0) denoised Nothing
  where
    w = fromInteger $ natVal (Proxy :: Proxy w)
@

<<doc/generated/examples/fastNlMeansDenoisingColoredMultiImg.png fastNlMeansDenoisingColoredMultiImg>>
-}

fastNlMeansDenoisingColoredMulti
   :: Double -- ^ Parameter regulating filter strength for luminance component.
             -- Bigger h value perfectly removes noise but also removes image
             -- details, smaller h value preserves details but also preserves
             -- some noise
   -> Double -- ^ The same as h but for color components. For most images value
             -- equals 10 will be enough to remove colored noise and do not
             -- distort colors
   -> Int32  -- ^ templateWindowSize Size in pixels of the template patch that
             -- is used to compute weights. Should be odd.
             -- Recommended value 7 pixels
   -> Int32  -- ^ searchWindowSize. Size in pixels of the window that is used to
             -- compute weighted average for given pixel. Should be odd.
             -- Affect performance linearly: greater searchWindowsSize -
             -- greater denoising time. Recommended value 21 pixels
   -> V.Vector (Mat ('S [h, w]) ('S 3) ('S Word8))
             -- ^ Vector of odd number of input 8-bit 3-channel images.
   -> CvExcept (Mat ('S [h, w]) ('S 3) ('S Word8))
             -- ^ Output image same size and type as input.

fastNlMeansDenoisingColoredMulti h hColor templateWindowSize searchWindowSize srcVec =
  unsafeWrapException $ do
    dst <- newEmptyMat
    handleCvException (pure $ unsafeCoerceMat dst) $
      withArrayPtr srcVec $ \srcVecPtr      ->
      withPtr dst         $ \dstPtr         ->
      [cvExcept|
        std::vector<Mat> buffer( $(Mat * srcVecPtr)
                    , $(Mat * srcVecPtr) + $(int32_t c'temporalWindowSize) );
        cv::fastNlMeansDenoisingColoredMulti( buffer
                                            , *$(Mat * dstPtr)
                                            , $(int32_t c'imgToDenoiseIndex)
                                            , $(int32_t c'temporalWindowSize)
                                            , $(double c'h)
                                            , $(double c'hColor)
                                            , $(int32_t templateWindowSize)
                                            , $(int32_t searchWindowSize)
                                            );
      |]
  where
    c'h = realToFrac h
    c'hColor = realToFrac hColor
    c'srcVecLength = fromIntegral $ V.length srcVec
    -- if it is not odd we drop the last image
    c'temporalWindowSize
        | c'srcVecLength `mod` 2 == 1 = c'srcVecLength
        | otherwise                   = c'srcVecLength - 1
    c'imgToDenoiseIndex = (c'temporalWindowSize - 1) `div` 2

{- | Perform denoise_TVL1

Example:

@

denoise_TVL1Img
    :: forall h w w2 c d
     . ( Mat (ShapeT [h, w]) ('S c) ('S d) ~ Lenna_512x512
       , w2 ~ ((*) w 2)
       )
    => Mat ('S ['S h, 'S w2]) ('S c) ('S d)
denoise_TVL1Img = exceptError $ do
    denoised <- matChannelMapM (denoise_TVL1 2 50 . V.singleton) lenna_512x512
    withMatM
      (Proxy :: Proxy [h, w2])
      (Proxy :: Proxy c)
      (Proxy :: Proxy d)
      black $ \imgM -> do
        matCopyToM imgM (V2 0 0) lenna_512x512 Nothing
        matCopyToM imgM (V2 w 0) denoised Nothing
  where
    w = fromInteger $ natVal (Proxy :: Proxy w)
@

<<doc/generated/examples/denoise_TVL1Img.png denoise_TVL1Img>>
-}

denoise_TVL1
   :: Double -- ^ details more is more 2
   -> Int32  -- ^ Number of iterations that the algorithm will run
   -> V.Vector (Mat ('S [h, w]) ('S 1) ('S Word8))
             -- ^ Vector of odd number of input 8-bit 3-channel images.
   -> CvExcept (Mat ('S [h, w]) ('S 1) ('S Word8))
             -- ^ Output image same size and type as input.

denoise_TVL1 lambda niters srcVec = unsafeWrapException $ do
    dst <- newEmptyMat
    handleCvException (pure $ unsafeCoerceMat dst) $
      withArrayPtr srcVec $ \srcVecPtr      ->
      withPtr dst         $ \dstPtr         ->
      [cvExcept|
        std::vector<Mat> buffer( $(Mat * srcVecPtr)
                           , $(Mat * srcVecPtr) + $(int32_t c'srcVecLength) );
        cv::denoise_TVL1( buffer
                        , *$(Mat * dstPtr)
                        , $(double c'lambda)
                        , $(int32_t niters)
                        );
      |]
  where
    c'lambda = realToFrac lambda
    c'srcVecLength = fromIntegral $ V.length srcVec


text:
package org.wso2.carbon.device.mgt.mobile.internal;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.device.mgt.mobile.common.MobileDeviceMgtPluginException;
import org.wso2.carbon.device.mgt.mobile.config.MobileDeviceConfigurationManager;
import org.wso2.carbon.device.mgt.mobile.config.MobileDeviceManagementConfig;
import org.wso2.carbon.device.mgt.mobile.config.datasource.MobileDataSourceConfig;
import org.wso2.carbon.device.mgt.mobile.dao.AbstractMobileDeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.mobile.dao.util.MobileDeviceManagementDAOUtil;
import org.wso2.carbon.ndatasource.core.DataSourceService;
import org.wso2.carbon.registry.core.service.RegistryService;

import java.util.Map;

/**
 * @scr.component name="org.wso2.carbon.device.mgt.mobile.impl.internal.MobileDeviceManagementServiceComponent"
 * immediate="true"
 * @scr.reference name="org.wso2.carbon.ndatasource"
 * interface="org.wso2.carbon.ndatasource.core.DataSourceService"
 * cardinality="1..1"
 * policy="dynamic"
 * bind="setDataSourceService"
 * unbind="unsetDataSourceService"
 * @scr.reference name="registry.service"
 * interface="org.wso2.carbon.registry.core.service.RegistryService" cardinality="0..1"
 * policy="dynamic" bind="setRegistryService" unbind="unsetRegistryService"
 * <p/>
 * Adding reference to API Manager Configuration service is an unavoidable hack to get rid of NPEs thrown while
 * initializing APIMgtDAOs attempting to register APIs programmatically. APIMgtDAO needs to be proper cleaned up
 * to avoid as an ideal fix
 */
public class MobileDeviceManagementServiceComponent {

    private ServiceRegistration gcmServiceRegRef;

    private static final Log log = LogFactory.getLog(MobileDeviceManagementServiceComponent.class);

    protected void activate(ComponentContext ctx) {

        if (log.isDebugEnabled()) {
            log.debug("Activating Mobile Device Management Service Component");
        }
        try {
            BundleContext bundleContext = ctx.getBundleContext();

            /* Initialize the data source configuration */
            MobileDeviceConfigurationManager.getInstance().initConfig();
            MobileDeviceManagementConfig config = MobileDeviceConfigurationManager.getInstance()
                    .getMobileDeviceManagementConfig();
            Map<String, MobileDataSourceConfig> dsConfigMap =
                    config.getMobileDeviceMgtRepository().getMobileDataSourceConfigMap();

            AbstractMobileDeviceManagementDAOFactory.init(dsConfigMap);

            String setupOption = System.getProperty("setup");
            if (setupOption != null) {
                if (log.isDebugEnabled()) {
                    log.debug(
                            "-Dsetup is enabled. Mobile Device management repository schema initialization is about " +
                                    "to begin");
                }
                try {
                    for (String pluginType : dsConfigMap.keySet()) {
                        MobileDeviceManagementDAOUtil
                                .setupMobileDeviceManagementSchema(AbstractMobileDeviceManagementDAOFactory.getDataSourceMap
                                        ().get(pluginType), pluginType);
                    }
                } catch (MobileDeviceMgtPluginException e) {
                    log.error("Exception occurred while initializing mobile device management database schema", e);
                }
            }

            if (log.isDebugEnabled()) {
                log.debug("Mobile Device Management Service Component has been successfully activated");
            }
        } catch (Throwable e) {
            log.error("Error occurred while activating Mobile Device Management Service Component", e);
        }
    }

    protected void deactivate(ComponentContext ctx) {
        if (log.isDebugEnabled()) {
            log.debug("De-activating Mobile Device Management Service Component");
        }
        try {
            if (gcmServiceRegRef != null) {
                gcmServiceRegRef.unregister();
            }
            if (log.isDebugEnabled()) {
                log.debug(
                        "Mobile Device Management Service Component has been successfully de-activated");
            }
        } catch (Throwable e) {
            log.error("Error occurred while de-activating Mobile Device Management bundle", e);
        }
    }

    protected void setDataSourceService(DataSourceService dataSourceService) {
        /* This is to avoid mobile device management component getting initialized before the underlying datasources
        are registered */
        if (log.isDebugEnabled()) {
            log.debug("Data source service set to mobile service component");
        }
    }

    protected void unsetDataSourceService(DataSourceService dataSourceService) {
        //do nothing
    }

    protected void setRegistryService(RegistryService registryService) {
        if (log.isDebugEnabled()) {
            log.debug("RegistryService acquired");
        }
        MobileDeviceManagementDataHolder.getInstance().setRegistryService(registryService);
    }

    protected void unsetRegistryService(RegistryService registryService) {
        MobileDeviceManagementDataHolder.getInstance().setRegistryService(null);
    }

}

redpajama_set_name: RedPajamaGithub


text:
Encoding
========

Changing the format of data, but not changing the data itself,
e.g. converting to gif format, comes under the banner of Encoding.

You can register as many encoders as you like.

Let's say we have a Dragonfly app

    app = Dragonfly[:images]

and an image object (actually a {Dragonfly::Job Job} object)...

    image = app.fetch('some/uid')

...OR a Dragonfly model accessor...

    image = @album.cover_image

We can encode it to any format registered with the encoder.

RMagickEncoder
----------------
The {Dragonfly::Encoding::RMagickEncoder RMagickEncoder} is registered by default by
the {Dragonfly::Config::RMagick RMagick configuration} used by 'dragonfly/rails/images'.

If not already registered:

    app.encoder.register(Dragonfly::Encoding::RMagickEncoder)

gives us:

    image.encode(:jpg)
    image.encode(:gif)
    image.encode(:png)
    image.encode(:tiff)

and various other formats (see {Dragonfly::Encoding::RMagickEncoder RMagickEncoder})

Lazy evaluation
---------------

    gif_image = image.encode(:gif)

doesn't actually do anything until you call something on the returned {Dragonfly::Job Job} object, like `url`, `data`, etc.

Bang method
-----------

    image.encode!(:gif)

modifies the image object itself, rather than returning a new object.

Custom Encoders
---------------

To register a custom encoder, for e.g. pdf format:

    app.encoder.add do |temp_object, format|
      throw :unable_to_handle unless format == :pdf
      # use temp_object.data, temp_object.path, temp_object.file, etc.
      SomeLibrary.convert_to_pdf(temp_object.data)
      # return a String, File or Tempfile
    end

    pdf_image = image.encode(:pdf)

If `:unable_to_handle` is thrown, the next most recently registered encoder is used, and so on.

Alternatively you can create a class like the RMagick one above, which implements the method `encode`, and register this.

    class MyEncoder

      def encode(temp_object, format, *args)
        SomeLib.encode(temp_object.data, format, *args)
      end

    end

    app.encoder.register(MyEncoder)

    pdf_image = image.encode(:pdf, :some => :args)


text:
#region LICENSE
//==============================================================================//
//	Copyright (c) 2014-2016 Daniel Castaño Estrella						        //
//	This projected is licensed under the terms of the MIT license.				//
//	See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT	//
//==============================================================================//
#endregion

using UnityEngine;

namespace Tactel.Extensions
{
    public static class Extensions
    {
        public static T[] CompactArray<T>(this T[] array)
        {
            int empty_cells_count = 0;
            for(int i = 0; i < array.Length; i++)
            {
                if (array[i] == null)
                    empty_cells_count++;
                else
                {
                    //there were empty cells
                    if(empty_cells_count > 0)
                    {
                        array[i - empty_cells_count] = array[i];    //copy object back
                        array[i] = default(T);    //delete duplicate object
                        i -= empty_cells_count;
                        empty_cells_count = 0;

                    }
                }
            }

            return array;
        }

        public static void SetBool(string name, bool value)
        {
            PlayerPrefs.SetInt(name, value ? 1 : 0);
        }

        public static bool GetBool(string name, bool defaultValue = false)
        {
            return PlayerPrefs.GetInt(name) == 1 ? true : defaultValue;
        }
    }
}


text:
mod boundary_iter;
mod point_iter;
mod print_iter;
mod range_iter;
mod ranges_iter;
mod point;
mod range;

pub use cw::point_iter::PointIter;
pub use cw::print_iter::PrintItem;
pub use cw::range::Range;
pub use cw::point::Point;

use std::collections::HashSet;
use std::iter::{repeat, Zip};
use std::fmt;
use std::fmt::{Display, Formatter};
use std::slice;
use cw::boundary_iter::BoundaryIter;
use cw::print_iter::PrintIter;
use cw::range_iter::RangeIter;
use cw::ranges_iter::RangesIter;

pub const BLOCK: char = '#';

/// The possible directions for words: `Right` and `Down`.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum Dir {
    Right,
    Down,
}

impl Dir {
    /// The other direction, perpendicular to this one.
    pub fn other(&self) -> Dir {
        match *self {
            Dir::Right => Dir::Down,
            Dir::Down => Dir::Right,
        }
    }

    /// The corresponding vector. To move in this direction, add the vector to a point.
    pub fn point(&self) -> Point {
        match *self {
            Dir::Right => Point::new(1, 0),
            Dir::Down => Point::new(0, 1),
        }
    }
}

/// A crosswords grid that keeps track of the words it contains and doesn't allow duplicates.
#[derive(Clone)]
pub struct Crosswords {
    width: usize,
    height: usize,
    chars: Vec<char>,
    right_border: Vec<bool>,
    down_border: Vec<bool>,
    words: HashSet<Vec<char>>,
}

impl Crosswords {
    /// Creates a new empty crosswords grid with the given dimensions.
    pub fn new(width: usize, height: usize) -> Crosswords {
        Crosswords {
            width: width,
            height: height,
            chars: repeat(BLOCK).take(width * height).collect(),
            right_border: repeat(true).take((width - 1) * height).collect(),
            down_border: repeat(true).take(width * (height - 1)).collect(),
            words: HashSet::new(),
        }
    }

    #[inline]
    pub fn get_width(&self) -> usize {
        self.width
    }

    #[inline]
    pub fn get_height(&self) -> usize {
        self.height
    }

    /// Returns the set of words that are present in the grid.
    pub fn get_words(&self) -> &HashSet<Vec<char>> {
        &self.words
    }

    /// Returns `true` if the given cell has a right resp. bottom border, where points outside the
    /// grid are considered to have borders all around. The value `false` means that the cell
    /// belongs to a word which in the given direction and that it doesn't contain the last letter
    /// of that word.
    #[inline]
    pub fn get_border(&self, point: Point, dir: Dir) -> bool {
        match dir {
            Dir::Right => {
                match point.coord(self.width - 1, self.height) {
                    None => true,
                    Some(p) => self.right_border[p],
                }
            }
            Dir::Down => {
                match point.coord(self.width, self.height - 1) {
                    None => true,
                    Some(p) => self.down_border[p],
                }
            }
        }
    }

    /// Returns `true` if the cell has a right and left resp. top and bottom border. The value
    /// `false` means that the cell belongs to a word in the given direction.
    #[inline]
    pub fn both_borders(&self, point: Point, dir: Dir) -> bool {
        self.get_border(point, dir) && self.get_border(point - dir.point(), dir)
    }

    #[inline]
    fn set_border(&mut self, point: Point, dir: Dir, value: bool) -> bool {
        match dir {
            Dir::Right => {
                match point.coord(self.width - 1, self.height) {
                    None => if value { true } else { unreachable!() },
                    Some(p) => {
                        let existing = self.right_border[p];
                        self.right_border[p] = value;
                        existing
                    }
                }
            }
            Dir::Down => {
                match point.coord(self.width, self.height - 1) {
                    None => if value { true } else { unreachable!() },
                    Some(p) => {
                        let existing = self.down_border[p];
                        self.down_border[p] = value;
                        existing
                    }
                }
            }
        }
    }

    #[inline]
    fn is_char_allowed(&self, point: Point, c: char) -> bool {
        match point.coord(self.width, self.height) {
            None => false,
            Some(p) => {
                let existing = self.chars[p];
                c == existing || existing == BLOCK
            }
        }
    }

    /// Returns `Some(c)` if the given cell contains the letter c, where `#` stands for blocks. If
    /// the given point is outside the grid, it returns `None`.
    #[inline]
    pub fn get_char(&self, point: Point) -> Option<char> {
        point
            .coord(self.width, self.height)
            .and_then(|p| self.chars.get(p).cloned())
    }

    /// An iterator over the characters in the given range.
    pub fn chars(&self, range: Range) -> RangeIter {
        RangeIter::new(range, self)
    }

    /// An iterator over the characters of the word in the given position. If there is no word, the
    /// iterator will be empty.
    pub fn chars_at(&self, point: Point, dir: Dir) -> RangeIter {
        self.chars(self.get_word_range_at(point, dir))
    }

    /// Returns word in the given position.
    pub fn word_at(&self, point: Point, dir: Dir) -> Vec<char> {
        self.chars_at(point, dir).collect()
    }

    #[inline]
    fn put_char(&mut self, point: Point, c: char) -> char {
        let p = point.coord(self.width, self.height).unwrap();
        let existing = self.chars[p];
        self.chars[p] = c;
        existing
    }

    fn word_iter(word: &[char], point: Point, dir: Dir) -> Zip<slice::Iter<char>, PointIter> {
        word.iter().zip(PointIter::new(point, dir, word.len()))
    }

    /// Returns whether the given word could be inserted in that position, without conflicting with
    /// other words.
    pub fn is_word_allowed(&self, point: Point, dir: Dir, word: &[char]) -> bool {
        let dp = dir.point();
        let len = word.len() as i32;
        !self.words.contains(word) && len > 1 && self.get_border(point - dp, dir) &&
        self.get_border(point + dp * (len - 1), dir) &&
        Self::word_iter(word, point, dir).all(|(&c, p)| self.is_char_allowed(p, c))
    }

    fn push_word(&mut self, point: Point, dir: Dir, word: &[char]) {
        for (&c, p) in Self::word_iter(word, point, dir) {
            let existing = self.word_at(p, dir);
            self.words.remove(&existing);
            self.put_char(p, c);
        }
        for p in PointIter::new(point, dir, word.len() - 1) {
            self.set_border(p, dir, false);
        }
        self.words.insert(word.to_vec());
    }

    /// Removes and returns the word from the given position.
    pub fn pop_word(&mut self, point: Point, dir: Dir) -> Vec<char> {
        let word: Vec<_> = self.word_at(point, dir);
        if word.len() <= 1 {
            return Vec::new();
        }
        let odir = dir.other();
        for p in PointIter::new(point, dir, word.len()) {
            self.set_border(p, dir, true);
            if self.both_borders(p, odir) {
                self.put_char(p, BLOCK);
            }
        }
        self.words.remove(&word);
        word
    }

    /// Inserts the word in the given position if that is allowed, otherwise returns `false`.
    pub fn try_word(&mut self, point: Point, dir: Dir, word: &[char]) -> bool {
        if self.is_word_allowed(point, dir, word) {
            self.push_word(point, dir, word);
            true
        } else {
            false
        }
    }

    /// Returns whether the point is a valid coordinate for a cell in the grid.
    pub fn contains(&self, point: Point) -> bool {
        point.x >= 0 && point.y >= 0 && point.x < self.width as i32 && point.y < self.height as i32
    }

    /// Returns `false` if any cell of the range belongs to a word in the range's direction.
    pub fn is_range_free(&self, range: Range) -> bool {
        let dp = range.dir.point();
        self.contains(range.point) && self.contains(range.point + dp * (range.len - 1)) &&
        self.get_border(range.point - dp, range.dir) &&
        range.points().all(|p| self.get_border(p, range.dir))
    }

    /// Returns the largest free range containing the point.
    pub fn get_free_range_containing(&self, mut point: Point, dir: Dir) -> Range {
        let dp = dir.point();
        while self.contains(point - dp) && self.get_border(point - dp * 2, dir) {
            point = point - dp;
        }
        self.get_free_range_at(point, dir)
    }

    /// Returns the largest free range starting at that point.
    pub fn get_free_range_at(&self, point: Point, dir: Dir) -> Range {
        let dp = dir.point();
        if !self.contains(point - dp) ||
           (self.get_border(point - dp, dir) && !self.get_border(point - dp * 2, dir)) {
            Range::cells_with(point, dir, |p| self.contains(p) && self.get_border(p, dir))
        } else {
            Range {
                point: point,
                dir: dir,
                len: 0,
            }
        }
    }

    /// Returns the largest free range adjacent to the end of the given one.
    pub fn get_range_after(&self, range: &Range) -> Range {
        let dp = range.dir.point();
        let mut len = 0;
        let mut p = range.point + dp * range.len;
        while self.get_border(p, range.dir) && self.contains(p) {
            len += 1;
            p = p + dp;
        }
        Range {
            point: range.point + dp * range.len,
            dir: range.dir,
            len: len,
        }
    }

    /// Returns the largest free range adjacent to the start of the given one.
    pub fn get_range_before(&self, range: &Range) -> Range {
        let dp = range.dir.point();
        let mut len = 0;
        let mut p = range.point;
        while self.get_border(p - dp * 2, range.dir) && self.contains(p - dp) {
            len += 1;
            p = p - dp;
        }
        Range {
            point: p,
            dir: range.dir,
            len: len,
        }
    }

    /// Returns `true` if the point is the coordinate of a cell which belongs to a word.
    #[inline]
    pub fn is_letter(&self, point: Point) -> bool {
        match self.get_char(point) {
            None | Some(BLOCK) => false,
            Some(_) => true,
        }
    }

    fn is_boundary_point(&self, point: Point) -> bool {
        self.get_char(point) == Some(BLOCK) &&
        (self.is_letter(point + Point::new(1, 0)) || self.is_letter(point + Point::new(-1, 0)) ||
         self.is_letter(point + Point::new(0, 1)) ||
         self.is_letter(point + Point::new(0, -1)))
    }

    /// Returns the smallest set of pairs of points that defines the boundary of a cluster of empty
    /// cells.
    pub fn get_smallest_boundary(&self) -> HashSet<(Point, Point)> {
        let mut points = HashSet::new();
        let mut smallest = HashSet::new();
        for x in 0..(self.width as i32) {
            for y in 0..(self.height as i32) {
                let point = Point::new(x, y);
                if !points.contains(&point) && self.is_boundary_point(point) {
                    let boundary: HashSet<_> = self.get_boundary_iter_for(point, None).collect();
                    if boundary.len() <= 1 {
                        return boundary;
                    }
                    if points.is_empty() || boundary.len() < smallest.len() {
                        smallest = boundary.clone();
                    }
                    points.extend(boundary.into_iter().map(|(p0, _)| p0));
                }
            }
        }
        smallest
    }

    /// Returns an iterator over the ranges containing the words.
    pub fn word_ranges(&self) -> RangesIter {
        RangesIter::new(self)
    }

    /// Returns the range of the word the given point belongs to.
    pub fn get_word_range_containing(&self, mut point: Point, dir: Dir) -> Range {
        let dp = dir.point();
        while !self.get_border(point - dp, dir) {
            point = point - dp;
        }
        self.get_word_range_at(point, dir)
    }

    /// Returns the range beginning at the given point until the end of the word.
    pub fn get_word_range_at(&self, point: Point, dir: Dir) -> Range {
        let dp = dir.point();
        Range::cells_with(point, dir, |p| (p == point) == self.get_border(p - dp, dir))
    }

    /// Returns `true` if a word with the given orientation starts at that point.
    pub fn has_hint_at_dir(&self, point: Point, dir: Dir) -> bool {
        !self.get_border(point, dir) && self.get_border(point - dir.point(), dir)
    }

    /// Returns `true` if a word with starts at that point.
    pub fn has_hint_at(&self, point: Point) -> bool {
        self.has_hint_at_dir(point, Dir::Right) || self.has_hint_at_dir(point, Dir::Down)
    }

    /// Returns `true` if the grid is empty, i. e. it contains no words and every cell is a block.
    pub fn is_empty(&self) -> bool {
        self.words.is_empty()
    }

    /// Returns `true` if the grid is full, i. e. every cell contains a letter.
    pub fn is_full(&self) -> bool {
        (0..(self.width * self.height)).all(|p| self.chars[p] != BLOCK)
    }

    /// Returns the number of borders inside the grid.
    pub fn count_borders(&self) -> usize {
        self.right_border
            .iter()
            .chain(&self.down_border)
            .filter(|&&b| b)
            .count()
    }

    /// The maximum number of borders inside a grid of this size, i. e. the number of borders if
    /// the grid were empty: 2 * width * height - width - height.
    pub fn max_border_count(&self) -> usize {
        2 * self.width * self.height - self.width - self.height
    }

    /// Returns an iterator over the `PrintItem`s representing the current state of the crosswords,
    /// including all borders and cell contents, from left to right, from top to bottom. They can
    /// be converted to text or graphics to display the grid.
    pub fn print_items(&self) -> PrintIter {
        PrintIter::new(self)
    }

    /// Returns an iterator over all pairs of points that define the border of the cluster of empty
    /// cells which the given point belongs to. If the cell at that point is not empty, the
    /// iterator is empty.
    pub fn get_boundary_iter_for(&self, point: Point, range: Option<Range>) -> BoundaryIter {
        BoundaryIter::new(point, range, self)
    }
}

impl Display for Crosswords {
    fn fmt(&self, formatter: &mut Formatter) -> Result<(), fmt::Error> {
        {
            let bc = self.count_borders();
            let bt = self.max_border_count();
            let br = 100. * (bc as f32) / (bt as f32);
            try!(formatter.write_fmt(format_args!("{} / {} borders ({}%)\n", bc, bt, br)));
        }
        for item in self.print_items() {
            try!(formatter.write_str(&match item {
                                              PrintItem::Cross(true) => '\u{00B7}',
                                              PrintItem::VertBorder(true) => '|',
                                              PrintItem::HorizBorder(true) => '\u{2014}',
                                              PrintItem::Cross(false) |
                                              PrintItem::VertBorder(false) |
                                              PrintItem::HorizBorder(false) => ' ',
                                              PrintItem::Block => '\u{2588}',
                                              PrintItem::CharHint(c, _) => c,
                                              PrintItem::LineBreak => '\n',
                                          }
                                          .to_string()
                                          [..]))
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use test_util::str_to_cvec;

    #[test]
    fn test_put_word() {
        let mut cw = Crosswords::new(6, 2);
        let p00 = Point::new(0, 0);
        let p01 = Point::new(0, 1);
        let p30 = Point::new(3, 0);
        // Words are too long:
        assert_eq!(false, cw.try_word(p00, Dir::Down, &str_to_cvec("FOO")));
        assert_eq!(false,
                   cw.try_word(p00, Dir::Right, &str_to_cvec("FOOBARBAZ")));
        // BAR fits horizontally, but cannot be duplicated.
        assert_eq!(true, cw.try_word(p00, Dir::Right, &str_to_cvec("BAR")));
        assert_eq!(false, cw.try_word(p01, Dir::Right, &str_to_cvec("BAR")));
        assert_eq!("BAR".to_string(),
                   cw.chars_at(p00, Dir::Right).collect::<String>());
        assert_eq!(true, cw.try_word(p30, Dir::Right, &str_to_cvec("BAZ")));
        // BARBAZ is also a word. Combine BAR and BAZ, so that they are free again:
        assert_eq!(true, cw.try_word(p00, Dir::Right, &str_to_cvec("BARBAZ")));
        assert_eq!(true, cw.try_word(p01, Dir::Right, &str_to_cvec("BAR")));
        assert_eq!(true, cw.try_word(p00, Dir::Down, &str_to_cvec("BB")));
    }
}


text:
module Distribution.Solver.Modular.Index
    ( Index
    , PInfo(..)
    , defaultQualifyOptions
    , mkIndex
    ) where

import Data.List as L
import Data.Map as M
import Prelude hiding (pi)

import Distribution.Solver.Modular.Dependency
import Distribution.Solver.Modular.Flag
import Distribution.Solver.Modular.Package
import Distribution.Solver.Modular.Tree

-- | An index contains information about package instances. This is a nested
-- dictionary. Package names are mapped to instances, which in turn is mapped
-- to info.
type Index = Map PN (Map I PInfo)

-- | Info associated with a package instance.
-- Currently, dependencies, flags and failure reasons.
-- Packages that have a failure reason recorded for them are disabled
-- globally, for reasons external to the solver. We currently use this
-- for shadowing which essentially is a GHC limitation, and for
-- installed packages that are broken.
data PInfo = PInfo (FlaggedDeps PN) FlagInfo (Maybe FailReason)

mkIndex :: [(PN, I, PInfo)] -> Index
mkIndex xs = M.map M.fromList (groupMap (L.map (\ (pn, i, pi) -> (pn, (i, pi))) xs))

groupMap :: Ord a => [(a, b)] -> Map a [b]
groupMap xs = M.fromListWith (flip (++)) (L.map (\ (x, y) -> (x, [y])) xs)

defaultQualifyOptions :: Index -> QualifyOptions
defaultQualifyOptions idx = QO {
      qoBaseShim         = or [ dep == base
                              | -- Find all versions of base ..
                                Just is <- [M.lookup base idx]
                                -- .. which are installed ..
                              , (I _ver (Inst _), PInfo deps _flagNfo _fr) <- M.toList is
                                -- .. and flatten all their dependencies ..
                              , (LDep _ (Dep _is_exe dep _ci), _comp) <- flattenFlaggedDeps deps
                              ]
    , qoSetupIndependent = True
    }
  where
    base = mkPackageName "base"


text:
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "extensions/browser/image_sanitizer.h"

#include "base/bind.h"
#include "base/debug/dump_without_crashing.h"
#include "base/files/file_util.h"
#include "base/task/task_runner_util.h"
#include "extensions/browser/extension_file_task_runner.h"
#include "extensions/common/extension_resource_path_normalizer.h"
#include "services/data_decoder/public/cpp/decode_image.h"
#include "ui/gfx/codec/png_codec.h"

namespace extensions {

namespace {

// We don't expect icons and other extension's images to be big.
// We use this limit to prevent from opening too large images.
const int kMaxImageCanvas = 4096 * 4096;  // 16MB

// Reads the file in |path| and then deletes it.
// Returns a tuple containing: the file content, whether the read was
// successful, whether the delete was successful.
std::tuple<std::vector<uint8_t>, bool, bool> ReadAndDeleteBinaryFile(
    const base::FilePath& path) {
  std::vector<uint8_t> contents;
  bool read_success = false;
  int64_t file_size;
  if (base::GetFileSize(path, &file_size)) {
    contents.resize(file_size);
    read_success =
        base::ReadFile(path, reinterpret_cast<char*>(contents.data()),
                       file_size) == file_size;
  }
  bool delete_success = base::DeleteFile(path);
  return std::make_tuple(std::move(contents), read_success, delete_success);
}

std::pair<bool, std::vector<unsigned char>> EncodeImage(const SkBitmap& image) {
  std::vector<unsigned char> image_data;
  bool success = gfx::PNGCodec::EncodeBGRASkBitmap(
      image,
      /*discard_transparency=*/false, &image_data);
  return std::make_pair(success, std::move(image_data));
}

int WriteFile(const base::FilePath& path,
              const std::vector<unsigned char>& data) {
  return base::WriteFile(path, reinterpret_cast<const char*>(data.data()),
                         base::checked_cast<int>(data.size()));
}

}  // namespace

// static
std::unique_ptr<ImageSanitizer> ImageSanitizer::CreateAndStart(
    scoped_refptr<Client> client,
    const base::FilePath& image_dir,
    const std::set<base::FilePath>& image_paths,
    const scoped_refptr<base::SequencedTaskRunner>& io_task_runner) {
  std::unique_ptr<ImageSanitizer> sanitizer(
      new ImageSanitizer(client, image_dir, image_paths, io_task_runner));
  sanitizer->Start();
  return sanitizer;
}

ImageSanitizer::ImageSanitizer(
    scoped_refptr<Client> client,
    const base::FilePath& image_dir,
    const std::set<base::FilePath>& image_relative_paths,
    const scoped_refptr<base::SequencedTaskRunner>& io_task_runner)
    : image_dir_(image_dir),
      image_paths_(image_relative_paths),
      client_(std::move(client)),
      io_task_runner_(io_task_runner) {
  DCHECK(client_);
}

ImageSanitizer::~ImageSanitizer() = default;
ImageSanitizer::Client::~Client() = default;

void ImageSanitizer::Start() {
  if (image_paths_.empty()) {
    base::SequencedTaskRunnerHandle::Get()->PostTask(
        FROM_HERE, base::BindOnce(&ImageSanitizer::ReportSuccess,
                                  weak_factory_.GetWeakPtr()));
    return;
  }

  std::set<base::FilePath> normalized_image_paths;
  for (const base::FilePath& path : image_paths_) {
    // Normalize paths as |image_paths_| can contain duplicates like "icon.png"
    // and "./icon.png" to avoid unpacking the same image twice.
    base::FilePath normalized_path;
    if (path.IsAbsolute() || path.ReferencesParent() ||
        !NormalizeExtensionResourcePath(path, &normalized_path)) {
      // Report the error asynchronously so the caller stack has chance to
      // unwind.
      base::SequencedTaskRunnerHandle::Get()->PostTask(
          FROM_HERE, base::BindOnce(&ImageSanitizer::ReportError,
                                    weak_factory_.GetWeakPtr(),
                                    Status::kImagePathError, path));
      return;
    }
    normalized_image_paths.insert(normalized_path);
  }
  // Update |image_paths_| as some of the path might have been changed by
  // normalization.
  image_paths_ = std::move(normalized_image_paths);

  // Note that we use 2 for loops instead of one to prevent a race and flakyness
  // in tests: if |image_paths_| contains 2 paths, a valid one that points to a
  // file that does not exist and an invalid one, there is a race that can cause
  // either error to be reported (kImagePathError or kFileReadError).
  for (const base::FilePath& path : image_paths_) {
    base::FilePath full_image_path = image_dir_.Append(path);
    base::PostTaskAndReplyWithResult(
        io_task_runner_.get(), FROM_HERE,
        base::BindOnce(&ReadAndDeleteBinaryFile, full_image_path),
        base::BindOnce(&ImageSanitizer::ImageFileRead,
                       weak_factory_.GetWeakPtr(), path));
  }
}

void ImageSanitizer::ImageFileRead(
    const base::FilePath& image_path,
    std::tuple<std::vector<uint8_t>, bool, bool> read_and_delete_result) {
  if (!std::get<1>(read_and_delete_result)) {
    ReportError(Status::kFileReadError, image_path);
    return;
  }
  if (!std::get<2>(read_and_delete_result)) {
    ReportError(Status::kFileDeleteError, image_path);
    return;
  }
  const std::vector<uint8_t>& image_data = std::get<0>(read_and_delete_result);
  data_decoder::DecodeImage(
      client_->GetDataDecoder(), image_data,
      data_decoder::mojom::ImageCodec::kDefault,
      /*shrink_to_fit=*/false, kMaxImageCanvas, gfx::Size(),
      base::BindOnce(&ImageSanitizer::ImageDecoded, weak_factory_.GetWeakPtr(),
                     image_path));
}

void ImageSanitizer::ImageDecoded(const base::FilePath& image_path,
                                  const SkBitmap& decoded_image) {
  if (decoded_image.isNull()) {
    ReportError(Status::kDecodingError, image_path);
    return;
  }
  if (decoded_image.colorType() != kN32_SkColorType) {
    // The renderer should be sending us N32 32bpp bitmaps in reply, otherwise
    // this can lead to out-of-bounds mistakes when transferring the pixels out
    // of the bitmap into other buffers.
    base::debug::DumpWithoutCrashing();
    ReportError(Status::kDecodingError, image_path);
    return;
  }

  // TODO(mpcomplete): It's lame that we're encoding all images as PNG, even
  // though they may originally be .jpg, etc.  Figure something out.
  // http://code.google.com/p/chromium/issues/detail?id=12459
  base::PostTaskAndReplyWithResult(
      io_task_runner_.get(), FROM_HERE,
      base::BindOnce(&EncodeImage, decoded_image),
      base::BindOnce(&ImageSanitizer::ImageReencoded,
                     weak_factory_.GetWeakPtr(), image_path));

  client_->OnImageDecoded(image_path, decoded_image);
  // Note that the `client` callback could potentially delete `this` object.
}

void ImageSanitizer::ImageReencoded(
    const base::FilePath& image_path,
    std::pair<bool, std::vector<unsigned char>> result) {
  bool success = result.first;
  std::vector<unsigned char> image_data = std::move(result.second);
  if (!success) {
    ReportError(Status::kEncodingError, image_path);
    return;
  }

  int size = base::checked_cast<int>(image_data.size());
  base::PostTaskAndReplyWithResult(
      io_task_runner_.get(), FROM_HERE,
      base::BindOnce(&WriteFile, image_dir_.Append(image_path),
                     std::move(image_data)),
      base::BindOnce(&ImageSanitizer::ImageWritten, weak_factory_.GetWeakPtr(),
                     image_path, size));
}

void ImageSanitizer::ImageWritten(const base::FilePath& image_path,
                                  int expected_size,
                                  int actual_size) {
  if (expected_size != actual_size) {
    ReportError(Status::kFileWriteError, image_path);
    return;
  }
  // We have finished with this path.
  size_t removed_count = image_paths_.erase(image_path);
  DCHECK_EQ(1U, removed_count);

  if (image_paths_.empty()) {
    // This was the last path, we are done.
    ReportSuccess();
  }
}

void ImageSanitizer::ReportSuccess() {
  // Reset `client_` early, before the callback potentially deletes `this`.
  scoped_refptr<Client> client = std::move(client_);
  DCHECK(!client_);

  // The `client_` callback is the last statement, because it can potentially
  // delete `this` object.
  client->OnImageSanitizationDone(Status::kSuccess, base::FilePath());
}

void ImageSanitizer::ReportError(Status status, const base::FilePath& path) {
  // Prevent any other task from reporting, we want to notify only once.
  weak_factory_.InvalidateWeakPtrs();

  // Reset `client_` early, before the callback potentially deletes `this`.
  scoped_refptr<Client> client = std::move(client_);
  DCHECK(!client_);

  // The `client_` callback is the last statement, because it can potentially
  // delete `this` object.
  client->OnImageSanitizationDone(status, path);
}

}  // namespace extensions


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

var fs = require('fs');
var path = require('path');
var shelljs = require('shelljs');
var mungeutil = require('./munge-util');
var pluginMappernto = require('cordova-registry-mapper').newToOld;
var pluginMapperotn = require('cordova-registry-mapper').oldToNew;

function PlatformJson(filePath, platform, root) {
    this.filePath = filePath;
    this.platform = platform;
    this.root = fix_munge(root || {});
}

PlatformJson.load = function(plugins_dir, platform) {
    var filePath = path.join(plugins_dir, platform + '.json');
    var root = null;
    if (fs.existsSync(filePath)) {
        root = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
    }
    return new PlatformJson(filePath, platform, root);
};

PlatformJson.prototype.save = function() {
    shelljs.mkdir('-p', path.dirname(this.filePath));
    fs.writeFileSync(this.filePath, JSON.stringify(this.root, null, 4), 'utf-8');
};

PlatformJson.prototype.isPluginInstalled = function(pluginId) {
    var installed_plugin_id;
    var json = this.root;

    for (installed_plugin_id in json.installed_plugins) {
        if ((installed_plugin_id == pluginId)||(installed_plugin_id == pluginMappernto[pluginId]) || (installed_plugin_id == pluginMapperotn[pluginId])) {
            return true;
        }
    }
    for (installed_plugin_id in json.dependent_plugins) {
        if ((installed_plugin_id == pluginId)||(installed_plugin_id == pluginMappernto[pluginId]) || (installed_plugin_id == pluginMapperotn[pluginId])) {
            return true;
        }
    }
    return false;
};

PlatformJson.prototype.addInstalledPluginToPrepareQueue = function(pluginDirName, vars, is_top_level) {
    this.root.prepare_queue.installed.push({'plugin':pluginDirName, 'vars':vars, 'topLevel':is_top_level});
};

PlatformJson.prototype.addUninstalledPluginToPrepareQueue = function(pluginId, is_top_level) {
    this.root.prepare_queue.uninstalled.push({'plugin':pluginId, 'id':pluginId, 'topLevel':is_top_level});
};

// convert a munge from the old format ([file][parent][xml] = count) to the current one
function fix_munge(root) {
    root.prepare_queue = root.prepare_queue || {installed:[], uninstalled:[]};
    root.config_munge = root.config_munge || {files: {}};
    root.installed_plugins = root.installed_plugins || {};
    root.dependent_plugins = root.dependent_plugins || {};

    var munge = root.config_munge;
    if (!munge.files) {
        var new_munge = { files: {} };
        for (var file in munge) {
            for (var selector in munge[file]) {
                for (var xml_child in munge[file][selector]) {
                    var val = parseInt(munge[file][selector][xml_child]);
                    for (var i = 0; i < val; i++) {
                        mungeutil.deep_add(new_munge, [file, selector, { xml: xml_child, count: val }]);
                    }
                }
            }
        }
        root.config_munge = new_munge;
    }

    return root;
}

module.exports = PlatformJson;


text:
name "ffi-yajl"
default_version "master"
relative_path "ffi-yajl"

source :git => "git://github.com/lamont-granquist/ffi-yajl"

if windows?
  dependency "ruby-windows"
  dependency "ruby-windows-devkit"
else
  dependency "libffi"
  dependency "ruby"
  dependency "rubygems"
end

dependency "bundler"

env = with_embedded_path()

build do
  bundle "install --without development_extras", :env => env
  bundle "exec rake gem", :env => env
  delete "pkg/*java*", :env => env
  gem ["install pkg/ffi-yajl-*.gem",
       "--no-rdoc --no-ri"].join(" "), :env => env
end


text:
<?php
class Home_model extends CI_Model {

    public function __construct()
    {
            $this->load->database();
    }

    public function get_player_data()
	{
        $query = $this->db->query('SELECT * FROM garvhai_players LIMIT 10');
        return $query->result_array();
	}
    public function get_player_video()
    {
        $query = $this->db->query('SELECT * FROM garvhai_players_media WHERE player_id = 1 LIMIT 8');
        return $query->result_array();
    }

    public function get_player_modal_data($mode = '',$player_id = '')
    {
        if ($mode == 'profile') {
            $query = $this->db->get_where('garvhai_players', array('id' => $player_id));
        }else if($mode == 'videos'){
            $query = $this->db->get_where('garvhai_players', array('id' => $player_id));
        }else if($mode == 'media'){
            $query = $this->db->get_where('garvhai_players_media', array('player_id' => $player_id));
        }
        //echo $this->db->last_query(); exit();
        return $query->result_array();
    }

     public function get_player_filter_data($player_id = '')
    {
        $query = $this->db->get_where('garvhai_players_media', array('player_id' => $player_id), 8, 0);
        //echo $this->db->last_query(); exit();
        return $query->result_array();
    }
}


text:
from .halconsole import HalConsole
Default = HalConsole


text:
import api

class LibraryEReserves():
    # LibraryEReserves.LibEreserves
    def lib_ereserves(self, courseId, titleOnly=False, auth=True):
        params = {'CourseID': courseId, 'TitleOnly': titleOnly}
        return api.call('LibEreserves', params, auth)

    # LibraryEReserves.LibEreserveFiles
    def lib_ereserves_files(self, folderId, auth=True):
        params = {'FolderID': folderId}
        return api.call('LibEreserveFiles', params, auth)


text:
.class Lcom/google/common/collect/BstNode;
.super Ljava/lang/Object;
.source "BstNode.java"

# annotations
.annotation build Lcom/google/common/annotations/GwtCompatible;
.end annotation

.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Lcom/google/common/collect/BstNode$1;
    }
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "<K:",
        "Ljava/lang/Object;",
        "N:",
        "Lcom/google/common/collect/BstNode",
        "<TK;TN;>;>",
        "Ljava/lang/Object;"
    }
.end annotation

# instance fields
.field private final key:Ljava/lang/Object;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "TK;"
        }
    .end annotation
.end field

.field private final left:Lcom/google/common/collect/BstNode;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "TN;"
        }
    .end annotation

    .annotation runtime Ljavax/annotation/Nullable;
    .end annotation
.end field

.field private final right:Lcom/google/common/collect/BstNode;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "TN;"
        }
    .end annotation

    .annotation runtime Ljavax/annotation/Nullable;
    .end annotation
.end field

# direct methods
.method constructor <init>(Ljava/lang/Object;Lcom/google/common/collect/BstNode;Lcom/google/common/collect/BstNode;)V
    .locals 0
    .param p1    # Ljava/lang/Object;
        .annotation runtime Ljavax/annotation/Nullable;
        .end annotation
    .end param
    .param p2    # Lcom/google/common/collect/BstNode;
        .annotation runtime Ljavax/annotation/Nullable;
        .end annotation
    .end param
    .param p3    # Lcom/google/common/collect/BstNode;
        .annotation runtime Ljavax/annotation/Nullable;
        .end annotation
    .end param
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(TK;TN;TN;)V"
        }
    .end annotation

    .prologue
    .line 63
    .local p0, "this":Lcom/google/common/collect/BstNode;, "Lcom/google/common/collect/BstNode<TK;TN;>;"
    .local p1, "key":Ljava/lang/Object;, "TK;"
    .local p2, "left":Lcom/google/common/collect/BstNode;, "TN;"
    .local p3, "right":Lcom/google/common/collect/BstNode;, "TN;"
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 64
    iput-object p1, p0, Lcom/google/common/collect/BstNode;->key:Ljava/lang/Object;

    .line 65
    iput-object p2, p0, Lcom/google/common/collect/BstNode;->left:Lcom/google/common/collect/BstNode;

    .line 66
    iput-object p3, p0, Lcom/google/common/collect/BstNode;->right:Lcom/google/common/collect/BstNode;

    .line 67
    return-void
.end method

# virtual methods
.method public final childOrNull(Lcom/google/common/collect/BstSide;)Lcom/google/common/collect/BstNode;
    .locals 2
    .param p1, "side"    # Lcom/google/common/collect/BstSide;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(",
            "Lcom/google/common/collect/BstSide;",
            ")TN;"
        }
    .end annotation

    .annotation runtime Ljavax/annotation/Nullable;
    .end annotation

    .prologue
    .line 82
    .local p0, "this":Lcom/google/common/collect/BstNode;, "Lcom/google/common/collect/BstNode<TK;TN;>;"
    sget-object v0, Lcom/google/common/collect/BstNode$1;->$SwitchMap$com$google$common$collect$BstSide:[I

    invoke-virtual {p1}, Lcom/google/common/collect/BstSide;->ordinal()I

    move-result v1

    aget v0, v0, v1

    packed-switch v0, :pswitch_data_0

    .line 88
    new-instance v0, Ljava/lang/AssertionError;

    invoke-direct {v0}, Ljava/lang/AssertionError;-><init>()V

    throw v0

    .line 84
    :pswitch_0
    iget-object v0, p0, Lcom/google/common/collect/BstNode;->left:Lcom/google/common/collect/BstNode;

    .line 86
    :goto_0
    return-object v0

    :pswitch_1
    iget-object v0, p0, Lcom/google/common/collect/BstNode;->right:Lcom/google/common/collect/BstNode;

    goto :goto_0

    .line 82
    nop

    :pswitch_data_0
    .packed-switch 0x1
        :pswitch_0
        :pswitch_1
    .end packed-switch
.end method

.method public final getChild(Lcom/google/common/collect/BstSide;)Lcom/google/common/collect/BstNode;
    .locals 2
    .param p1, "side"    # Lcom/google/common/collect/BstSide;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(",
            "Lcom/google/common/collect/BstSide;",
            ")TN;"
        }
    .end annotation

    .prologue
    .line 105
    .local p0, "this":Lcom/google/common/collect/BstNode;, "Lcom/google/common/collect/BstNode<TK;TN;>;"
    invoke-virtual {p0, p1}, Lcom/google/common/collect/BstNode;->childOrNull(Lcom/google/common/collect/BstSide;)Lcom/google/common/collect/BstNode;

    move-result-object v0

    .line 106
    .local v0, "child":Lcom/google/common/collect/BstNode;, "TN;"
    if-eqz v0, :cond_0

    const/4 v1, 0x1

    :goto_0
    invoke-static {v1}, Lcom/google/common/base/Preconditions;->checkState(Z)V

    .line 107
    return-object v0

    .line 106
    :cond_0
    const/4 v1, 0x0

    goto :goto_0
.end method

.method public final getKey()Ljava/lang/Object;
    .locals 1
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "()TK;"
        }
    .end annotation

    .annotation runtime Ljavax/annotation/Nullable;
    .end annotation

    .prologue
    .line 74
    .local p0, "this":Lcom/google/common/collect/BstNode;, "Lcom/google/common/collect/BstNode<TK;TN;>;"
    iget-object v0, p0, Lcom/google/common/collect/BstNode;->key:Ljava/lang/Object;

    return-object v0
.end method

.method public final hasChild(Lcom/google/common/collect/BstSide;)Z
    .locals 1
    .param p1, "side"    # Lcom/google/common/collect/BstSide;

    .prologue
    .line 96
    .local p0, "this":Lcom/google/common/collect/BstNode;, "Lcom/google/common/collect/BstNode<TK;TN;>;"
    invoke-virtual {p0, p1}, Lcom/google/common/collect/BstNode;->childOrNull(Lcom/google/common/collect/BstSide;)Lcom/google/common/collect/BstNode;

    move-result-object v0

    if-eqz v0, :cond_0

    const/4 v0, 0x1

    :goto_0
    return v0

    :cond_0
    const/4 v0, 0x0

    goto :goto_0
.end method

.method protected final orderingInvariantHolds(Ljava/util/Comparator;)Z
    .locals 5
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(",
            "Ljava/util/Comparator",
            "<-TK;>;)Z"
        }
    .end annotation

    .prologue
    .local p0, "this":Lcom/google/common/collect/BstNode;, "Lcom/google/common/collect/BstNode<TK;TN;>;"
    .local p1, "comparator":Ljava/util/Comparator;, "Ljava/util/Comparator<-TK;>;"
    const/4 v2, 0x1

    const/4 v3, 0x0

    .line 115
    invoke-static {p1}, Lcom/google/common/base/Preconditions;->checkNotNull(Ljava/lang/Object;)Ljava/lang/Object;

    .line 116
    const/4 v0, 0x1

    .line 117
    .local v0, "result":Z
    sget-object v1, Lcom/google/common/collect/BstSide;->LEFT:Lcom/google/common/collect/BstSide;

    invoke-virtual {p0, v1}, Lcom/google/common/collect/BstNode;->hasChild(Lcom/google/common/collect/BstSide;)Z

    move-result v1

    if-eqz v1, :cond_0

    .line 118
    sget-object v1, Lcom/google/common/collect/BstSide;->LEFT:Lcom/google/common/collect/BstSide;

    invoke-virtual {p0, v1}, Lcom/google/common/collect/BstNode;->getChild(Lcom/google/common/collect/BstSide;)Lcom/google/common/collect/BstNode;

    move-result-object v1

    invoke-virtual {v1}, Lcom/google/common/collect/BstNode;->getKey()Ljava/lang/Object;

    move-result-object v1

    iget-object v4, p0, Lcom/google/common/collect/BstNode;->key:Ljava/lang/Object;

    invoke-interface {p1, v1, v4}, Ljava/util/Comparator;->compare(Ljava/lang/Object;Ljava/lang/Object;)I

    move-result v1

    if-gez v1, :cond_2

    move v1, v2

    :goto_0
    and-int/2addr v0, v1

    .line 120
    :cond_0
    sget-object v1, Lcom/google/common/collect/BstSide;->RIGHT:Lcom/google/common/collect/BstSide;

    invoke-virtual {p0, v1}, Lcom/google/common/collect/BstNode;->hasChild(Lcom/google/common/collect/BstSide;)Z

    move-result v1

    if-eqz v1, :cond_1

    .line 121
    sget-object v1, Lcom/google/common/collect/BstSide;->RIGHT:Lcom/google/common/collect/BstSide;

    invoke-virtual {p0, v1}, Lcom/google/common/collect/BstNode;->getChild(Lcom/google/common/collect/BstSide;)Lcom/google/common/collect/BstNode;

    move-result-object v1

    invoke-virtual {v1}, Lcom/google/common/collect/BstNode;->getKey()Ljava/lang/Object;

    move-result-object v1

    iget-object v4, p0, Lcom/google/common/collect/BstNode;->key:Ljava/lang/Object;

    invoke-interface {p1, v1, v4}, Ljava/util/Comparator;->compare(Ljava/lang/Object;Ljava/lang/Object;)I

    move-result v1

    if-lez v1, :cond_3

    :goto_1
    and-int/2addr v0, v2

    .line 123
    :cond_1
    return v0

    :cond_2
    move v1, v3

    .line 118
    goto :goto_0

    :cond_3
    move v2, v3

    .line 121
    goto :goto_1
.end method


text:
@implementation DODropletTableViewCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)setDroplet:(DODroplet *)droplet
{
    _droplet = droplet;

    self.textLabel.text = _droplet.name;
    self.detailTextLabel.text = _droplet.ipAddress;
    self.imageView.image = [[UIImage imageNamed:@"Drop_icon"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    self.imageView.tintColor = [_droplet colorForStatus];

    [self setNeedsDisplay];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end


text:
Some time ago Cocoa developers used a brilliant framework [ShortcutRecorder](http://wafflesoftware.net/shortcut/) for managing keyboard shortcuts in application preferences. However, it became incompatible with a new plugin architecture of Xcode 4.

The project MASShortcut introduces modern API and user interface for recording, storing and using global keyboard shortcuts. All code is compatible with Xcode 4.3, Mac OS X 10.7 and the sandboxed environment.

# Usage

I hope, it is really easy:

```objective-c
// Drop a custom view into XIB and set its class to MASShortcutView
@property (nonatomic, weak) IBOutlet MASShortcutView *shortcutView;

// Think up a preference key to store a global shortcut between launches
NSString *const kPreferenceGlobalShortcut = @"GlobalShortcut";

// Assign the preference key and the shortcut view will take care of persistence
self.shortcutView.associatedUserDefaultsKey = kPreferenceGlobalShortcut;

// Execute your block of code automatically when user triggers a shortcut from preferences
[MASShortcut registerGlobalShortcutWithUserDefaultsKey:kPreferenceGlobalShortcut handler:^{
    // Let me know if you find a better or more convenient API.
}];
```

To set an example, I made a  demo project: [MASShortcutDemo](https://github.com/shpakovski/MASShortcutDemo). Enjoy!

#Notifications
By registering for KVO notifications from `NSUserDefaultsController`, you can get a callback whenever a user changes the shortcut, allowing you to perform any UI updates, or other code handling tasks.

This is just as easy to implement:

```objective-c
// Declare an ivar for key path in the user defaults controller
NSString *_observableKeyPath;

// Make a global context reference
void *kGlobalShortcutContext = &kGlobalShortcutContext;

// Implement when loading view
_observableKeyPath = [@"values." stringByAppendingString:kPreferenceGlobalShortcut];
[[NSUserDefaultsController sharedUserDefaultsController] addObserver:self forKeyPath:_observableKeyPath
                                                             options:NSKeyValueObservingOptionInitial
                                                             context:kGlobalShortcutContext];

// Capture the KVO change and do something
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)obj
                        change:(NSDictionary *)change context:(void *)ctx
{
    if (ctx == kGlobalShortcutContext) {
        NSLog(@"Shortcut has changed");
    }
    else {
        [super observeValueForKeyPath:keyPath ofObject:obj change:change context:ctx];
    }
}

// Do not forget to remove the observer
[[NSUserDefaultsController sharedUserDefaultsController] removeObserver:self
                                                             forKeyPath:_observableKeyPath
                                                                context:kGlobalShortcutContext];
```

# Non-ARC Version

If you like retain/release, please check out these forks: [heardrwt/MASShortcut](https://github.com/heardrwt/MASShortcut) and [chendo/MASShortcut](https://github.com/chendo/MASShortcut). However, the preferred way is to enable the `-fobjc-arc` in Xcode source options.

# Copyright

MASShortcut is licensed under the 2-clause BSD license.


text:
namespace open_vcdiff {

// The instruction types from section 5.5 (mistakenly labeled 5.4) of the RFC.
//
enum VCDiffInstructionType {
  VCD_NOOP = 0,
  VCD_ADD  = 1,
  VCD_RUN  = 2,
  VCD_COPY = 3,
  VCD_LAST_INSTRUCTION_TYPE = VCD_COPY,
  // The following values are not true instruction types, but rather
  // special condition values for functions that return VCDiffInstructionType.
  VCD_INSTRUCTION_ERROR = 4,
  VCD_INSTRUCTION_END_OF_DATA = 5
};

const char* VCDiffInstructionName(VCDiffInstructionType inst);

// OpcodeOrNone: An opcode is a value between 0-255.  There is not room
// in a single byte to express all these values plus a "no opcode found"
// value.  So use a 16-bit integer to hold either an opcode or kNoOpcode.
//
typedef uint16_t OpcodeOrNone;
const OpcodeOrNone kNoOpcode = 0x100;  // outside the opcode range 0x00 - 0xFF

// struct VCDiffCodeTableData:
//
// A representation of the VCDiff code table as six 256-byte arrays
// as described in Section 7 of RFC 3284.  Each instruction code
// can represent up to two delta instructions, which is why inst,
// size, and mode each appear twice.  Each of the two delta instructions
// has the following three attributes:
// * inst (NOOP, ADD, RUN, or COPY)
// * size (0-255 bytes) of the data to be copied; if this value is zero, then
//   the size will be encoded separately from the instruction code, as a Varint
// * mode (SELF, HERE, NEAR(n), or SAME(n)), only used for COPY instructions
//
// Every valid code table should contain AT LEAST the following instructions:
//     inst1=ADD  size1=0 mode1=X inst2=NOOP size2=X mode2=X
//     inst1=RUN  size1=0 mode1=X inst2=NOOP size2=X mode2=X
//     inst1=COPY size1=0 mode1=N inst2=NOOP size2=X mode2=X (for all N)
// ... where X represents a "don't care" value which will not be read,
// and N stands for every possible COPY mode between 0 and
// ([same cache size] + [here cache size]) inclusive.
// Without these instructions, it will be impossible to guarantee that
// all ADD, RUN, and COPY encoding requests can be fulfilled.
//
struct VCDiffCodeTableData {
  static const int kCodeTableSize = 256;

  static const VCDiffCodeTableData kDefaultCodeTableData;

  // Validates that the data contained in the VCDiffCodeTableData structure
  // does not violate certain assumptions.  Returns true if none of these
  // assumptions are violated, or false if an unexpected value is found.
  // This function should be called on any non-default code table that is
  // received as part of an encoded transmission.
  // max_mode is the maximum value for the mode of a COPY instruction;
  // this is equal to same_cache_size + near_cache_size + 1.
  //
  bool Validate(unsigned char max_mode) const;

  // This version of Validate() assumes that the default address cache sizes
  // are being used, and calculates max_mode based on that assumption.
  bool Validate() const;

  // The names of these elements are taken from RFC 3284 section 5.4
  // (Instruction Codes), which contains the following specification:
  //
  // Each instruction code entry contains six fields, each of which is a single
  // byte with an unsigned value:
  // +-----------------------------------------------+
  // | inst1 | size1 | mode1 | inst2 | size2 | mode2 |
  // +-----------------------------------------------+
  //
  unsigned char inst1[kCodeTableSize];  // from enum VCDiffInstructionType
  unsigned char inst2[kCodeTableSize];  // from enum VCDiffInstructionType
  unsigned char size1[kCodeTableSize];
  unsigned char size2[kCodeTableSize];
  unsigned char mode1[kCodeTableSize];  // from enum VCDiffModes
  unsigned char mode2[kCodeTableSize];  // from enum VCDiffModes

 private:
  // Single-letter abbreviations that make it easier to read
  // the default code table data.
  static const VCDiffInstructionType N = VCD_NOOP;
  static const VCDiffInstructionType A = VCD_ADD;
  static const VCDiffInstructionType R = VCD_RUN;
  static const VCDiffInstructionType C = VCD_COPY;

  static bool ValidateOpcode(int opcode,
                             unsigned char inst,
                             unsigned char size,
                             unsigned char mode,
                             unsigned char max_mode,
                             const char* first_or_second);
};

}  // namespace open_vcdiff

#endif  // OPEN_VCDIFF_CODETABLE_H_


text:
Add the bunde to your `composer.json` file:
```javascript
require: {
    // ...
    "earls/rhino-report-bundle": "dev-master@dev",
    "lexik/form-filter-bundle": "v2.0.3"
    // ...
},
"repositories": [
    {
        "type": "vcs",
        "url": "https://github.com/Earls/RhinoReport.git"
    }
]
```

Then run a `composer update`:
```shell
composer.phar update
# OR
composer.phar update earls/rhino-report-bundle # to only update the bundle
```

Register the bundle with your `kernel`:
```php
// in AppKernel::registerBundles()
$bundles = array(
    // ...
    new Earls\RhinoReportBundle\EarlsRhinoReportBundle(),
    // ...
);
```


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

	<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />

	<title>Class: Itsumade::Prompt</title>

	<link rel="stylesheet" href="../rdoc.css" type="text/css" media="screen" />

          Home
          Classes
          Methods

In Files

lib/itsumade/prompt.rb

Parent

Object

Methods

::new

#add_hours

#add_store

#breadcrumbs

#edit_store

#get_confirmation

#get_response

#list_options

#run

#valid_index?

Files

Gemfile

LICENSE

README.rdoc

Rakefile

Class Index

				<form action="#" method="get" accept-charset="utf-8" class="initially-hidden">
				<fieldset>
					<legend>Quicksearch</legend>
					<input type="text" name="quicksearch" value=""
						class="quicksearch-field" />
				</fieldset>
				</form>

Itsumade

Itsumade::Manager

Itsumade::OpeningHours

Itsumade::Prompt

Itsumade::Store

Itsumade::TimeBuilder

No matching classes.

Itsumade::Prompt

Constants

DAYS

WEEKDAYS_SELECTED

WEEKENDS_SELECTED

EVERYDAY_SELECTED

Public Class Methods

					new(manager)
					click to toggle source

    # File lib/itsumade/prompt.rb, line 12
12:     def initialize(manager)
13:       @manager = manager
14:     end

Public Instance Methods

					run()
					click to toggle source

    # File lib/itsumade/prompt.rb, line 16
16:     def run
17:       while true
18:         breadcrumbs
19:         list_options @manager
20:
21:         puts " a: Add store\n"               " x: Exit"
22:         response = get_response('Your selection: ')
23:         case response
24:         when 'a'
25:           add_store
26:         when 'x'
27:           exit
28:         else
29:           edit_store(response.to_i) if valid_index?(response, @manager.length)
30:         end
31:       end
32:     end

Private Instance Methods

					add_hours(index)
					click to toggle source

    # File lib/itsumade/prompt.rb, line 69
69:     def add_hours(index)
70:       breadcrumbs @manager[index].name, 'add hours'
71:       list_options DAYS
72:       weekdays   = get_response('Enter start weekday (0-8): ').to_i
73:       start_hour = get_response('Enter start hour (0-23+):  ').to_i
74:       start_min  = get_response('Enter start minute (0-59): ').to_i
75:       end_hour   = get_response('Enter start hour (0-23+):  ').to_i
76:       end_min    = get_response('Enter start minute (0-59): ').to_i
77:
78:       case weekdays
79:       when WEEKDAYS_SELECTED
80:         weekdays = 1..5
81:       when WEEKENDS_SELECTED
82:         weekdays = [0, 6]
83:       when EVERYDAY_SELECTED
84:         weekdays = 0..6
85:       else
86:         weekdays = [weekdays]
87:       end
88:
89:       weekdays.each do |weekday|
90:         @manager[index] << OpeningHours.new(TimeBuilder.build(weekday, start_hour, start_min),
91:                                             TimeBuilder.build(weekday, end_hour, end_min))
92:       end
93:     end

					add_store()
					click to toggle source

    # File lib/itsumade/prompt.rb, line 95
95:     def add_store
96:       @manager << get_response('Enter name: ')
97:       edit_store(@manager.length - 1)
98:     end

					breadcrumbs(*crumbs)
					click to toggle source

    # File lib/itsumade/prompt.rb, line 37
37:     def breadcrumbs(*crumbs)
38:       puts "\n"
39:       crumbs.unshift 'itsumade'
40:       puts ANSI.yellow + ANSI.bold + crumbs.join(' > ').upcase + ANSI.clear
41:     end

					edit_store(index)
					click to toggle source

     # File lib/itsumade/prompt.rb, line 100
100:     def edit_store(index)
101:       while true
102:         breadcrumbs @manager[index].name
103:         list_options @manager[index]
104:         puts " a: Add hours\n"               " c: Change name\n"               " r: Remove\n"               ' x: Exit'
105:         response = get_response('Your selection: ')
106:         case response
107:         when 'a'
108:           add_hours index
109:         when 'c'
110:           @manager[index].name = get_response('Enter name: ')
111:         when 'r'
112:           if get_confirmation("store #{@manager[index].name}")
113:             @manager.delete_at index
114:             return false
115:           end
116:         when 'x'
117:           @manager.sort!
118:           return false
119:         else
120:           if valid_index?(response, @manager[index].length)
121:             @manager[index].delete_at(response.to_i) if get_confirmation("time ##{response}")
122:           end
123:         end
124:       end
125:     end

					get_confirmation(name)
					click to toggle source

    # File lib/itsumade/prompt.rb, line 56
56:     def get_confirmation(name)
57:       get_response("Delete #{name}? (Y/N): ")[0].downcase == 'y'
58:     end

					get_response(text)
					click to toggle source

    # File lib/itsumade/prompt.rb, line 51
51:     def get_response(text)
52:       print ANSI.bold + text + ANSI.clear
53:       gets.chomp
54:     end

					list_options(options, indent = nil)
					click to toggle source

    # File lib/itsumade/prompt.rb, line 43
43:     def list_options(options, indent = nil)
44:       i = 0
45:       options.each do |option|
46:         puts "#{'% 2d' % i}: #{option}"
47:         i += 1
48:       end
49:     end

					valid_index?(response, length)
					click to toggle source

    # File lib/itsumade/prompt.rb, line 60
60:     def valid_index?(response, length)
61:       if response =~ /^[0-9]+$/
62:         response_index = response.to_i
63:         return response_index >= 0 && response_index < length
64:       else
65:         return false
66:       end
67:     end

Disabled; run with --debug to generate this.

[Validate]

Generated with the Darkfish
			Rdoc Generator 1.1.6.


text:
'use strict';
/**
 * site config
 */
export default {
  //key: value
  name: 'SinalVee\'s Blog',
  description: 'Thoughts, stories and ideas.',
  signature: 'Just do, don\'t BB.',
  githubUrl: 'https://github.com/SinalVee'
};


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';

function SideTab(props) {
  const innerHTML = props.tabType === 'settings' ? 'Settings' :
  const classString = 'SideTab ' + ((props.tabType === 'expressive') === props.isRouteTreeView ? 'activeSideTab' : 'inactiveSideTab');
  return (

 {props.onSideTabClick(props.tabType)}}>
      {innerHTML}

  )
}

SideTab.propTypes = {
  tabType: PropTypes.string,
  isRouteTreeView: PropTypes.bool
}

module.exports = SideTab;


text:
package org.minimallycorrect.mixin.internal;

import lombok.val;
import org.minimallycorrect.javatransformer.api.MethodInfo;
import org.minimallycorrect.javatransformer.api.code.CodeFragment;
import org.minimallycorrect.mixin.Inject;

class Injector {
	static void inject(MethodInfo target, MethodInfo injectable, Inject inject) {
		val targetFragment = target.getCodeFragment();
		val injectableFragment = injectable.getCodeFragment();

		if (targetFragment == null || injectableFragment == null)
			// TODO: log?/throw?
			return;

		val fragments = targetFragment.findFragments(inject.type().getFragmentClass());

		val arg = inject.value();
		val index = inject.index();
		int i = 0;
		for (CodeFragment fragment : fragments) {
			if (!"".equals(arg)) {
				if (fragment instanceof CodeFragment.HasName)
					if (!((CodeFragment.HasName) fragment).getName().equals(arg))
						continue;
					else
						throw new UnsupportedOperationException("Unknown fragment class to match Inject.value into " + fragment.getClass());
			}
			// This must be the last check
			if (index == -1 || index == i)
				try {
					fragment.insert(injectableFragment, inject.position().getPosition());
				} catch (Throwable t) {
					throw new MixinError("Failed to inject " + injectable + " into " + fragment + " in " + target + " with " + inject, t);
				}
			i++;
		}
	}
}


text:
require 'shoulda/active_record/matchers'
require 'shoulda/action_controller/matchers'
require 'shoulda/action_mailer/matchers'
require 'active_support/test_case'

# :enddoc:
module ActiveSupport
  class TestCase
    include Shoulda::ActiveRecord::Matchers
    include Shoulda::ActionController::Matchers
    include Shoulda::ActionMailer::Matchers
  end
end


text:
package leetCode.threadtest;

/**
 * @Author:Dave
 * @Description:
 * @Date: 2017/9/25 16:35
 */
public class PriorityTest extends Thread {
    public PriorityTest(String name){
        super(name);
    }

    public void run(){
        for(int i = 0; i < 50; i ++){
            System.out.println(getName() + "'s ppriority " + getPriority() + " -- " + i);
        }
    }

    public static void main(String[] args){
        Thread.currentThread().setPriority(6);
        for(int i = 0; i < 30; i ++){
            if(i == 10){
                PriorityTest low = new PriorityTest("low level");
                low.start();
                System.out.println("low level thread's priority is " + low.getPriority());
                low.setPriority(Thread.MIN_PRIORITY);
            }
            if(i == 20){
                PriorityTest high = new PriorityTest("super");
                high.start();
                System.out.println("super level thread's priority is " + high.getPriority());
                high.setPriority(Thread.MAX_PRIORITY);
            }
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<workingSetManager>
<workingSet aggregate="true" factoryID="org.eclipse.ui.internal.WorkingSetFactory" id="1403047077979_0" label="Window Working Set" name="Aggregate for window 1403047077979"/>
</workingSetManager>


text:
// Original file: deps/envoy-api/envoy/service/discovery/v3/ads.proto

/**
 * [#not-implemented-hide:] Not configuration. Workaround c++ protobuf issue with importing
 * services: https://github.com/google/protobuf/issues/4221
 */
export interface AdsDummy {
}

/**
 * [#not-implemented-hide:] Not configuration. Workaround c++ protobuf issue with importing
 * services: https://github.com/google/protobuf/issues/4221
 */
export interface AdsDummy__Output {
}


text:
var plugin;
var manager;
var plug;

var events = {};

events.onLoad = function(_plugin) {
    plugin = _plugin;
    manager = plugin.manager;
    plug = manager.getPlugin("plug").plugin.plug;
}

events.command_save = function(message) {
    manager.core.saveConfig();
}

events.command_plugins = function(message) {
    console.log(message);
    if (message.args[0] == "list") {
        var loaded = [];
        var unloaded = [];

        for (var i = 0; i < manager.plugins.length; i++) {
            var plugin = manager.plugins[i];
            console.log(plugin);
            if (plugin.loaded) {
                loaded.push(plugin.meta.name);
            }
            else {
                unloaded.push(plugin.meta.name);
            }
        }

        message.from.sendReply("Loaded: " + loaded.join(", "));
        message.from.sendReply("Available: " + unloaded.join(", "));
    }
    else if (message.args[0] == "refresh") {
        manager.scanPlugins();
        message.from.sendReply("Plugins rescanned");
    }
    else {
        message.from.sendReply("Usage: !plugins list/refresh");
    }
}

events.command_plugin = function(message) {
    var plugin = manager.getPlugin(message.args[1]);
    if (["info", "load", "unload", "reload"].indexOf(message.args[0]) != -1) {
        if (!plugin) {
            message.from.sendReply("Error: Couldn't find plugin");
            return;
        }
    }

    if (message.args[0] == "info") {

    }
    else if (message.args[0] == "load") {
        plugin.load();
        message.from.sendReply("Plugin loaded");
    }
    else if (message.args[0] == "unload") {
        plugin.unload();
        message.from.sendReply("Plugin unloaded");
    }
    else if (message.args[0] == "reload") {
        plugin.reload();
        message.from.sendReply("Plugin reloaded");
    }
    else {
        message.from.sendReply("Usage: !plugin info/load/unload/reload [plugin Name]");
    }
}

events.plug_command_deps = function(message) {
    console.log(manager.getDependencies(message.args[0]));
}

module.exports = {
    "events" : events
};


text:
import java.awt.*;

class ImportDialogLayout implements LayoutManager {
    public ImportDialogLayout() {}
    public void addLayoutComponent(String name, Component c) {}
    public void removeLayoutComponent(Component c) {}
    public Dimension preferredLayoutSize(Container target) {
	return new Dimension(500, 500);
    }
    public Dimension minimumLayoutSize(Container target) {
	return new Dimension(100,100);
    }
    public void layoutContainer(Container target) {
	Insets insets = target.insets();
	int targetw = target.size().width - insets.left - insets.right;
	int targeth = target.size().height - (insets.top+insets.bottom);
	int i;
	int pw = 300;
	if (target.getComponentCount() == 0)
	    return;
	Component cl = target.getComponent(target.getComponentCount()-1);
	Dimension dl = cl.getPreferredSize();
	target.getComponent(0).move(insets.left, insets.top);
	int cw = target.size().width - insets.left - insets.right;
	int ch = target.size().height - insets.top - insets.bottom -
	    dl.height;
	target.getComponent(0).resize(cw, ch);
	int h = ch + insets.top;
	int x = 0;
	for (i = 1; i < target.getComponentCount(); i++) {
	    Component m = target.getComponent(i);
	    if (m.isVisible()) {
		Dimension d = m.getPreferredSize();
		m.move(insets.left+x, h);
		m.resize(d.width, d.height);
		x += d.width;
	    }
	}
    }
};


text:
Docker-Registry-Index-DynamoDB
==============================

# Obsolete

Since the release of [Docker Registry 2](https://docs.docker.com/registry/) this code has become obsolete. Please use that registry, or its commercial version.

A DynamoDB index for the [docker-registry](https://github.com/docker/docker-registry). By default, docker-registry stores its index using [sqlalchemy](http://www.sqlalchemy.org/) in a relational database. This project provides a module that allows you to store the index in [Amazon AWS DynamoDB](http://aws.amazon.com/dynamodb/). This is particularly useful if you are using docker-registry's Amazon S3 driver for your Image Store. With DynamoDB you will have a high-availability index to match the high-availability image store.

# Table of Contents

- [Quick Start](#quick-start)
- [Configuration](#configuration)
- [Manual install](#manual-install)
- [Implementation Details](#implementation-details)

# Quick start

The easiest way to run this is to install docker, then run the docker image:

    docker pull dlaidlaw/docker-registry-index-dynamodb

Then run the docker image, specifying your settings as environment variables:

	docker run -d \
         -e SEARCH_BACKEND=docker_registry_index.dynamodb \
         -e SETTINGS_FLAVOR=prod \
         -e AWS_REGION=us-east-1 \
         -e AWS_BUCKET=mybucket \
         -e STORAGE_PATH=/registry \
         -e AWS_KEY=myawskey \
         -e AWS_SECRET=myawssecret \
         -p 5000:5000 \
         docker_registry_dynamodb

This will pull the image from the docker hub.

# Configuration

See the [docker-registry](https://github.com/docker/docker-registry) project for details on configuring the docker-registry. This project uses the same configuration mechanism, an you may add the configuration to the same configuration file used by docker-registry. The configuration used by this code is stored in the docker-registry config in the extensions section: For example:

	common: &common
	    # add the following
	    search_backend: docker_registry_index.dynamodb

	extensions:
	    dynamodb_index:
	        database: _env:DYNAMODB_DATABASE:docker-registry
	        repository_table: _env:DYNAMODB_REPOSITORY_TABLE
	        version_table: _env:DYNAMODB_VERSION_TABLE
	        region: _env:DYNAMODB_REGION
	        access_key: _env:DYNAMODB_ACCESS_KEY
	        secret_access_key: _env:DYNAMODB_SECRET_ACCESS_KEY

If you do not specify a `repository_table`, then the table name will be formed by adding `-repository` to the end of the `database` name. If you do not specify a `version_table`, then `-version` is added to the `database` name. Note that there is no concept of a database in DynamoDB, the `database` name here is simply used as a prefix for calculating the table names when no table names are specified in the configuration.

The `region` will default to the `s3_region`, which in turn defaults to 'us-east-1'.

The `access_key` and `secret_access_key` default to the value of the `s3_access_key` and `s3_secret_access_key` respectively. If not specified then you must configure these by other means. This code uses [boto Python interface to Amazon Web Services](https://github.com/boto/boto) to access the DynamoDB. Therefore, you can use a boto configuration file in your home directory, or in /etc. For details see the [boto configuration](http://docs.pythonboto.org/en/latest/) documentation.

So if you use the DynamoDB with no configuration specified it will default to using 'docker-registry-repository' as the `respository_table` name, and 'docker-registry-version' as the `version_table` name. The region, access_key and secret_access_key will default to the S3 values or whatever is found in boto configuration. But remember, you must still set the search_backend to docker_registry_index.dynamodb.

# Manual Install

Simply install and run the docker-registry as normal, but first ensure that this python package (docker-registry-index-dynamodb) is installed and set the docker-registry configuration to use it.

* Install docker-registry as normal.
* Install this python package.
  * Available at PYPI: `pip install docker-registry-index-dynamodb`
* Make sure the docker-registry configuration has the `search_backend` set to `docker_registry_index.dynamodb`.
* Optionaly set other configuration as specified above and in the docker-registry project.
* Run the docker-registry.
  * Installing the docker-registry also installs a `docker-registry` command.

# Implementation details

## Startup

At startup the Index class (the one that does all the work) checks to see if the configured DynamoDB table names exist, and if not, create them.

If the tables were created, then the repositories already located in the data store (which is presumably the s3 data store) will be loaded into the repository table. This means that you can delete the DynamoDB tables, and they will be reloaded when the docker-registry is started. You should probably not delete the tables while the docker-registry is running, although they are only used for query.

A simple lock is used in the Index constructor to prevent multiple threads attempting to create and/or load the database at the same time.


text:
<?php
namespace Lulu\Imageboard\Service;

use League\Route\RouteCollection;

interface RESTServiceInterface
{
    public function initRoutes(RouteCollection $routes);
}