text:
--------------------------------------------------------------------------------
{-# LANGUAGE OverloadedStrings, NoMonomorphismRestriction #-}
import           Control.Applicative
import           Control.Monad
import           System.FilePath.Posix
import           System.Process
import           System.Exit
import           Hakyll

import qualified Data.Map as M
import qualified Data.Set as S
import           Data.Char (toLower)
import           Data.List(unfoldr,partition,mapAccumL)
import           Data.Monoid (Monoid, mempty, mconcat, (<>))

import qualified Text.HTML.TagSoup as TS
import qualified Text.Highlighting.Kate as Kate

import           SearchIndex
import qualified Bib
--------------------------------------------------------------------------------

rootAddress :: String
rootAddress = "http://philopon.github.io"

postParPage :: Int
postParPage = 5

recentCount :: Int
recentCount = 5

postsPattern :: Pattern
postsPattern = "posts/**/post.*"

dateFormat :: String
dateFormat = "%Y-%m-%d"

descriptionLength :: Int
descriptionLength = 100

feedConfig :: FeedConfiguration
feedConfig = FeedConfiguration
    { feedTitle       = "About:Blank"
    , feedDescription = ""
    , feedAuthorName  = "philopon"
    , feedAuthorEmail = ""
    , feedRoot        = rootAddress
    }

postRoute :: Identifier -> FilePath
postRoute = (<.> "html"). takeDirectory . toFilePath

citationStyle :: Identifier
citationStyle = "citation-styles/nature.csl"

minifyJs :: Item String -> Compiler (Item String)
minifyJs = processCompiler "./node_modules/uglify-js/bin/uglifyjs" ["--unsafe", "-m", "-mf"]

main :: IO ()
main = hakyll $ do
    match "static/**" $ do
        route . customRoute $ joinPath . tail . splitDirectories . toFilePath
        compile copyFileCompiler

    match ("images/*" .||. "fonts/*" .||. "css/*.min.css") $ do
        route   idRoute
        compile copyFileCompiler

    match ("js/*/*" .&&. complement "js/*/*.min.js") $ do
        route . customRoute $ ("js" </>) . takeFileName . toFilePath
        compile $ getResourceString >>= minifyJs

    match "js/*/*.min.js" $ do
        route . customRoute $ ("js" </>) . (<.> "js") . dropExtensions . takeFileName . toFilePath
        compile getResourceString

    match ("css/*" .&&. complement "css/*.min.css") $ do
        route   idRoute
        compile compressCssCompiler

    match (fromList [citationStyle]) $ compile cslCompiler
    match ("bibliography.*" .||. "posts/**/bibliography.*") $ compile Bib.compiler

    create ["css/highlight.css"] $ do
        route idRoute
        compile $ makeItem (Kate.styleToCss Kate.kate)

    match "templates/*" $ compile templateCompiler

    match "posts/**" $ version "raw" $ do
        route idRoute
        compile copyFileCompiler

    tags <- sortTagsBy tagOrder <$>
            buildTags (postsPattern .&&. hasNoVersion) (\tag -> fromFilePath $ "tags" </> tag </> "1.html")

    singlePages <- createPaginate (postsPattern .&&. hasNoVersion)

    multiPages  <- createPaginateWith postParPage
        (\pn -> if pn == 1
                then "index.html"
                else fromFilePath $ "pages" </> show pn <.> "html")
        (postsPattern .&&. hasNoVersion)

    match postsPattern $ version "post list" $ do
        route mempty
        compile $ postCompiler
            >>= loadAndApplyTemplate "templates/post-list.html"
                ( field "url" (return . ("/" </>) . postRoute . itemIdentifier) <>
                  dateField "date" dateFormat <>
                  defaultContext)

    let postCxt = postContext tags singlePages

    paginateRules singlePages $ \_ _ -> do
        route   $ customRoute postRoute
        compile $ do
            postList <- loadAll (postsPattern .&&. hasVersion "post list") :: Compiler [Item String]

            items <- postCompiler

            void $ saveSnapshot "plain" (fmap stripTags items)

            void $ dropAfterMore items >>= postLink >>= saveSnapshot "summary"

            saveSnapshot "raw_post" items
                >>= loadAndApplyTemplate "templates/post.html"    (postCxt postList)
                >>= loadAndApplyTemplate "templates/default.html" (postCxt postList)
                >>= postLink

    paginateRules multiPages $ \pn pat -> do
        route idRoute
        compile $ do
            posts <- recentFirst . filter (matches pat . setVersion Nothing . itemIdentifier) =<<
                     loadAllSnapshots (postsPattern .&&. hasNoVersion) "summary" :: Compiler [Item String]
            postList <- loadAll (postsPattern .&&. hasVersion "post list") :: Compiler [Item String]

            let paginate = paginateField
                    (\p -> return . fromFilePath $
                        if p == 1
                        then "index.html"
                        else "pages" </> show p <.> "html") multiPages pn

                pagesCxt =
                    paginate <>
                    field "title" (\i ->
                        return $
                            if itemIdentifier i == "index.html"
                            then "Home"
                            else "All posts - " ++ show pn) <>
                    paginateContext multiPages        <>
                    listField "posts" (postCxt postList) (mapM postLink posts) <>
                    globalContext tags postList
            makeItem ""
                >>= loadAndApplyTemplate "templates/multipost.html"   pagesCxt
                >>= loadAndApplyTemplate "templates/default.html" pagesCxt

    tagsRules tags $ \tag pat -> do
        tagPages <- createPaginateWith postParPage
                    (\pn -> fromFilePath $ "tags" </> tag </> show pn <.> "html") pat
        paginateRules tagPages $ \pn pat' -> do
            route idRoute
            compile $ do
                posts <- recentFirst . filter (matches pat' . setVersion Nothing . itemIdentifier) =<<
                         loadAllSnapshots (postsPattern .&&. hasNoVersion) "summary" :: Compiler [Item String]
                postList <- loadAll (postsPattern .&&. hasVersion "post list") :: Compiler [Item String]

                let paginate = paginateField
                        (\p -> return . fromFilePath $ "tags" </> tag </> show p <.> "html")
                        tagPages pn
                let tagsCxt =
                        constField "subbrand" ("Tag:" ++ tag) <>
                        paginate <>
                        constField "title" (tag ++ " - " ++ show pn)    <>
                        listField "posts" (postCxt postList) (mapM postLink posts) <>
                        globalContext tags postList
                makeItem ""
                    >>= loadAndApplyTemplate "templates/multipost.html" tagsCxt
                    >>= loadAndApplyTemplate "templates/default.html"   tagsCxt

    create ["search.json"] $ do
        route idRoute
        compile $ do
            posts <- recentFirst =<< loadAllSnapshots (postsPattern .&&. hasNoVersion) "plain" :: Compiler [Item String]
            let cxt = field "url" (return . ("/" </>) . postRoute . itemIdentifier) <> postCxt []
            Item "search.json" <$> searchIndex cxt descriptionLength [] posts

    create ["search.html"] $ do
        route idRoute
        compile $ do
            postList <- loadAll (postsPattern .&&. hasVersion "post list") :: Compiler [Item String]
            let template = readTemplate "<script type=\"text/javascript\" src=\"$url$\"></script>"
            scripts  <- loadAll "js/search/*" >>= applyJoinTemplateList "\n" template defaultContext

            let cxt = constField "inheader" scripts    <>
                      constField "subbrand" "Search: " <>
                      postCxt postList
            makeItem ""
                >>= loadAndApplyTemplate "templates/searchResult.html" cxt
                >>= loadAndApplyTemplate "templates/default.html" cxt

    create ["sitemap.xml"] $ do
        route idRoute
        compile $ do
            posts <- recentFirst =<< loadAllSnapshots (postsPattern .&&. hasNoVersion) "raw_post" :: Compiler [Item String]
            let template = readTemplate $ "<url>\n  <loc>" ++ rootAddress ++ "$url$</loc>\n  <lastmod>$modified$</lastmod>\n</url>"
            fmap (Item "sitemap.xml") (applyJoinTemplateList "\n" template (modificationTimeField "modified" "%FT%X+09:00" <> defaultContext) posts)
                >>= loadAndApplyTemplate "templates/sitemap.xml" defaultContext

    create ["atom.xml"] $ do
        route idRoute
        compile $ do
            let feedCxt = bodyField "description" <> postCxt []
            posts <- recentFirst =<< loadAllSnapshots (postsPattern .&&. hasNoVersion) "raw_post"
            renderAtom feedConfig feedCxt posts

    create ["rss.xml"] $ do
        route idRoute
        compile $ do
            let feedCxt = bodyField "description" <> postCxt []
            posts <- recentFirst =<< loadAllSnapshots (postsPattern .&&. hasNoVersion) "raw_post"
            renderRss feedConfig feedCxt posts

tagOrder :: (String, [Identifier]) -> (String, [Identifier]) -> Ordering
tagOrder a@(_,ai) b@(_,bi) = case length bi `compare` length ai of
    EQ -> caseInsensitiveTags a b
    o  -> o

nPages :: Paginate -> Int
nPages = M.size . paginatePages

globalContext :: Tags -> [Item String] -> Context String
globalContext tags pl =
    constField "inheader" "" <>
    constField "subbrand" "" <>
    listField "postList" defaultContext (take recentCount <$> recentFirst pl) <>
    field "taglist" (const $ renderTags tagFunc concat tags) <>
    defaultContext
  where tagFunc tag url n _ _ = TS.renderTags
            [ TS.TagOpen "li" []
            , TS.TagOpen "a" [("href", url)]
            , TS.TagText $ tag ++ " "
            , TS.TagClose "a"
            , TS.TagOpen "span" [("class", "badge")]
            , TS.TagText $ show n
            , TS.TagClose "span"
            , TS.TagClose "li"
            ]

postContext :: Tags -> Paginate -> [Item String] -> Context String
postContext tags pagenate pl =
    tagsField "tags" tags <>
    dateField "date" dateFormat <>
    paginateContext pagenate <>
    globalContext tags pl

postLink :: Item String -> Compiler (Item String)
postLink item = do
    mbr <- getRoute $ itemIdentifier item
    return $ case mbr of
        Nothing -> item
        Just r  -> fmap (withUrls $ process r) item
  where
    process _ [] = []
    process r url@(h:_)
        | h == '#'                               = "/" </> r ++ url
        | isRelative url && not (isExternal url) = normalise $ "/" </> dropExtension r </> url
        | otherwise                              = url

paginateField :: (Int -> Compiler Identifier) -> Paginate -> Int -> Context String
paginateField f paginate pn = listField "paginate"
    (field "active" (\i ->
        if itemBody i == show pn
        then return "active"
        else fail "") <> defaultContext)
    (mapM (\n -> f n >>= \i -> return $ Item i (show n)) [1 .. nPages paginate])

addClass :: String -> TS.Tag String -> TS.Tag String
addClass cls (TS.TagOpen name attr) = case partition ((== "class") . fst) attr of
    ([],         _)     -> TS.TagOpen name $ ("class", cls) : attr
    ((_,cls'):_, attr') -> TS.TagOpen name $ ("class", cls ++ ' ': cls') : attr'
addClass _ tag = tag

postCompiler :: Compiler (Item String)
postCompiler = cached "site.postCompiler" $ do
    csl <- load citationStyle :: Compiler (Item CSL)
    global <- load "bibliography.bib" :: Compiler (Item Bib.Bib)
    pat    <- fromGlob . (</> "bibliography.*") . takeDirectory . toFilePath <$> getUnderlying
    local  <- mconcat . map itemBody <$> loadAll (pat .&&. hasNoVersion)
    let bib = Item "" $ local <> itemBody global

    fmap ( demoteHeaders . renderTags'
         . concat . snd . mapAccumL addImageLink False
         . map addTableClass . TS.parseTags) <$>
         ( getResourceBody
            >>= readPandocBiblio defaultHakyllReaderOptions csl (Bib.cast bib)
            >>= return . writePandoc)

  where addTableClass tag | TS.isTagOpenName "table" tag = addClass "table" tag
                          | otherwise                    = tag
        addImageLink a i
            | TS.isTagOpenName   "a" i          = (True,  [i])
            | TS.isTagCloseName  "a" i          = (False, [i])
            | TS.isTagOpenName "img" i && not a = (False, addLink i)
            | otherwise                         = (a, [i])
        addLink img@(TS.TagOpen _ attr) = case lookup "src" attr of
            Nothing  -> [img]
            Just src -> [TS.TagOpen "a" [("href", src)], img, TS.TagClose "a"]
        addLink _ = error "addLink: only TagOpen expected."

dropAfterMore :: Item String -> Compiler (Item String)
dropAfterMore item = do
    StringField url <- unContext (urlField "url") "url" item
    return $ renderTags'. process url . TS.parseTags <$> item
  where
    process _   []                                      = []
    process url (TS.TagComment c:_) | strip c == "more" = [ TS.TagOpen "a" [("href", url), ("class", "readmore")]
                                                          , TS.TagText "read more"
                                                          , TS.TagClose "a"]
    process url (o:ts)                                  = o:process url ts

strip :: String -> String
strip = f . f
  where f = dropWhile (`elem` (" \t" :: String)) . reverse

processCompiler :: FilePath -> [String] -> Item String -> Compiler (Item String)
processCompiler prog opts (Item idnt str) = do
    r <- unsafeCompiler $ readProcessWithExitCode prog opts str
    case r of
        (ExitSuccess  , o, _) -> return $ Item idnt o
        (ExitFailure c, _, e) -> fail $ "processCompiler: " ++ prog ++ ": " ++ e ++ "(exit code: " ++ show c ++ ")"

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

createPaginateWith :: (MonadMetadata m, Functor m) => Int -> (PageNumber -> Identifier) -> Pattern -> m Paginate
createPaginateWith n makeId pattern = do
    idents <- map itemIdentifier <$> (recentFirst . map (`Item` undefined) =<< getMatches pattern)
    let pages          = flip unfoldr idents $ \xs ->
            if null xs then Nothing else Just (splitAt n xs)
        numPages       = length pages
        paginatePages' = zip [1..] pages
        pagPlaces'     =
            [(ident, idx) | (idx,ids) <- paginatePages', ident <- ids] ++
            [(makeId i, i) | i <- [1 .. numPages]]

    return $ Paginate (M.fromList paginatePages') (M.fromList pagPlaces') makeId
        (PatternDependency pattern idents)

createPaginate :: (MonadMetadata m, Functor m) => Pattern -> m Paginate
createPaginate pattern = do
    idents <- map itemIdentifier <$> (recentFirst . map (`Item` undefined) =<< getMatches pattern)
    let pagPages  = M.fromList $ zip [1 ..] (map return idents)
        pagPlaces = M.fromList $ zip idents [1 ..]
        makeId pn = case M.lookup pn pagPages of
            Just [id'] -> id'
            _          -> error $
                "Hakyll.Web.Paginate.buildPaginate: " ++
                "invalid page number: " ++ show pn

    return $ Paginate pagPages pagPlaces makeId
        (PatternDependency pattern idents)

renderTags' :: [TS.Tag String] -> String
renderTags' = TS.renderTagsOptions TS.renderOptions
    { TS.optRawTag   = (`elem` ["script", "style"]) . map toLower
    , TS.optMinimize = (`S.member` minimize) . map toLower
    }
  where
    -- A list of elements which must be minimized
    minimize = S.fromList
        [ "area", "br", "col", "embed", "hr", "img", "input", "meta", "link"
        , "param"
        ]


text:
<?xml version="1.0" encoding="utf-8"?>
<selector
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:color="@color/main_color" />
    <item android:state_selected="true" android:color="@color/main_color" />
    <item android:color="#ffa0a3a2" />
</selector>

redpajama_set_name: RedPajamaGithub


text:
import argparse
import os

import ray
from ray import air, tune
from ray.rllib.algorithms.algorithm import Algorithm
from ray.rllib.evaluation.postprocessing import discount_cumsum
from ray.rllib.policy.tf_policy_template import build_tf_policy
from ray.rllib.utils.framework import try_import_tf

tf1, tf, tfv = try_import_tf()

parser = argparse.ArgumentParser()
parser.add_argument("--stop-iters", type=int, default=200)
parser.add_argument("--num-cpus", type=int, default=0)

def policy_gradient_loss(policy, model, dist_class, train_batch):
    logits, _ = model(train_batch)
    action_dist = dist_class(logits, model)
    return -tf.reduce_mean(
        action_dist.logp(train_batch["actions"]) * train_batch["returns"]
    )

def calculate_advantages(policy, sample_batch, other_agent_batches=None, episode=None):
    sample_batch["returns"] = discount_cumsum(sample_batch["rewards"], 0.99)
    return sample_batch

# <class 'ray.rllib.policy.tf_policy_template.MyTFPolicy'>
MyTFPolicy = build_tf_policy(
    name="MyTFPolicy",
    loss_fn=policy_gradient_loss,
    postprocess_fn=calculate_advantages,
)

# Create a new Algorithm using the Policy defined above.
class MyAlgo(Algorithm):
    @classmethod
    def get_default_policy_class(cls, config):
        return MyTFPolicy

if __name__ == "__main__":
    args = parser.parse_args()
    ray.init(num_cpus=args.num_cpus or None)
    tuner = tune.Tuner(
        MyAlgo,
        run_config=air.RunConfig(
            stop={"training_iteration": args.stop_iters},
        ),
        param_space={
            "env": "CartPole-v1",
            # Use GPUs iff `RLLIB_NUM_GPUS` env var set to > 0.
            "num_gpus": int(os.environ.get("RLLIB_NUM_GPUS", "0")),
            "num_workers": 2,
            "framework": "tf",
        },
    )


text: void kernelVersionVis(uchar4* pos, int width, int height, int major, int minor);


text:
APP_VERSION="5.14.1"

docker build \
    --tag="lburgazzoli/app-activemq:${APP_VERSION}" \
    --build-arg APP_VERSION=${APP_VERSION} \
    .


text:
<?php

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

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=8; IE=7" >

    <title><?php echo $this->escape($this->title) ?></title>

    <link rel="stylesheet" type="text/css" href="library/ExtJS/resources/css/ext-all.css" />
    <link rel="stylesheet" type="text/css" href="library/ExtJS/resources/css/xtheme-blue.css" />
    <?php /*
    <link rel="stylesheet" type="text/css" href="library/ExtJS/resources/css/xtheme-gray.css" />

    */?>

    <?php
        /**
         * this variable gets replaced by the buildscript
         */
        $tineBuildPath = '';

        $locale = Zend_Registry::get('locale');
        switch(TINE20_BUILDTYPE) {
            case 'RELEASE':
                echo "\n    <link rel='stylesheet' type='text/css' href='Tinebase/css/Tinebase-FAT.css' />";
                echo "\n    <link rel='stylesheet' type='text/css' href='Setup/css/Setup-FAT.css' />";
                echo "\n    ";
                echo "\n    ";
                echo "\n    ";
                echo "\n    ";
                break;

            case 'DEBUG':
                echo "\n    <link rel='stylesheet' type='text/css' href='Tinebase/css/Tinebase-FAT.css' />";
                echo "\n    <link rel='stylesheet' type='text/css' href='Setup/css/Setup-FAT.css' />";
                echo "\n    ";
                echo "\n    ";
                echo "\n    ";
                echo "\n    ";
                break;

            case 'DEVELOPMENT':
            default:
                echo $this->jsb2tk->getHTML();
                echo '    ';
                break;
        }?>

    You need to enable javascript to use Tine 2.0 setup or use the CLI setup


text:
<?php

namespace Behat\Gherkin\Node;

use Behat\Gherkin\Exception\NodeException;

/**
 * Represents Gherkin Step.
 *
 * @author Konstantin Kudryashov <ever.zet@gmail.com>
 */
class StepNode implements NodeInterface
{
    /**
     * @var string
     */
    private $keyword;
    /**
     * @var string
     */
    private $keywordType;
    /**
     * @var string
     */
    private $text;
    /**
     * @var ArgumentInterface[]
     */
    private $arguments = array();
    /**
     * @var integer
     */
    private $line;

    /**
     * Initializes step.
     *
     * @param string              $keyword
     * @param string              $text
     * @param ArgumentInterface[] $arguments
     * @param integer             $line
     * @param string              $keywordType
     */
    public function __construct($keyword, $text, array $arguments, $line, $keywordType = null)
    {
        if (count($arguments) > 1) {
            throw new NodeException(sprintf(
                'Steps could have only one argument, but `%s %s` have %d.',
                $keyword,
                $text,
                count($arguments)
            ));
        }

        $this->keyword = $keyword;
        $this->text = $text;
        $this->arguments = $arguments;
        $this->line = $line;
        $this->keywordType = $keywordType ?: 'Given';
    }

    /**
     * Returns node type string
     *
     * @return string
     */
    public function getNodeType()
    {
        return 'Step';
    }

    /**
     * Returns step keyword in provided language (Given, When, Then, etc.).
     *
     * @return string
     *
     * @deprecated use getKeyword() instead
     */
    public function getType()
    {
        return $this->getKeyword();
    }

    /**
     * Returns step keyword in provided language (Given, When, Then, etc.).
     *
     * @return string
     *
     */
    public function getKeyword()
    {
        return $this->keyword;
    }

    /**
     * Returns step type keyword (Given, When, Then, etc.).
     *
     * @return string
     */
    public function getKeywordType()
    {
        return $this->keywordType;
    }

    /**
     * Returns step text.
     *
     * @return string
     */
    public function getText()
    {
        return $this->text;
    }

    /**
     * Checks if step has arguments.
     *
     * @return Boolean
     */
    public function hasArguments()
    {
        return 0 < count($this->arguments);
    }

    /**
     * Returns step arguments.
     *
     * @return ArgumentInterface[]
     */
    public function getArguments()
    {
        return $this->arguments;
    }

    /**
     * Returns step declaration line number.
     *
     * @return integer
     */
    public function getLine()
    {
        return $this->line;
    }
}


text:
"""Converts pixel observation to from int to float32 between 0.0 and 1.0."""

from typing import Dict

from android_env.components import utils
from android_env.wrappers import base_wrapper
import dm_env
from dm_env import specs
import numpy as np

class FloatPixelsWrapper(base_wrapper.BaseWrapper):
  """Wraps AndroidEnv for Panultimate agent."""

  def __init__(self, env: dm_env.Environment):
    super().__init__(env)
    self._input_spec = self._env.observation_spec()['pixels']
    self._should_convert_int_to_float = np.issubdtype(self._input_spec.dtype,
                                                      np.integer)

  def _process_observation(
      self, observation: Dict[str, np.ndarray]
  ) -> Dict[str, np.ndarray]:
    if self._should_convert_int_to_float:
      float_pixels = utils.convert_int_to_float(observation['pixels'],
                                                self._input_spec, np.float32)
      observation['pixels'] = float_pixels
    return observation

  def _process_timestep(self, timestep: dm_env.TimeStep) -> dm_env.TimeStep:
    step_type, reward, discount, observation = timestep
    return dm_env.TimeStep(
        step_type=step_type,
        reward=reward,
        discount=discount,
        observation=self._process_observation(observation))

  def reset(self) -> dm_env.TimeStep:
    return self._process_timestep(self._env.reset())

  def step(self, action: Dict[str, np.ndarray]) -> dm_env.TimeStep:
    return self._process_timestep(self._env.step(action))

  def observation_spec(self) -> Dict[str, specs.Array]:
    if self._should_convert_int_to_float:
      observation_spec = self._env.observation_spec()
      observation_spec['pixels'] = specs.BoundedArray(
          shape=self._env.observation_spec()['pixels'].shape,
          dtype=np.float32,
          minimum=0.0,
          maximum=1.0,
          name=self._env.observation_spec()['pixels'].name)
      return observation_spec
    return self._env.observation_spec()


text:
class JavaRequirement < Requirement
  cask "java"

  env do
    env_java_common
    env_oracle_jdk || env_apple
  end

  private

  def possible_javas
    javas = []
    javas << Pathname.new(ENV["JAVA_HOME"])/"bin/java" if ENV["JAVA_HOME"]
    javas << java_home_cmd
    which_java = which("java")
    # /usr/bin/java is a stub on macOS
    javas << which_java if which_java.to_s != "/usr/bin/java"
    javas
  end

  def java_home_cmd
    return nil unless File.executable?("/usr/libexec/java_home")
    args = %w[--failfast]
    args << "--version" << @version.to_s if @version
    java_home = Utils.popen_read("/usr/libexec/java_home", *args).chomp
    return nil unless $CHILD_STATUS.success?
    Pathname.new(java_home)/"bin/java"
  end

  def env_apple
    ENV.append_to_cflags "-I/System/Library/Frameworks/JavaVM.framework/Versions/Current/Headers/"
  end

  def oracle_java_os
    :darwin
  end
end


text:
package org.jkiss.dbeaver.ui.search.metadata;

import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.*;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.core.CoreMessages;
import org.jkiss.dbeaver.core.DBeaverCore;
import org.jkiss.dbeaver.model.DBPDataSource;
import org.jkiss.dbeaver.model.DBUtils;
import org.jkiss.dbeaver.model.navigator.*;
import org.jkiss.dbeaver.model.preferences.DBPPreferenceStore;
import org.jkiss.dbeaver.model.runtime.DefaultProgressMonitor;
import org.jkiss.dbeaver.model.struct.*;
import org.jkiss.dbeaver.runtime.DBWorkbench;
import org.jkiss.dbeaver.ui.DBeaverIcons;
import org.jkiss.dbeaver.ui.UIUtils;
import org.jkiss.dbeaver.ui.navigator.database.DatabaseNavigatorTree;
import org.jkiss.dbeaver.ui.navigator.database.load.TreeNodeSpecial;
import org.jkiss.dbeaver.ui.search.AbstractSearchPage;
import org.jkiss.utils.CommonUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.List;

public class SearchMetadataPage extends AbstractSearchPage {

    private static final String PROP_MASK = "search.metadata.mask"; //$NON-NLS-1$
    private static final String PROP_CASE_SENSITIVE = "search.metadata.case-sensitive"; //$NON-NLS-1$
    private static final String PROP_MAX_RESULT = "search.metadata.max-results"; //$NON-NLS-1$
    private static final String PROP_MATCH_INDEX = "search.metadata.match-index"; //$NON-NLS-1$
    private static final String PROP_HISTORY = "search.metadata.history"; //$NON-NLS-1$
    private static final String PROP_OBJECT_TYPE = "search.metadata.object-type"; //$NON-NLS-1$
    private static final String PROP_SOURCES = "search.metadata.object-source"; //$NON-NLS-1$

    private Table typesTable;
    private Combo searchText;
    private DatabaseNavigatorTree dataSourceTree;

    private String nameMask;
    private boolean caseSensitive;
    private int maxResults;
    private int matchTypeIndex;
    private Set<DBSObjectType> checkedTypes = new HashSet<>();
    private Set<String> searchHistory = new LinkedHashSet<>();
    private Set<String> savedTypeNames = new HashSet<>();
    private List<DBNNode> sourceNodes = new ArrayList<>();

    public SearchMetadataPage() {
		super("Database objects search");
    }

	@Override
	public void createControl(Composite parent) {
        super.createControl(parent);

        initializeDialogUnits(parent);

        Composite searchGroup = new Composite(parent, SWT.NONE);
        searchGroup.setLayoutData(new GridData(GridData.FILL_BOTH));
        searchGroup.setLayout(new GridLayout(3, false));
        setControl(searchGroup);
        UIUtils.createControlLabel(searchGroup, CoreMessages.dialog_search_objects_label_object_name);
        searchText = new Combo(searchGroup, SWT.DROP_DOWN);
        searchText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
        if (nameMask != null) {
            searchText.setText(nameMask);
        }
        for (String history : searchHistory) {
            searchText.add(history);
        }
        searchText.addModifyListener(e -> {
            nameMask = searchText.getText();
            updateEnablement();
        });

        Composite optionsGroup = new SashForm(searchGroup, SWT.NONE);
        GridLayout layout = new GridLayout(2, true);
        layout.marginHeight = 0;
        layout.marginWidth = 0;
        optionsGroup.setLayout(layout);
        GridData gd = new GridData(GridData.FILL_BOTH);
        gd.horizontalSpan = 3;
        optionsGroup.setLayoutData(gd);

        {
            final DBeaverCore core = DBeaverCore.getInstance();

            Group sourceGroup = UIUtils.createControlGroup(optionsGroup, CoreMessages.dialog_search_objects_group_objects_source, 1, GridData.FILL_BOTH, 0);
            gd = new GridData(GridData.FILL_BOTH);
            //gd.heightHint = 300;
            sourceGroup.setLayoutData(gd);
            final DBNProject projectNode = core.getNavigatorModel().getRoot().getProject(core.getProjectRegistry().getActiveProject());
            DBNNode rootNode = projectNode == null ? core.getNavigatorModel().getRoot() : projectNode.getDatabases();
            dataSourceTree = new DatabaseNavigatorTree(sourceGroup, rootNode, SWT.SINGLE);
            gd = new GridData(GridData.FILL_BOTH);
            gd.heightHint = 300;
            dataSourceTree.setLayoutData(gd);

            dataSourceTree.getViewer().addFilter(new ViewerFilter() {
                @Override
                public boolean select(Viewer viewer, Object parentElement, Object element)
                {
                    if (element instanceof TreeNodeSpecial) {
                        return true;
                    }
                    if (element instanceof DBNNode) {
                        if (element instanceof DBNDatabaseFolder) {
                            DBNDatabaseFolder folder = (DBNDatabaseFolder)element;
                            Class<? extends DBSObject> folderItemsClass = folder.getChildrenClass();
                            return folderItemsClass != null && DBSObjectContainer.class.isAssignableFrom(folderItemsClass);
                        }
                        if (element instanceof DBNLocalFolder ||
                            element instanceof DBNProjectDatabases ||
                            element instanceof DBNDataSource ||
                            (element instanceof DBSWrapper && ((DBSWrapper)element).getObject() instanceof DBSObjectContainer))
                        {
                            return true;
                        }
                    }
                    return false;
                }
            });
            dataSourceTree.getViewer().addSelectionChangedListener(
                event -> {
                    fillObjectTypes();
                    updateEnablement();
                    IStructuredSelection structSel = (IStructuredSelection) event.getSelection();
                    Object object = structSel.isEmpty() ? null : structSel.getFirstElement();
                    if (object instanceof DBNNode) {
                        for (DBNNode node = (DBNNode)object; node != null; node = node.getParentNode()) {
                            if (node instanceof DBNDataSource) {
                                DBNDataSource dsNode = (DBNDataSource) node;
                                dsNode.initializeNode(null, status -> {
                                    if (status.isOK()) {
                                        UIUtils.asyncExec(() -> {
                                            if (!dataSourceTree.isDisposed()) {
                                                fillObjectTypes();
                                            }
                                        });
                                    }
                                });
                                break;
                            }
                        }
                    }
                }
            );
        }

        {
            Group settingsGroup = UIUtils.createControlGroup(optionsGroup, "Settings", 2, GridData.FILL_BOTH, 0);
            gd = new GridData(GridData.FILL_BOTH);
            gd.heightHint = 300;
            settingsGroup.setLayoutData(gd);

            {
                //new Label(searchGroup, SWT.NONE);
                UIUtils.createControlLabel(settingsGroup, CoreMessages.dialog_search_objects_label_name_match);
                final Combo matchCombo = new Combo(settingsGroup, SWT.DROP_DOWN | SWT.READ_ONLY);
                matchCombo.add(CoreMessages.dialog_search_objects_combo_starts_with, SearchMetadataConstants.MATCH_INDEX_STARTS_WITH);
                matchCombo.add(CoreMessages.dialog_search_objects_combo_contains, SearchMetadataConstants.MATCH_INDEX_CONTAINS);
                matchCombo.add(CoreMessages.dialog_search_objects_combo_like, SearchMetadataConstants.MATCH_INDEX_LIKE);
                matchCombo.select(0);
                matchCombo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
                if (matchTypeIndex >= 0) {
                    matchCombo.select(matchTypeIndex);
                }
                matchCombo.addSelectionListener(new SelectionAdapter() {
                    @Override
                    public void widgetSelected(SelectionEvent e)
                    {
                        matchTypeIndex = matchCombo.getSelectionIndex();
                    }
                });
                matchCombo.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING));

                if (maxResults <= 0) {
                    maxResults = 100;
                }

                final Spinner maxResultsSpinner = UIUtils.createLabelSpinner(settingsGroup, CoreMessages.dialog_search_objects_spinner_max_results, maxResults, 1, 10000);
                maxResultsSpinner.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
                maxResultsSpinner.addModifyListener(e -> maxResults = maxResultsSpinner.getSelection());
                maxResultsSpinner.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING));

                final Button caseCheckbox = UIUtils.createLabelCheckbox(settingsGroup, CoreMessages.dialog_search_objects_case_sensitive, caseSensitive);
                caseCheckbox.addSelectionListener(new SelectionAdapter() {
                    @Override
                    public void widgetSelected(SelectionEvent e)
                    {
                        caseSensitive = caseCheckbox.getSelection();
                    }
                });
                caseCheckbox.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

            }

            Label otLabel = UIUtils.createControlLabel(settingsGroup, CoreMessages.dialog_search_objects_group_object_types);
            otLabel.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING));

            typesTable = new Table(settingsGroup, SWT.CHECK | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION);
            typesTable.addSelectionListener(new SelectionAdapter() {
                @Override
                public void widgetSelected(SelectionEvent e)
                {
                    //checkedTypes.clear();
                    for (TableItem item : typesTable.getItems()) {
                        DBSObjectType objectType = (DBSObjectType) item.getData();
                        if (item.getChecked()) {
                            checkedTypes.add(objectType);
                        } else {
                            checkedTypes.remove(objectType);
                        }
                    }
                    updateEnablement();
                }
            });
            typesTable.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseDoubleClick(MouseEvent e) {
                    TableItem[] selection = typesTable.getSelection();
                    if (selection.length > 0) {
                        TableItem tableItem = selection[0];
                        tableItem.setChecked(!tableItem.getChecked());
                    }
                }
            });
            typesTable.setLayoutData(new GridData(GridData.FILL_BOTH));

            UIUtils.createTableColumn(typesTable, SWT.LEFT, CoreMessages.dialog_search_objects_column_type);
            UIUtils.createTableColumn(typesTable, SWT.LEFT, CoreMessages.dialog_search_objects_column_description);
        }

        UIUtils.asyncExec(this::loadState);
    }

    private void loadState() {
        try {
            container.getRunnableContext().run(true, true, monitor -> {
                monitor.beginTask("Load database nodes", 1);
                try {
                    monitor.subTask("Load tree state");
                    sourceNodes = loadTreeState(new DefaultProgressMonitor(monitor), DBWorkbench.getPlatform().getPreferenceStore().getString(PROP_SOURCES));
                } finally {
                    monitor.done();
                }
            });
        } catch (InvocationTargetException e) {
            DBWorkbench.getPlatformUI().showError("Data sources load", "Error loading settings", e.getTargetException());
        } catch (InterruptedException e) {
            // ignore
        }

        if (!sourceNodes.isEmpty()) {
            dataSourceTree.getViewer().setSelection(
                new StructuredSelection(sourceNodes));
            DBNDataSource node = DBNDataSource.getDataSourceNode(sourceNodes.get(0));
            if (node != null) {
                dataSourceTree.getViewer().reveal(node);
            }
        }
        updateEnablement();
    }

    private DBNNode getSelectedNode()
    {
        IStructuredSelection selection = (IStructuredSelection) dataSourceTree.getViewer().getSelection();
        if (!selection.isEmpty()) {
            return (DBNNode) selection.getFirstElement();
        }
        return null;
    }

    private DBPDataSource getSelectedDataSource()
    {
        DBNNode node = getSelectedNode();
        if (node instanceof DBSWrapper) {
            DBSObject object = ((DBSWrapper)node).getObject();
            if (object != null && object.getDataSource() != null) {
                return object.getDataSource();
            }
        }
        return null;
    }

    private DBSStructureAssistant getSelectedStructureAssistant()
    {
        return DBUtils.getAdapter(DBSStructureAssistant.class, getSelectedDataSource());
    }

    private void fillObjectTypes()
    {
        DBSStructureAssistant assistant = getSelectedStructureAssistant();
        typesTable.removeAll();
        if (assistant == null) {
            // No structure assistant - no object types
        } else {
            for (DBSObjectType objectType : assistant.getSupportedObjectTypes()) {
                TableItem item = new TableItem(typesTable, SWT.NONE);
                item.setText(objectType.getTypeName());
                if (objectType.getImage() != null) {
                    item.setImage(0, DBeaverIcons.getImage(objectType.getImage()));
                }
                if (!CommonUtils.isEmpty(objectType.getDescription())) {
                    item.setText(1, objectType.getDescription());
                }
                item.setData(objectType);
                if (checkedTypes.contains(objectType)) {
                    item.setChecked(true);
                } else if (savedTypeNames.contains(objectType.getTypeClass().getName())) {
                    item.setChecked(true);
                    checkedTypes.add(objectType);
                    savedTypeNames.remove(objectType.getTypeClass().getName());
                }
            }
        }
        for (TableColumn column : typesTable.getColumns()) {
            column.pack();
        }
        updateEnablement();
    }

    @Override
    public SearchMetadataQuery createQuery() throws DBException
    {
        DBNNode selectedNode = getSelectedNode();
        DBSObjectContainer parentObject = null;
        if (selectedNode instanceof DBSWrapper && ((DBSWrapper)selectedNode).getObject() instanceof DBSObjectContainer) {
            parentObject = (DBSObjectContainer) ((DBSWrapper)selectedNode).getObject();
        }

        DBPDataSource dataSource = getSelectedDataSource();
        DBSStructureAssistant assistant = getSelectedStructureAssistant();
        if (dataSource == null || assistant == null) {
            throw new IllegalStateException("No active datasource");
        }
        java.util.List<DBSObjectType> objectTypes = new ArrayList<>();
        for (TableItem item : typesTable.getItems()) {
            if (item.getChecked()) {
                objectTypes.add((DBSObjectType) item.getData());
            }
        }
        String objectNameMask = nameMask;

        // Save search query
        if (!searchHistory.contains(objectNameMask)) {
            searchHistory.add(objectNameMask);
            searchText.add(objectNameMask);
        }

        if (matchTypeIndex == SearchMetadataConstants.MATCH_INDEX_STARTS_WITH) {
            if (!objectNameMask.endsWith("%")) { //$NON-NLS-1$
                objectNameMask = objectNameMask + "%"; //$NON-NLS-1$
            }
        } else if (matchTypeIndex == SearchMetadataConstants.MATCH_INDEX_CONTAINS) {
            if (!objectNameMask.startsWith("%")) { //$NON-NLS-1$
                objectNameMask = "%" + objectNameMask; //$NON-NLS-1$
            }
            if (!objectNameMask.endsWith("%")) { //$NON-NLS-1$
                objectNameMask = objectNameMask + "%"; //$NON-NLS-1$
            }
        }

        SearchMetadataParams params = new SearchMetadataParams();
        params.setParentObject(parentObject);
        params.setObjectTypes(objectTypes);
        params.setObjectNameMask(objectNameMask);
        params.setCaseSensitive(caseSensitive);
        params.setMaxResults(maxResults);
        return SearchMetadataQuery.createQuery(dataSource, params);

    }

    @Override
    public void loadState(DBPPreferenceStore store)
    {
        nameMask = store.getString(PROP_MASK);
        caseSensitive = store.getBoolean(PROP_CASE_SENSITIVE);
        maxResults = store.getInt(PROP_MAX_RESULT);
        matchTypeIndex = store.getInt(PROP_MATCH_INDEX);
        for (int i = 0; ;i++) {
            String history = store.getString(PROP_HISTORY + "." + i); //$NON-NLS-1$
            if (CommonUtils.isEmpty(history)) {
                break;
            }
            searchHistory.add(history);
        }

        {
            String type = store.getString(PROP_OBJECT_TYPE);
            if (!CommonUtils.isEmpty(type)) {
                StringTokenizer st = new StringTokenizer(type, "|"); //$NON-NLS-1$
                while (st.hasMoreTokens()) {
                    savedTypeNames.add(st.nextToken());
                }
            }
        }
    }

    @Override
    public void saveState(DBPPreferenceStore store)
    {
        store.setValue(PROP_MASK, nameMask);
        store.setValue(PROP_CASE_SENSITIVE, caseSensitive);
        store.setValue(PROP_MAX_RESULT, maxResults);
        store.setValue(PROP_MATCH_INDEX, matchTypeIndex);
        saveTreeState(store, PROP_SOURCES, dataSourceTree);

        {
            // Search history
            int historyIndex = 0;
            for (String history : searchHistory) {
                if (historyIndex >= 20) {
                    break;
                }
                store.setValue(PROP_HISTORY + "." + historyIndex, history); //$NON-NLS-1$
                historyIndex++;
            }
        }
        {
            // Object types
            StringBuilder typesString = new StringBuilder();
            for (DBSObjectType type : checkedTypes) {
                if (typesString.length() > 0) {
                    typesString.append("|"); //$NON-NLS-1$
                }
                typesString.append(type.getTypeClass().getName());
            }
            store.setValue(PROP_OBJECT_TYPE, typesString.toString());
        }
    }

    protected void updateEnablement()
    {
        boolean enabled = false;
        if (getSelectedDataSource() != null) {
            enabled = !checkedTypes.isEmpty();
        }
        if (CommonUtils.isEmpty(nameMask)) {
            enabled = false;
        }

        container.setPerformActionEnabled(enabled);
    }

    protected static void saveTreeState(DBPPreferenceStore store, String propName, DatabaseNavigatorTree tree)
    {
        // Object sources
        StringBuilder sourcesString = new StringBuilder();
        Object[] nodes = ((IStructuredSelection)tree.getViewer().getSelection()).toArray();
        for (Object obj : nodes) {
            DBNNode node = (DBNNode) obj;
            if (sourcesString.length() > 0) {
                sourcesString.append("|"); //$NON-NLS-1$
            }
            sourcesString.append(node.getNodeItemPath());
        }
        store.setValue(propName, sourcesString.toString());
    }

}


text:
"use strict";

module.exports = function () {
  var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var action = arguments[1];

  switch (action.type) {
    case `CREATE_NODE`:
      state[action.payload.id] = true;
      return state;

    case `TOUCH_NODE`:
      state[action.payload] = true;
      return state;

    default:
      return state;
  }
};
//# sourceMappingURL=nodes-touched.js.map


text:
from authentication.models import Account
from groups.serializers import GroupSerializer
from posts.models import Post
from access.models import AccessRule
from access.serializers import AccessRuleSerializer
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework import status

'''
    Used to update AccessRule instanced. Could not use partial_update in AccessViewSet because apparently
    django_rest_framework does not support HTTP PATCH requests: https://gist.github.com/ahankinson/4282606
    So we had to create this PartialUpdateView in order to handle HTTP POST request in a different way.
    This is more like a hack
'''
class PartialUpdateView(viewsets.ModelViewSet):
    queryset = AccessRule.objects.order_by('order')
    serializer_class = AccessRuleSerializer
    '''
        post_id
        response
        emailNotification

        update the AccessRule link between post and the follower group of request.user
    '''
    def create(self, request, *args, **kwargs):
        post = Post.objects.get(pk=request.data['post_id'])
        ar = post.accessrule_set.get(group__name=request.user.username)
        ar.notify_receiver = False
        ar.save()

        updated_ar = self.serializer_class(ar, data = request.data, partial=True)
        if updated_ar.is_valid():
            updated_ar.save()
            print ar.receiver_response
            return Response(updated_ar.data, status=status.HTTP_200_OK)
        return Response(updated_ar.errors, status=status.HTTP_304_NOT_MODIFIED)

# Handles creating a single AccessRule
class AccessViewSet(viewsets.ModelViewSet):
    queryset = AccessRule.objects.order_by('order')
    serializer_class = AccessRuleSerializer

    '''
    # expecting:
    post: post_id
    # returns: list of all AccessRules for a post
    # (need to call this only when modifying a post)
    '''
    def list(self, request):
        post = Post.objects.get(id=request.data['post'])
        queryset = self.queryset.filter(post=post)
        serializer = self.serializer_class(queryset, many=True)
        return Response(serializer.data)

    '''
    # expecting:
    post: post_id
    rules:
        [
            (group: group_name1, visibility: 'ALL'),
            (group: group_name2, visibility: 'MOD'),
        ]
    # order of rule determined from position in list
    # set all rules at once
    '''

    '''
        Create AccessRule between groups and posts

        The format of data that the front-end passed to us is:
         post: post_id
         rule:
            {"group_name1" : "vis_1",
             "group_name2" : "vis_2",
             "group_name3" : "vis_3"}
    '''
    def create(self, request):
        serializer = self.serializer_class()
        order = 0
        post = Post.objects.get(pk=request.data['post'])
        user = Account.objects.get(email = request.user.email)
        group_rule_dict = request.data['rules'] #keys are group names, values are vis strings

        if post.is_holiday:
            return Response(status=status.HTTP_204_NO_CONTENT)

        for group_name in request.data['rules']:

            rule = {}

            group = user.mygroups.get(name=group_name)

            rule['order'] = order
            rule['visibility'] = group_rule_dict.get(group_name)

            #need partial=True for the serializer to parse it
            serializer = self.serializer_class(data=rule, partial=True)
            serializer.is_valid(raise_exception=True)
            if hasattr(post, 'signup'):
                print 'Shared post is a signup'
                serializer.save(post=post, group=group, receiver_response = 'CONFIRM', notify_receiver = True)
            else:
                serializer.save(post=post, group=group)
            order += 1

        # If a post is shared with a non-follower group, then we should go through the member list and
        # create AccessRule between the post and all the members of the non-follower group. Existing AccessRule
        # are not overwritten
        for group_name in request.data['rules']:
            group = user.mygroups.get(name=group_name)

            if not group.is_follow_group:
                print "this group is not a follower group:"
                print group.name

                group_access = AccessRule.objects.get(post=post, group=group)
                print "this is the already created accessrule for the group:"
                print group_access.visibility

                for member in group.members.all():
                    #Check if an AccessRule is present
                    member_follower_group = user.mygroups.get(name=member.username)
                    print "Member's follower group:"
                    print member_follower_group.name

                    access_query = AccessRule.objects.filter(post = post, group = member_follower_group)
                    if access_query.exists():
                        print "accessRule already exist"
                    else:
                        print "access rule not exist, creating now"
                        AccessRule.objects.create(post=post,
                                                  group=member_follower_group,
                                                  visibility=group_access.visibility,
                                                  order = group_access.order,
                                                  receiver_response = group_access.receiver_response,
                                                  notify_receiver = group_access.notify_receiver)

        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    # Partial update should work by itself

# see shared posts
class AccountAccessViewSet(viewsets.ViewSet):
    queryset = AccessRule.objects.select_related('group')
    serializer_class = AccessRuleSerializer

    '''
    # returns: list of access rules
    '''
    def list(self, request, account_username=None):
        print 'in list'

        # first get complete set of access rules for each group that I am a member of
        user = Account.objects.get(username=account_username)
        groups = user.mygroups.all()
        queryset = self.queryset.none()
        for group in groups:
            queryset = queryset | self.queryset.filter(group=group)

        # then eliminate duplicates for a given post, taking only the highest precedence
        # queryset = queryset.order_by('post', 'order').distinct('post'); requires PostgreSQL
        queryset = queryset.order_by('order')
        posts_seen = set()
        rules_to_remove = set()
        for rule in queryset:
            if rule.post.id in posts_seen:
                rules_to_remove.add(rule)
            else:
                posts_seen.add(rule.post.id)

        for rule in rules_to_remove:
            queryset = queryset.exclude(group=rule.group, post=rule.post)

        serializer = self.serializer_class(queryset, many=True)
        return Response(serializer.data)

'''
    Return a list of users who has given a certain response to post
    Expect
    {post_id:      post_id,
     response:  response}
'''
class NotificationResponseView(viewsets.ModelViewSet):
    queryset = AccessRule.objects.all()
    serializer_class = GroupSerializer

    # Here the input parameters have to be named post_pk and res_pk, because when the front-end
    # call this function, it expects the variable names to be *_pk.
    # For example, when it is not call post_pk, this is the error:
    # list() got an unexpected keyword argument 'post_pk'
    def list(self, request, post_pk, res_pk):
        '''
        print "NotificationResponse View"
        print post_pk
        print res_pk
        '''

        post = Post.objects.get(pk=post_pk)
        response_type = res_pk

        follower_groups = post.shared_with.filter(is_follow_group = True, accessrule__receiver_response=response_type)
        '''
        for ag in follower_groups:
            print ag.name
            print response_type
        '''
        serializer = self.serializer_class(follower_groups, many=True)

        return Response(serializer.data)


text: module.exports = require('css').parse;


text:
package net.sf.mmm.util.nls.impl.formatter;

import javax.inject.Named;
import javax.inject.Singleton;

import net.sf.mmm.util.nls.api.NlsFormatterManager;

/**
 * The {@link NlsFormatterDateTime} for {@link net.sf.mmm.util.nls.api.NlsFormatterManager#STYLE_MEDIUM medium}
 * {@link #getStyle() style}.
 *
 * @author Joerg Hohwiller (hohwille at users.sourceforge.net)
 * @since 2.0.0
 */
@Singleton
@Named
public class NlsFormatterDateTimeMedium extends NlsFormatterDateTime {

  /**
   * The constructor.
   */
  public NlsFormatterDateTimeMedium() {

    super();
  }

  @Override
  public String getStyle() {

    return NlsFormatterManager.STYLE_MEDIUM;
  }

}


text:
@CHARSET "UTF-8";

a:link, a:visited {text-decoration: none; color: #656565;}

.board_list {width:100%;border-top:2px solid #252525;border-bottom:1px solid #ccc}
.board_list thead th:first-child{background-image:none}
.board_list thead th {border-bottom:1px solid #ccc;padding:12px 0 13px 0;color:#3b3a3a;vertical-align:middle}
.board_list tbody td {border-top:1px solid #ccc;padding:10px 0;text-align:center;vertical-align:middle}
.board_list tbody tr:first-child td {border:none}
.board_list tbody td.title {text-align:left; padding-left:20px}
.board_list tbody td a {display:inline-block}

.board_view {width:50%;border-top:2px solid #252525;border-bottom:1px solid #ccc}
.board_view tbody th {text-align:left;background:#f7f7f7;color:#3b3a3a}
.board_view tbody th.list_tit {font-size:13px;color:#000;letter-spacing:0.1px}
.board_view tbody .no_line_b th, .board_view tbody .no_line_b td {border-bottom:none}
.board_view tbody th, .board_view tbody td {padding:15px 0 16px 16px;border-bottom:1px solid #ccc}
.board_view tbody td.view_text {border-top:1px solid #ccc; border-bottom:1px solid #ccc;padding:45px 18px 45px 18px}
.board_view tbody th.th_file {padding:0 0 0 15px; vertical-align:middle}

.wdp_90 {width:90%}
.btn {border-radius:3px;padding:5px 11px;color:#fff !important; display:inline-block; background-color:#6b9ab8; border:1px solid #56819d;vertical-align:middle}


text:
package edu.emory.physics.surfdep.controllers.analysis.functions;

import edu.emory.physics.surfdep.controllers.analysis.AnalysisControl;
import edu.emory.physics.surfdep.utils.InputDialog;

import java.util.HashMap;
import java.util.function.Consumer;

/**
 * Abstracts functionality for generating InputDialogs
 * and running callbacks into a single wrapper class
 * for all AnalysisControl functions.
 *
 * @author Tyler Parsons
 */
public abstract class AnalysisFunction implements Consumer<HashMap<String, String>> {

	protected String title;
	protected String inputMessage;
	protected String[] inputParams;
	protected AnalysisControl control;

	public AnalysisFunction(
		String title,
		String inputMessage,
		String[] inputParams,
		AnalysisControl control
	) {
		this.title = title;
		this.inputMessage = inputMessage;
		this.inputParams = inputParams;
		this.control = control;
	}

	public AnalysisFunction(String title, AnalysisControl control) {
		this(
			title,
			AnalysisControl.DEFAULT_INPUT_MSG,
			AnalysisControl.COMPLETE_MODEL_PARAMS,
			control
		);
	}

	/**
	 * Create input dialog to enable user
	 * specification of trials over which
	 * to run average.
	 */
	public void analyze() {

		new InputDialog(
			inputMessage,
			inputParams,
			this
		);

	}

	public String getTitle() {
		return title;
	}

//	protected String inputMessage;
//	protected String[] inputParams;
//	protected Consumer<HashMap<String, String>> analyzer;
//
//	public AnalysisFunction(
//		String inputMessage,
//		String[] inputParams,
//		Consumer<HashMap<String, String>> analyzer
//	) {
//		this.inputMessage = inputMessage;
//		this.inputParams = inputParams;
//		this.analyzer = analyzer;
//	}
//
//	public AnalysisFunction(Consumer<HashMap<String, String>> analyzer) {
//		this(
//			AnalysisControl.DEFAULT_INPUT_MSG,
//			AnalysisControl.COMPLETE_MODEL_PARAMS,
//			analyzer
//		);
//	}
//
//	public abstract Consumer<HashMap<String, String>> createAnalyzer();
//
//	public void analyze() {
//
//		// Create input dialog to enable user
//		// specification of trials over which
//		// to run average
//
//		new InputDialog(
//			inputMessage,
//			inputParams,
//			(HashMap<String, String> input) -> analyzer.accept(input)
//		);
//
//	}

}


text:
package com.huawei.esdk.fusionmanager.local.impl.autogen.net;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for SwitchInfo complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="SwitchInfo">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="description" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="ip" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="product" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="status" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="switchId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="type" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SwitchInfo", namespace = "http://types.model.hardware.soap.business.net.north.galaxmanager.com/xsd", propOrder = {
    "description",
    "ip",
    "name",
    "product",
    "status",
    "switchId",
    "type"
})
public class SwitchInfo {

    protected String description;
    protected String ip;
    protected String name;
    protected String product;
    protected String status;
    protected String switchId;
    protected String type;

    /**
     * Gets the value of the description property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getDescription() {
        return description;
    }

    /**
     * Sets the value of the description property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setDescription(String value) {
        this.description = value;
    }

    /**
     * Gets the value of the ip property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getIp() {
        return ip;
    }

    /**
     * Sets the value of the ip property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setIp(String value) {
        this.ip = value;
    }

    /**
     * Gets the value of the name property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getName() {
        return name;
    }

    /**
     * Sets the value of the name property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setName(String value) {
        this.name = value;
    }

    /**
     * Gets the value of the product property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getProduct() {
        return product;
    }

    /**
     * Sets the value of the product property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setProduct(String value) {
        this.product = value;
    }

    /**
     * Gets the value of the status property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getStatus() {
        return status;
    }

    /**
     * Sets the value of the status property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setStatus(String value) {
        this.status = value;
    }

    /**
     * Gets the value of the switchId property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getSwitchId() {
        return switchId;
    }

    /**
     * Sets the value of the switchId property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setSwitchId(String value) {
        this.switchId = value;
    }

    /**
     * Gets the value of the type property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getType() {
        return type;
    }

    /**
     * Sets the value of the type property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setType(String value) {
        this.type = value;
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kooboo.CMS.Search.Models;
using Kooboo.CMS.Content.Persistence.Default;
using System.IO;
using Kooboo.CMS.Content.Models.Paths;

namespace Kooboo.CMS.Search.Persistence.Default
{
    public class SearchSettingProvider : FileSystemProviderBase<SearchSetting>, ISearchSettingProvider
    {
        static System.Threading.ReaderWriterLockSlim locker = new System.Threading.ReaderWriterLockSlim();
        public IQueryable<SearchSetting> All(Content.Models.Repository repository)
        {
            var baseDir = SearchSetting.FolderSearchSettingPath.GetBasePhysicalPath(repository);
            List<SearchSetting> list = new List<SearchSetting>();

            if (Directory.Exists(baseDir))
            {
                foreach (var file in IO.IOUtility.EnumerateFilesExludeHidden(baseDir, "*" + PathHelper.SettingFileExtension))
                {
                    list.Add(new SearchSetting(repository, Path.GetFileNameWithoutExtension(file.Name)));
                }
            }

            return list.AsQueryable();
        }

        protected override System.Threading.ReaderWriterLockSlim GetLocker()
        {
            return locker;
        }
    }
}


text:
var chalk = require('chalk');
var inquirer = require('inquirer');
var CreateSchemas = require('./CreateSchemas');
var WriteConfig = require('./WriteConfig');

var exports = module.exports = {}

  exports.welcomeMessage = function(version) {
    var starString = '*************************************';
    return '\n\n\n'+starString+'\n\n'+'  Welcome to Trimurti (Version '+version+')\n\n'+starString+'\n';
  };

  exports.displayIntro = function() {
    return (
      'Trimurti is a data driven CMS which will allow content editors to easily add updates to your node API.'+'\n\n'+'Note: At the moment Trimurti is limited to a single feed with simple routes and no parameters e.g. https://url.ext/api/routename \n\n'+'To get started, follow the instructions below:\n\r'
    )
  }

  exports.askQuestions = function() {
    var questions = [
      {
        type: 'input',
        name: 'Name',
        message: 'What do you want to name your new Trimurti app?',
        default: 'MYAPP',
        validate: function (value) {
          var pass = value.match(/^[a-zA-Z0-9_]+$/);
          if (pass) { return true; }
          return 'Please do not use spaces or special characters (only A-Z a-z 0-9 and \'_\')';
        }
      },
      {
        type: 'input',
        name: 'API',
        message: 'What is the full URL of your API entrypoint (without a trailing /)?:',
        default: 'http://localhost:8080/api',
        validate: function (value) {
          var pass = value.match(/^(https?):\/\/([A-Z\d\.-]{2,})\.?([A-Z]{2,})?(:\d{2,5})?(\/)?([A-Z\d\.\-_?#&%=]{1,})?$/i);
          if (pass) { return true; }
          return 'That doesn\'t look like a valid url. Don\'t forget the \'http(s)!\'';
        }
      },
      {
        type: 'input',
        name: 'Routes',
        message: 'Please list your API routes (not including your entrypoint) as a comma seperated list? e.g. people, places, sausage-types',
        filter: function (val) {
          return val.toLowerCase().replace(/ /g, '');
        }
      }
    ]

    inquirer.prompt(questions)
    .then(function (answers) {
      console.log('Brill!, you are creating a new Trimurti app named', chalk.cyan(answers.Name));
      console.log('Trimurti will now build your editor from', chalk.cyan(answers.API), 'using the following routes:');
      if (answers.Routes) {
        var routes = answers.Routes.split(',');
        for (var i = 0; i < routes.length; i++) {
          console.log(chalk.cyan(answers.API +'/'+routes[i]+'/'));
        }
      } else {
        console.log(chalk.cyan(answers.API +'/'));
      }

      confirmer(answers);
    });

    var confirm = [
      {
        type: 'confirm',
        name: 'Happy',
        message: 'Are you happy with your answers?:',
        default: true
      }
    ]

    var confirmer = function(answers) {
      inquirer.prompt(confirm)
      .then(function (confirmations) {
        if(confirmations.Happy) {
          console.log(chalk.green('✔ Glad to hear it! Trimurti is now generating your editor'));
          WriteConfig.makeFile(answers);
          CreateSchemas.init(answers);
        } else {
          console.log(chalk.red('✘ Aww! I guess you need to start again, I\'m afraid'));
        }
      });
    }
  }

  // Execute all methods
  exports.init = function() {
    var message = this.welcomeMessage(process.env.npm_package_version);
    var intro = this.displayIntro();
    console.log(chalk.blue(message)+'\n'+chalk.yellow(intro));
    this.askQuestions();
  }


text:
namespace ui {

class TSFEventRouterObserver {
 public:
  TSFEventRouterObserver() {}

  TSFEventRouterObserver(const TSFEventRouterObserver&) = delete;
  TSFEventRouterObserver& operator=(const TSFEventRouterObserver&) = delete;

  // Called when the number of currently opened candidate windows changes.
  virtual void OnCandidateWindowCountChanged(size_t window_count) {}

  // Called when a composition is started.
  virtual void OnTSFStartComposition() {}

  // Called when the text contents are updated. If there is no composition,
  // gfx::Range::InvalidRange is passed to |composition_range|.
  virtual void OnTextUpdated(const gfx::Range& composition_range) {}

  // Called when a composition is terminated.
  virtual void OnTSFEndComposition() {}

 protected:
  virtual ~TSFEventRouterObserver() {}
};

// This class monitors TSF related events and forwards them to given
// |observer|.
class COMPONENT_EXPORT(UI_BASE_IME_WIN) TSFEventRouter {
 public:
  // Do not pass NULL to |observer|.
  explicit TSFEventRouter(TSFEventRouterObserver* observer);

  TSFEventRouter(const TSFEventRouter&) = delete;
  TSFEventRouter& operator=(const TSFEventRouter&) = delete;

  virtual ~TSFEventRouter();

  // Returns true if the IME is composing text.
  bool IsImeComposing();

  // Callbacks from the TSFEventRouterDelegate:
  void OnCandidateWindowCountChanged(size_t window_count);
  void OnTSFStartComposition();
  void OnTextUpdated(const gfx::Range& composition_range);
  void OnTSFEndComposition();

  // Sets |thread_manager| to be monitored. |thread_manager| can be NULL.
  void SetManager(ITfThreadMgr* thread_manager);

 private:
  class Delegate;

  Microsoft::WRL::ComPtr<Delegate> delegate_;

  raw_ptr<TSFEventRouterObserver> observer_;
};

}  // namespace ui

#endif  // UI_BASE_IME_WIN_TSF_EVENT_ROUTER_H_


text:
The Greek Bible App is nearing the first major release that should be fully published on the app stores.

[Greek Bible App](http://www.toldpro.com/Apps/GreekBible/)

### New Features

- Improved Performance
- Verse Selector
- Entry Details Popup
	- View meaning of morphology symbols
	- View Strong's Definition
	- Navigate to related definitions

### Developer Notes

Everything about the app is working well. It is passing all tests and the usability is good.

It will be uploaded for testing to be used for one week prior to the final polishing before the major release.

#### 5 Hour App Thoughts

The 5-Hour App technique promotes high porduction value. However, it is not sufficient to produce a major release in 5 hours.

Therefore, the 5-hour period will be used as a minor version. Then when then minor versions reach a fully-publishable state, it will be a major version.

Versions previously referred to as V1, V2 should be considered V0.1, V0.2, etc.

#### Links:

- [Greek Bible App](http://www.toldpro.com/Apps/GreekBible/)
- [GitHub Source Code](https://github.com/ricklove/GreekBibleApp/tree/ReleaseV0_3)
- [PhoneGap - Latest Version](https://build.phonegap.com/apps/783113/install)


text:
package org.agmip.translators.dssat;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import org.agmip.util.JSONAdapter;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

/**
 * Unit test for simple App.
 */
/**
 *
 * @author Meng Zhang
 */
public class DssatControllerTest {

    DssatControllerOutput obDssatControllerOutput;
    DssatControllerInput obDssatControllerInput;
    URL resource;
    URL resource2;
    String fileName =
//                        "UFGA8401_CPX.ZIP";
//                        "GHWA0401_MZX.ZIP";
//                        "UFGA8201_MZX.ZIP";
//                        "UFGA8202_MZX.ZIP";
//                        "UFGA8201_MZX_dummy.ZIP";
//                        "SWData.zip";
//                        "AGMIP_DSSAT_1359154224136.zip";
//                        "HSC_wth_bak.zip";
    "IUAM9801_FAX.zip";

    @Before
    public void setUp() throws Exception {
        obDssatControllerOutput = new DssatControllerOutput();
        obDssatControllerInput = new DssatControllerInput();
        resource = this.getClass().getResource("/" + fileName);
        resource2 = this.getClass().getResource("/CRAFT/Sample_Run");
    }

    @Test
    @Ignore
    public void test() throws IOException, Exception {
        HashMap result;
        Calendar cal;
        String outPath;
        File outDir;
        ArrayList<File> files;
        result = obDssatControllerInput.readFile(resource.getPath());
//        BufferedOutputStream bo;
//        File f = new File("output\\" + fileName.replaceAll("[Xx]*\\.\\w+$", ".json"));
//        bo = new BufferedOutputStream(new FileOutputStream(f));
//
//        // Output json for reading
//        bo.write(JSONAdapter.toJSON(result).getBytes());
//        bo.close();
//        f.delete();

        cal = Calendar.getInstance();
        outPath = "output\\AGMIP_DSSAT_" + cal.getTimeInMillis();
        obDssatControllerOutput = new DssatControllerOutput();
        obDssatControllerOutput.writeFile(outPath, result);
        outDir = new File(outPath);
        files = obDssatControllerOutput.getOutputFiles();
        for (File file : files) {
            System.out.println("Generated: " + file.getName());
        }
        obDssatControllerOutput.createZip();
        System.out.println("Generated: " + obDssatControllerOutput.getOutputZipFile().getPath());
        obDssatControllerOutput.getOutputZipFile().delete();
        outDir.delete();

        String jsonStr;
        InputStream is = this.getClass().getClassLoader().getResourceAsStream("Machakos_1Exp-1Yr.json");
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        jsonStr = br.readLine();
        cal = Calendar.getInstance();
        outPath = "output\\AGMIP_DSSAT_" + cal.getTimeInMillis();
        obDssatControllerOutput = new DssatControllerOutput();
        obDssatControllerOutput.writeFile(outPath, JSONAdapter.fromJSON(jsonStr));
        outDir = new File(outPath);
        files = obDssatControllerOutput.getOutputFiles();
        for (File file : files) {
            System.out.println("Generated: " + file.getName());
        }
        obDssatControllerOutput.createZip();
        System.out.println("Generated: " + obDssatControllerOutput.getOutputZipFile().getName());
        obDssatControllerOutput.getOutputZipFile().delete();
        outDir.delete();

        // Test for CRAFT
        result = obDssatControllerInput.readFileFromCRAFT(resource2.getPath());
//        f = new File("output/CRAFT.json");
//        bo = new BufferedOutputStream(new FileOutputStream(f));
//
//        // Output json for reading
//        bo.write(JSONAdapter.toJSON(result).getBytes());
//        bo.close();
//        f.delete();

        cal = Calendar.getInstance();
        outPath = "output\\AGMIP_DSSAT_" + cal.getTimeInMillis();
        obDssatControllerOutput = new DssatControllerOutput();
        obDssatControllerOutput.writeFile(outPath, result);
        outDir = new File(outPath);
        files = obDssatControllerOutput.getOutputFiles();
        for (File file : files) {
            System.out.println("Generated: " + file.getName());
            file.delete();
        }
        outDir.delete();
    }
}


text:
package com.gotwo.codegen;

/**
 * Created by florian on 11/12/15.
 */
public class LearnASM extends GoTwoBase{

    public static void main(String[] args) {
        LearnASM learn = new LearnASM();

        learn.start();
    }

    public void run() {
        if(currentScope == null) {
            int x;
        } else {
            int y;
        }

    }

}


text:
#define ALEMBIC_UNUSED_13_CLASSID					Class_ID(0x75d0291, 0x77876660)
#define ALEMBIC_UNUSED_14_CLASSID					Class_ID(0x27697f4e, 0x33b63fa5)
#define ALEMBIC_UNUSED_15_CLASSID					Class_ID(0x27de063a, 0x28fe18d9)
#define ALEMBIC_UNUSED_16_CLASSID					Class_ID(0x53da05d3, 0x90d1f9b)
#define ALEMBIC_UNUSED_17_CLASSID					Class_ID(0x7c0b4f98, 0x73e11929)
#define ALEMBIC_UNUSED_18_CLASSID					Class_ID(0x250b6e7a, 0xaf8348b)
#define ALEMBIC_UNUSED_19_CLASSID					Class_ID(0x42b015db, 0x8270650)
#define ALEMBIC_UNUSED_20_CLASSID					Class_ID(0x6ae5099b, 0x38c35ddd)
#define ALEMBIC_UNUSED_21_CLASSID					Class_ID(0x24cb562c, 0x6c4a5f9a)
#define ALEMBIC_UNUSED_22_CLASSID					Class_ID(0x4b3429e8, 0x2da67188)
#define ALEMBIC_UNUSED_23_CLASSID					Class_ID(0x7b2a5520, 0x19ab0773)
#define ALEMBIC_UNUSED_24_CLASSID					Class_ID(0x1b3227e1, 0x101202b8)
#define ALEMBIC_UNUSED_25_CLASSID					Class_ID(0x46c911e9, 0x7ce4278f)
#define ALEMBIC_UNUSED_26_CLASSID					Class_ID(0x6f941105, 0x377862fd)

ClassDesc2* GetAlembicXformControllerClassDesc();
ClassDesc2* GetAlembicVisibilityControllerClassDesc();

ClassDesc2* GetAlembicParticlesClassDesc();

ClassDesc2* GetAlembicMeshTopoModifierClassDesc();
ClassDesc2* GetAlembicMeshGeomModifierClassDesc();
ClassDesc2* GetAlembicMeshNormalsModifierClassDesc();
ClassDesc2* GetAlembicMeshUVWModifierClassDesc();

ClassDesc2 *GetEmptySplineObjectClassDesc();
ClassDesc2 *GetEmptyPolyLineObjectClassDesc();

ClassDesc2 *GetAlembicSplineGeomModifierClassDesc();
ClassDesc2 *GetAlembicSplineTopoModifierClassDesc();

ClassDesc2* GetAlembicFloatControllerClassDesc();

extern HINSTANCE hInstance;

#endif //__ALEMBIC_NAMES_H__


text:
package org.apache.spark.api.java;

import org.apache.spark.storage.StorageLevel;

/**
 * Expose some commonly useful storage level constants.
 */
public class StorageLevels {
  public static final StorageLevel NONE = new StorageLevel(false, false, false, 1);
  public static final StorageLevel DISK_ONLY = new StorageLevel(true, false, false, 1);
  public static final StorageLevel DISK_ONLY_2 = new StorageLevel(true, false, false, 2);
  public static final StorageLevel MEMORY_ONLY = new StorageLevel(false, true, true, 1);
  public static final StorageLevel MEMORY_ONLY_2 = new StorageLevel(false, true, true, 2);
  public static final StorageLevel MEMORY_ONLY_SER = new StorageLevel(false, true, false, 1);
  public static final StorageLevel MEMORY_ONLY_SER_2 = new StorageLevel(false, true, false, 2);
  public static final StorageLevel MEMORY_AND_DISK = new StorageLevel(true, true, true, 1);
  public static final StorageLevel MEMORY_AND_DISK_2 = new StorageLevel(true, true, true, 2);
  public static final StorageLevel MEMORY_AND_DISK_SER = new StorageLevel(true, true, false, 1);
  public static final StorageLevel MEMORY_AND_DISK_SER_2 = new StorageLevel(true, true, false, 2);

  /**
   * Create a new StorageLevel object.
   * @param useDisk saved to disk, if true
   * @param useMemory saved to memory, if true
   * @param deserialized saved as deserialized objects, if true
   * @param replication replication factor
   */
  public static StorageLevel create(boolean useDisk, boolean useMemory, boolean deserialized, int replication) {
    return StorageLevel.apply(useDisk, useMemory, deserialized, replication);
  }
}