text:
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_GHC -fno-warn-warnings-deprecations #-}

{-| Combines the construction of RPC server components and their Python stubs.

-}

{-

Copyright (C) 2013 Google Inc.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

-}

module Ganeti.THH.PyRPC
  ( genPyUDSRpcStub
  , genPyUDSRpcStubStr
  ) where

import Prelude ()
import Ganeti.Prelude

import Control.Monad (liftM, zipWithM)
import Data.Char (toLower, toUpper)
import Data.Maybe (fromMaybe)
import Language.Haskell.TH
import Language.Haskell.TH.Syntax (liftString)
import Text.PrettyPrint

import Ganeti.THH.Types

-- | The indentation step in generated Python files.
pythonIndentStep :: Int
pythonIndentStep = 2

-- | A helper function that nests a block of generated output by the default
-- step (see 'pythonIndentStep').
nest' :: Doc -> Doc
nest' = nest pythonIndentStep

-- | The name of an abstract function to which all method in a Python stub
-- are forwarded to.
genericInvokeName :: String
genericInvokeName = "_GenericInvoke"

-- | The name of a function that returns the socket path for reaching the
-- appropriate RPC client.
socketPathName :: String
socketPathName = "_GetSocketPath"

-- | Create a Python expression that applies a given function to a list of
-- given expressions
apply :: String -> [Doc] -> Doc
apply name as = text name <> parens (hcat $ punctuate (text ", ") as)

-- | An empty line block.
emptyLine :: Doc
emptyLine = text "" -- apparently using 'empty' doesn't work

lowerFirst :: String -> String
lowerFirst (x:xs) = toLower x : xs
lowerFirst []     = []

upperFirst :: String -> String
upperFirst (x:xs) = toUpper x : xs
upperFirst []     = []

-- | Creates a method declaration given a function name and a list of
-- Haskell types corresponding to its arguments.
toFunc :: String -> [Type] -> Q Doc
toFunc fname as = do
    args <- zipWithM varName [1..] as
    let args' = text "self" : args
        callName = lowerFirst fname
    return $ (text "def" <+> apply fname args') <> colon $+$
             nest' (text "return" <+>
                    text "self." <>
                    apply genericInvokeName (text (show callName) : args)
             )
  where
    -- | Create a name for a method argument, given its index position
    -- and Haskell type.
    varName :: Int -> Type -> Q Doc
    varName _   (VarT n)              = lowerFirstNameQ n
    varName _   (ConT n)              = lowerFirstNameQ n
    varName idx (AppT ListT t)        = listOf idx t
    varName idx (AppT (ConT n) t)
      | n == ''[]                     = listOf idx t
      | otherwise                     = kind1Of idx n t
    varName idx (AppT (AppT (TupleT 2) t) t')
                                      = pairOf idx t t'
    varName idx (AppT (AppT (ConT n) t) t')
      | n == ''(,)                    = pairOf idx t t'
    varName idx t                     = do
      report False $ "Don't know how to make a Python variable name from "
                     ++ show t ++ "; using a numbered one."
      return $ text ('_' : show idx)

    -- | Create a name for a method argument, knowing that its a list of
    -- a given type.
    listOf :: Int -> Type -> Q Doc
    listOf idx t = (<> text "List") <$> varName idx t

    -- | Create a name for a method argument, knowing that its wrapped in
    -- a type of kind @* -> *@.
    kind1Of :: Int -> Name -> Type -> Q Doc
    kind1Of idx name t = (<> text (nameBase name)) <$> varName idx t

    -- | Create a name for a method argument, knowing that its a pair of
    -- the given types.
    pairOf :: Int -> Type -> Type -> Q Doc
    pairOf idx t t' = do
      tn <- varName idx t
      tn' <- varName idx t'
      return $ tn <> text "_" <> tn' <> text "_Pair"

    lowerFirstNameQ :: Name -> Q Doc
    lowerFirstNameQ = return . text . lowerFirst . nameBase

-- | Creates a method declaration by inspecting (reifying) Haskell's function
-- name.
nameToFunc :: Name -> Q Doc
nameToFunc name = do
    (as, _) <- funArgs `liftM` typeOfFun name
    -- If the function has just one argument, try if it isn't a tuple;
    -- if not, use the arguments as they are.
    let as' = fromMaybe as $ case as of
                                [t] -> tupleArgs t -- TODO CHECK!
                                _   -> Nothing
    toFunc (upperFirst $ nameBase name) as'

-- | Generates a Python class stub, given a class name, the list of Haskell
-- functions to expose as methods, and a optionally a piece of code to
-- include.
namesToClass
  :: String       -- ^ the class name
  -> Doc          -- ^ Python code to include in the class
  -> [Name]       -- ^ the list of functions to include
  -> Q Doc
namesToClass cname pycode fns = do
  fnsCode <- mapM (liftM ($+$ emptyLine) . nameToFunc) fns
  return $ vcat [ text "class" <+> apply cname [text "object"] <> colon
                , nest' (
                    pycode $+$ vcat fnsCode
                  )
                ]

-- | Takes a list of function names and creates a RPC handler that delegates
-- calls to them, as well as writes out the corresponding Python stub.
--
-- See 'mkRpcM' for the requirements on the passed functions and the returned
-- expression.
genPyUDSRpcStub
  :: String     -- ^ the name of the class to be generated
  -> String     -- ^ the name of the constant from @constants.py@ holding
                --   the path to a UDS socket
  -> [Name]     -- ^ names of functions to include
  -> Q Doc
genPyUDSRpcStub className constName = liftM (header $+$) .
                                      namesToClass className stubCode
  where
    header = text "# This file is automatically generated, do not edit!" $+$
             text "# pylint: skip-file"
    stubCode =
      abstrMethod genericInvokeName [ text "method", text "*args"] $+$
      method socketPathName [] (
         text "from ganeti import pathutils" $+$
         text "return" <+> text "pathutils." <> text constName)
    method name args body =
      text "def" <+> apply name (text "self" : args) <> colon $+$
      nest' body $+$
      emptyLine
    abstrMethod name args = method name args $
      text "raise" <+> apply "NotImplementedError" []

-- The same as 'genPyUDSRpcStub', but returns the result as a @String@
-- expression.
genPyUDSRpcStubStr
  :: String   -- ^ the name of the class to be generated
  -> String   -- ^ the constant in @pathutils.py@ holding the socket path
  -> [Name]   -- ^ functions to include
  -> Q Exp
genPyUDSRpcStubStr className constName names =
    liftString . render =<< genPyUDSRpcStub className constName names


text:
using System.Collections.ObjectModel;
using System.Windows.Data;
using WPFDemo.Contactmanagement.DbAccess;
using WPFDemo.Contactmanagement.Model;

namespace WPFDemo.Contactmanagement.ViewModel
{
    public class ContactViewModel : PropertyWatcher
    {
        private readonly ContactRepository contactRepository;

        private string keyword;
        private readonly DelegateCommand<string> searchByKeywordCommand;

        private ObservableCollection<Contact> contacts;
        private Contact selectedContact;
        private readonly DelegateCommand<string> saveContact;

        public ContactViewModel(ContactRepository contactRepository)
        {
            this.contactRepository = contactRepository;

            this.Keyword = string.Empty;
            this.searchByKeywordCommand = new DelegateCommand<string>(
                s => CollectionViewSource.GetDefaultView(this.Contacts).Refresh(),
                null
            );

            this.saveContact = new DelegateCommand<string>(
                s => this.contactRepository.SaveChanges(),
                null
            );

            var allContacts = this.contactRepository.GetAll();
            this.Contacts = new ObservableCollection<Contact>(allContacts);
            var view = CollectionViewSource.GetDefaultView(this.Contacts);
            view.Filter += obj =>
            {
                var contact = obj as Contact;
                return contact.Fullname.ToLower().Contains(this.Keyword.ToLower());
            };
        }

        public string Keyword
        {
            get { return this.keyword; }
            set { this.SetValue(ref this.keyword, value, "Keyword"); }
        }

        public DelegateCommand<string> SearchByKeywordCommand
        {
            get { return this.searchByKeywordCommand; }
        }

        public DelegateCommand<string> SaveContact
        {
            get { return this.saveContact; }
        }

        public ObservableCollection<Contact> Contacts
        {
            get { return this.contacts; }
            set { this.SetValue(ref this.contacts, value, "Contacts"); }
        }

        public Contact SelectedContact
        {
            get { return this.selectedContact; }
            set { this.SetValue(ref this.selectedContact, value, "SelectedContact"); }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.twitter.penguin.korean.tools

import java.io.FileOutputStream

import com.twitter.penguin.korean.TwitterKoreanProcessor._
import com.twitter.penguin.korean.tokenizer.KoreanTokenizer.KoreanToken
import com.twitter.penguin.korean.util.KoreanDictionaryProvider._

/**
 * Create Korean Parsing examples.
 */
object CreateParsingExamples extends Runnable  {
  case class ParsingExample(text: String, parse: Seq[KoreanToken])

  def run {
    System.err.println("Reading the goldenset..")

    val parsedPairs = readFileByLineFromResources("example_chunks.txt").flatMap {
      case line if line.length > 0 =>
        val chunk = line.trim
        val parsed = tokenize(chunk)
        Some(ParsingExample(chunk, parsed))
      case line => None
    }.toSet

    val outputFile: String = "src/test/resources/com/twitter/penguin/korean/util/current_parsing.txt"

    System.err.println("Writing the new goldenset to " + outputFile)

    val out = new FileOutputStream(outputFile)
    parsedPairs.foreach {
      p =>
        out.write(p.text.getBytes)
        out.write("\t".getBytes)
        out.write(p.parse.mkString("/").getBytes)
        out.write("\n".getBytes)
    }
    out.close()

    System.err.println("Testing the new goldenset " + outputFile)
  }
}


text:
var test = require("test");
try {
    require("a");
    require("A");
    test.assert(false, "should fail to require alternate spelling");
} catch (error) {
}
test.print("DONE", "info");


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Threading.Tasks;

namespace TrophonTheGrumpyCat
{
    class Program
    {
        static void Main(string[] args)
        {
            var priceRatings = Console.ReadLine()
                .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                .Select(long.Parse)
                .ToArray();
            int entryPoint = int.Parse(Console.ReadLine());
            string typeOfItems = Console.ReadLine();
            string typeOfPriceRatings = Console.ReadLine();

            //calculate left damage
            //calculate right damage
            //print higher damage
            //if equal  - print left

            //cheap - lower than the entry price
            // ecpensive - same or higher price than the entry point

            //positive - above 0
            // negative - below 0
            // all - any

            BigInteger leftSum = 0;
            BigInteger rightSum = 0;
            var leftList = new List<long>();
            var rightList = new List<long>();

            if(typeOfItems == "cheap")
            {
                if(typeOfPriceRatings == "positive")
                {
                    //left
                    for (int i = 0; i < entryPoint; i++)
                    {
                        if(priceRatings[i] > 0 && priceRatings[i] < priceRatings[entryPoint])
                        {
                            leftList.Add(priceRatings[i]);
                        }
                    }

                    //right
                    for (long i = entryPoint + 1; i < priceRatings.Length; i++)
                    {
                        if (priceRatings[i] > 0 && priceRatings[i] < priceRatings[entryPoint])
                        {
                            rightList.Add(priceRatings[i]);
                        }
                    }
                }
                if (typeOfPriceRatings == "negative")
                {
                    //left
                    for (int i = 0; i < entryPoint; i++)
                    {
                        if (priceRatings[i] < 0 && priceRatings[i] < priceRatings[entryPoint])
                        {
                            leftList.Add(priceRatings[i]);
                        }
                    }

                    //right
                    for (long i = entryPoint + 1; i < priceRatings.Length; i++)
                    {
                        if (priceRatings[i] < 0 && priceRatings[i] < priceRatings[entryPoint])
                        {
                            rightList.Add(priceRatings[i]);
                        }
                    }
                }
                if (typeOfPriceRatings == "all")
                {
                    //left
                    for (int i = 0; i < entryPoint; i++)
                    {
                        if (priceRatings[i] < priceRatings[entryPoint])
                        {
                            leftList.Add(priceRatings[i]);
                        }
                    }

                    //right
                    for (long i = entryPoint + 1; i < priceRatings.Length; i++)
                    {
                        if (priceRatings[i] < priceRatings[entryPoint])
                        {
                            rightList.Add(priceRatings[i]);
                        }
                    }
                }
            }
            else
            {
                if (typeOfPriceRatings == "positive")
                {
                    //left
                    for (int i = 0; i < entryPoint; i++)
                    {
                        if (priceRatings[i] > 0 && priceRatings[i] >= priceRatings[entryPoint])
                        {
                            leftList.Add(priceRatings[i]);
                        }
                    }

                    //right
                    for (long i = entryPoint + 1; i < priceRatings.Length; i++)
                    {
                        if (priceRatings[i] > 0 && priceRatings[i] >= priceRatings[entryPoint])
                        {
                            rightList.Add(priceRatings[i]);
                        }
                    }
                }
                if (typeOfPriceRatings == "negative")
                {
                    //left
                    for (int i = 0; i < entryPoint; i++)
                    {
                        if (priceRatings[i] < 0 && priceRatings[i] >= priceRatings[entryPoint])
                        {
                            leftList.Add(priceRatings[i]);
                        }
                    }

                    //right
                    for (long i = entryPoint + 1; i < priceRatings.Length; i++)
                    {
                        if (priceRatings[i] < 0 && priceRatings[i] >= priceRatings[entryPoint])
                        {
                            rightList.Add(priceRatings[i]);
                        }
                    }
                }
                if (typeOfPriceRatings == "all")
                {
                    //left
                    for (int i = 0; i < entryPoint; i++)
                    {
                        if (priceRatings[i] >= priceRatings[entryPoint])
                        {
                            leftList.Add(priceRatings[i]);
                        }
                    }

                    //right
                    for (long i = entryPoint + 1; i < priceRatings.Length; i++)
                    {
                        if (priceRatings[i] >= priceRatings[entryPoint])
                        {
                            rightList.Add(priceRatings[i]);
                        }
                    }
                }
            }

            leftSum = leftList.Sum();
            rightSum = rightList.Sum();

            if(leftSum >= rightSum)
            {
                Console.WriteLine($"Left - {leftSum}");
            }else
            {
                Console.WriteLine($"Right - {rightSum}");
            }
        }
    }
}


text:
package iso20022

// Choice between an amount or a rate or an unspecified rate.
type TaxCreditRateFormat10Choice struct {

	// Value is expressed as a rate.
	Rate *PercentageRate `xml:"Rate"`

	// Number of monetary units specified in a currency.
	Amount *RestrictedFINActiveCurrencyAnd13DecimalAmount `xml:"Amt"`

	// Specifies different formats for the tax credit rate.
	RateTypeAndAmountAndRateStatus *RateTypeAndAmountAndStatus34 `xml:"RateTpAndAmtAndRateSts"`

	// Value of the rate not specified.
	NotSpecifiedRate *RateValueType7Code `xml:"NotSpcfdRate"`
}

func (t *TaxCreditRateFormat10Choice) SetRate(value string) {
	t.Rate = (*PercentageRate)(&value)
}

func (t *TaxCreditRateFormat10Choice) SetAmount(value, currency string) {
	t.Amount = NewRestrictedFINActiveCurrencyAnd13DecimalAmount(value, currency)
}

func (t *TaxCreditRateFormat10Choice) AddRateTypeAndAmountAndRateStatus() *RateTypeAndAmountAndStatus34 {
	t.RateTypeAndAmountAndRateStatus = new(RateTypeAndAmountAndStatus34)
	return t.RateTypeAndAmountAndRateStatus
}

func (t *TaxCreditRateFormat10Choice) SetNotSpecifiedRate(value string) {
	t.NotSpecifiedRate = (*RateValueType7Code)(&value)
}


text:
<?php

namespace Dolondro\TheGrid;

use Dolondro\TheGrid\Exception\ValidationException;

class GridFactory
{
    protected $validator;

    /**
     * GridFactory constructor.
     *
     * @param Validator $validator
     */
    public function __construct(Validator $validator)
    {
        $this->validator = $validator;
    }

    /**
     * Arguments could be made that GridFactory is an inefficient way of doing things as it means that everytime someone
     * wants to update a grid, they're building a new instance of a grid
     *
     * To make Grid something that can be changed however feels outside of the remit of this project. The idea I'm going
     * for is to be able to easily render grids in the terminal. I don't want the concept of a Grid to be something that
     * we're actually storign data in
     *
     * @param $array
     * @throws ValidationException
     * @return Grid
     */
    public function create($array)
    {
        $this->validator->validate($array);
        return new Grid($array);
    }
}


text:
layout: post
title: My 2017 GSoC Project - Part XIII
subtitle: Rough Edges of A Promising Piece
category: Programming
tags: [GSoC-2017, Scilab, Modelica]
---

Hello again,

The time has come and I can't go any further inside the ongoing **GSoC Final Term Evaluation** period. Therefore, I shall "lay down the pencil" and submit [the work done so far](http://bitiquinho.github.io/feed-gsoc2017.xml).

Fortunately, I have some new positive results to share.

### Successes

At the time of [my last post]({% post_url 2017-08-15-new_breath %}), **segfaults** in **FMI2** calls during simulation were preventing us to have a usable **OpenModelica** based solution. Gladly, I was able to track down the problem to its root, a **fmi2Terminate** call, that turned out to be unneeded. That way, now we can run a complete **Modelica** diagram simulation without crashing **Scilab**.

Also, I discovered that some **OpenModelica** forum searches lead me to outdated information, and the default options for model library compilation on which I was relying have been changed. Now, for building a pure **Model Exchange** library with no dependencies, as originally intended, the generation call inside **.mos** scripts must receive a few extra arguments, like in:

{% highlight python %}
buildModelFMU( model_name, version="2.0", fmuType="me", platforms={"static"} );
{% endhighlight %}

Finally, comparison between the old **modelicac** compiler and **OpenModelica** one shows that the new implementation is able to yield similar results, which is a must, in most of the cases:

(modelicac "Chaos" model simulation)

(omc "Chaos" model simulation)

(modelicac RLC circuit simulation)

(omc RLC circuit simulation)

(modelicac 2nd order model simulation)

(omc 2nd order model model simulation)

(modelicac bouncing ball simulation)

(omc bouncing ball simulation)

### Persisting Issues

As seen in the last comparison, I still couldn't find a way to make the **FMI2** wrapper properly handle **events** such as mechanical collisions, even if they are at least correctly detected.

Another issue that prevented me from testing more **Xcos Modelica** examples was a bug in generation of **flattened** (all code combined into a single file) **.mo** files, where mathematical signs end up duplicated, causing errors in the following compilation, like in the one from **"Ball in a platform"** demo:

{% highlight javascript %}
class Ball_Platform_im
  parameter Real Ball_Platform1__g = 9.800000000000001;
  parameter Real Ball_Platform1__m1 = 0.5;
  parameter Real Ball_Platform1__m2 = 0.3;
  parameter Real Ball_Platform1__k = 2.0;
  Real Ball_Platform1__y1(start = 11.0);
  Real Ball_Platform1__v1(start = 0.0);
  Real Ball_Platform1__y2(start = 15.0);
  Real Ball_Platform1__v2(start = 1.0);
  Real Ball_Platform1__y0;
  discrete Real Ball_Platform1__v1p;
  discrete Real Ball_Platform1__v2p;
  output Real OutPutPort1__vo;
  Real OutPutPort1__vi;
  output Real OutPutPort2__vo;
  Real OutPutPort2__vi;
equation
  Ball_Platform1__y0 = 10.0;
  der(Ball_Platform1__y1) = Ball_Platform1__v1;
  // Minus sign following plus sign and not isolated by parentheses
  Ball_Platform1__m1 * der(Ball_Platform1__v1) = if noEvent(Ball_Platform1__v1 < 0.001) and noEvent(Ball_Platform1__v1 > -0.001) then 0.0 else Ball_Platform1__k * (Ball_Platform1__y0 - Ball_Platform1__y1) + -0.2 * Ball_Platform1__v1 - Ball_Platform1__m1 * Ball_Platform1__g;
  der(Ball_Platform1__y2) = Ball_Platform1__v2;
  der(Ball_Platform1__v2) = if noEvent(Ball_Platform1__v2 < 0.001) and noEvent(Ball_Platform1__v2 > -0.001) then 0.0 else -Ball_Platform1__g;
  when Ball_Platform1__y2 < Ball_Platform1__y1 then
    Ball_Platform1__v1p = (Ball_Platform1__m1 * Ball_Platform1__v1 + Ball_Platform1__m2 * (2.0 * Ball_Platform1__v2 - Ball_Platform1__v1)) / (Ball_Platform1__m1 + Ball_Platform1__m2);
    Ball_Platform1__v2p = (Ball_Platform1__m2 * Ball_Platform1__v2 + Ball_Platform1__m1 * (2.0 * Ball_Platform1__v1 - Ball_Platform1__v2)) / (Ball_Platform1__m1 + Ball_Platform1__m2);
    reinit(Ball_Platform1__v1, 0.98 * Ball_Platform1__v1p);
    reinit(Ball_Platform1__v2, 0.98 * Ball_Platform1__v2p);
  end when;
  OutPutPort1__vi = OutPutPort1__vo;
  OutPutPort2__vi = OutPutPort2__vo;
  Ball_Platform1__y2 = OutPutPort1__vi;
  Ball_Platform1__y1 = OutPutPort2__vi;
end Ball_Platform_im;
{% endhighlight %}

As the error is caused by a **third-party** tool, **OMCompiler**, I've submitted a [**bug report**](https://trac.openmodelica.org/OpenModelica/ticket/4503#ticket) for it to be fixed **upstream**.

### Build System Integration

One task that I ended up leaving to the end and didn't take the time to blog about before is the replacement of **modelicac** and [**OCaml**](https://ocaml.org/) sources by **OMCompiler** ones in **Scilab**'s repository and build process. For my work I could simply use a minimal system-wide version of **OpenModelica**, but providing it as a bundled tool is useful for systems where is not easy to get a clean **OMCompiler** install.

Fortunately, **Scilab** uses the same [**autotools**](https://en.wikipedia.org/wiki/GNU_build_system) build system as the compiler, so integration is facilitated (but still cumbersome enough to make me hope for a [**CMake**](https://cmake.org/) solution, which is less powerful but easier to get).

After some modifications to **OMCompiler** build scripts (which were still looking for unneeded dependencies for [minimal **omc-no-sim** target](({% post_url 2017-07-31-omc %}))), I've removed **modelicac** and **OCaml** entries from **Scilab**'s ones and added conditional support for our new tool.

- In **scilab/configure.ac**:
{% highlight bash %}
# ...

XCOS_ENABLE=no
OMC_TARGET=""
OMC_INSTALL_TARGET=""

if test "$with_xcos" != no; then
   AC_DEFINE([WITH_XCOS], [], [with XCos])

   save_LIBS="$LIBS"

   AC_CHECK_LIB([rt], [clock_gettime],
              [RT_LIB="-lrt";
              AC_DEFINE([HAVE_CLOCK_GETTIME], [1],[Whether clock_gettime is available]) ],
        [AC_MSG_WARN([librt: library missing (Cannot find symbol clock_gettime). Check if librt is installed (it is usually provided by the libc) and if the version is correct])]
   )
   LIBS="$save_LIBS"
   AC_SUBST(RT_LIB)

#################
## modelica compiler which only called when using Xcos
#################

   if test "$with_modelica" != no; then
      CPPFLAGS="$CPPFLAGS -DH5_USE_18_API"
      OMC_TARGET="modelica-compiler"                    # "make" command target
      OMC_INSTALL_TARGET="install-modelica-compiler"    # "make install" command target
      AC_CONFIG_FILES([
      modules/scicos/src/modelica_compiler/Makefile
     ])
      AC_CONFIG_SUBDIRS([modules/scicos/src/modelica_compiler])
      USE_METIS=0
      WITH_UMFPACK=no
      OMBUILDDIR="../../"                               # put compiled binaries into modules/scicos/bin
      AC_SUBST(USE_METIS)
      AC_SUBST(WITH_UMFPACK)
      AC_SUBST(OMBUILDDIR)
   fi
   XCOS_ENABLE=yes

fi

AC_SUBST(XCOS_ENABLE)
AC_SUBST(OMC_TARGET)
AC_SUBST(OMC_INSTALL_TARGET)

# ...
{% endhighlight %}

- In **scilab/Makefile.in**:
{% highlight bash %}
# ...

# Build modelica stuff
modelica-compiler: $(MAKE) -C modules/scicos/src/modelica_compiler omc-no-sim
install-modelica-compiler: $(MAKE) -C modules/scicos/src/modelica_compiler install \
	cp modules/scicos_blocks/includes/fmi2_wrapper.h $(DESTDIR)$(pkgincludedir)/fmi2_wrapper.h
# ...
all-am: Makefile $(PROGRAMS) $(SCRIPTS) $(DATA) all-local $(OMC_TARGET)
install-am: all-am
	@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am $(OMC_INSTALL_TARGET)
# ...
{% endhighlight %}

### Missing Work

Apart from necessary fixes, remaining work for offering a full **modelicac** replacement involves improving **Windows** (mainly **64 bits**) compatibility (the **FMI2** library imports are formed erratically, [most probably an upstream problem as well](https://trac.openmodelica.org/OpenModelica/ticket/3790)) and better testing the integration of **OMCompiler** into **Scilab**'s build process.

### Final Thoughts

In the end, some aspects of this project ended up being more troublesome than expected, even if I knew since the beginning that it was a difficult task, and I couldn't make as much progress as I wanted. Nevertheless, I also admit lack of organization with my time and academic/real life affairs that held me back quite a lot. Shame on me, right ?!

On the other hand, I'm happy with all the learning experience and the fact that I was able to get the **OpenModelica** integration to work, to some extent. The **FMI2** specification, particularly, was a great finding that I surely intend to use for some of my future projects.

From now on it's all about cleaning up/submitting the code (hosted in a [public **GitHub** repository](https://github.com/Bitiquinho/Scilab-OpenModelica-Integration)) and waiting for my mentors evaluation. I'm thankful for all the help they provided me and I'll respect any decision regarding this final phase.

That's it for this **2017 GSoC**. Thanks one more time for sticking with me over the course of this (northern) summer.

I hope to come back soon with new things to show.


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/RelativeLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/forte_start_screen"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btn_home"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="40dp"
        android:background="@drawable/special_button"
        android:gravity="center_vertical|center_horizontal|center"
        android:text="@string/welcome"
        android:visibility="invisible" />

    <ProgressBar
        android:id="@+id/progressBar1"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="5dp"
        android:max="100" />

    <LinearLayout
        android:id="@+id/lay_nearest"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/btn_home"
        android:layout_alignParentTop="true"
        android:layout_alignRight="@+id/btn_home"
        android:layout_marginTop="114dp"
        android:visibility="invisible" >

        <fragment
            android:id="@+id/fragment1"
            android:name="com.audax.dev.forte.NearestCenterFragment"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </LinearLayout>

</RelativeLayout>


text:
#include "OptimizeEnumsUnmap.h"

#include "CFGMutation.h"
#include "Show.h"
#include "Trace.h"

/**
 * A switch map is initialized with the *runtime* length of the enum values()
 * array. The known enums are then assigned a strictly positive case value,
 * which is put in the switch map; i.e. `lookup[enum.ordinal()] = case;`.
 *
 * It is possible that the runtime enum has more variants than the clinit
 * knew about when compiled. Because the switch map used the runtime length,
 * it has a safety net: an unknown ordinal maps to zero. When an enum is
 * switched over, it actually switches over `lookup[enum.ordinal()]`. All of
 * the switch cases are converted to the known positive case values and the
 * default case is used to handle unknown ordinals (i.e., zero).
 *
 * ---
 *
 * When a switch is converted to a sequence of if statements by D8, the
 * default case becomes the trailing `else` case. Although a switch map
 * lookup could result in 0, it is not explicitly listed as a case.
 *
 * Due to this we can omit looking at IF_EQZ/IF_NEZ opcodes. Even if we
 * came across an explicit 0 case, unmapping that would require non-trivial
 * rearrangement to turn it back into the `else` case. Given that this
 * doesn't occur in practice, implementing this is omitted; if we see a
 * case value of 0, we give up as the fallback.
 *
 * -----
 *
 * In Kotlin, a switchmap may not be the only source value to a switch. When
 * switching over a nullable enum, the null case is "switch mapped" to -1.
 * This allows the null case to gracefully remain alongside the others:
 *
 *     val foo: Foo? = ...;
 *     when (foo) {
 *         null -> <null case>
 *         Foo.THIS -> <this case>
 *         Foo.THAT -> <that case>
 *     }
 *
 * Compiles into something analogous to:
 *
 *     val mapped = if (foo == null) {
 *         -1
 *     } else {
 *         T$WhenMappings.$EnumSwitchMapping[foo.ordinal()]
 *     };
 *     when (mapped) {
 *         -1 -> <null case>
 *          1 -> <this case>
 *          2 -> <that case>
 *     }
 *
 * This causes problems for unmapping, because there is no enum corresponding
 * to -1 in a switchmap. However, because -1 is not a valid ordinal we can
 * simply consider the "ordinal" of a null enum to be -1 as well. This allows
 * us to leave the case values of -1 untouched:
 *
 *     val unmapped = if (foo == null) {
 *         -1
 *     } else {
 *         foo.ordinal()
 *     };
 *     when (unmapped) {
 *         -1 -> <null case>
 *          0 -> <this case>
 *          1 -> <that case>
 *     }
 *
 * We are effectively pretending the const -1 instruction is ordinal().
 *
 * ---
 *
 * A quirk of the above Kotlin null handling is that in order to use a
 * packed switch, the 0 case (which is typically left as the default case)
 * must be made explicit. This is counter to the vanilla Java invariants
 * described above.
 *
 * When D8 turns such a switch into a sequence of if statements it merges
 * the 0 case with the default case. As a result, there is no explicit if
 * statement comparing to zero and our typical invariants hold.
 *
 * However, when the switch remains as such then we may see an "unexpected"
 * case of 0. As long as it goes to the same target as the default case,
 * we will consider it obsolete once we unmap and delete it. (The case 0
 * slot will be filled by an ordinal instead.)
 */

namespace optimize_enums {
namespace {

// The ordinal we will give a null Kotlin enum.
//
// This is able to be the same value as the null Kotlin enum switchmap value,
// because non-null ordinals are always >= 0. In turn, this allows us to do
// minimal changes to the structure of switches and keep them packed.
constexpr int32_t kKotlinNullOrdinal = -1;

/**
 * The state and helper functions while unmapping a CFG.
 *
 * For every matching cmp instr, we apply the inverse mapping.
 *
 *  INVOKE_VIRTUAL <v_enum> <Enum>;.ordinal:()
 *  MOVE_RESULT <v_ordinal>
 *  ...
 *  AGET <v_switchmap>, <v_ordinal>
 *  MOVE_RESULT_PSEUDO <v_mapped>
 *  ...
 *  IF_EQ <v_mapped> C  // Some constant C.
 *
 * Becomes:
 *
 *  INVOKE_VIRTUAL <v_enum> <Enum>;.ordinal:()
 *  MOVE_RESULT <v_ordinal>
 *  MOVE <v_ordinal_cpy> <v_ordinal> // Newly added
 *  ...
 *  AGET <v_switchmap>, <v_ordinal>  // Dead code
 *  MOVE_RESULT_PSEUDO <v_mapped>  // Dead code
 *  ...
 *  IF_EQ <v_ordinal_cpy> C'
 *
 * Where C' is the ordinal that would switchmap to C.
 *
 * This causes use of the switch map to become dead code. We rely
 * on a DCE pass to actually remove it all once it has become unused.
 */
class OptimizeEnumsUnmapCfg {
 public:
  OptimizeEnumsUnmapCfg(const OptimizeEnumsUnmapMatchFlow& flow,
                        const EnumFieldToOrdinal& enum_field_to_ordinal,
                        const GeneratedSwitchCases& generated_switch_cases,
                        cfg::ControlFlowGraph& cfg)
      : m_flow(flow),
        m_enum_field_to_ordinal(enum_field_to_ordinal),
        m_generated_switch_cases(generated_switch_cases),
        m_cfg(cfg),
        m_mutation(cfg) {}

  void unmap_switchmaps() {
    auto cmp_locations = {
        m_flow.cmp_switch,
        m_flow.cmp_if_src0,
        m_flow.cmp_if_src1,
    };
    auto res = m_flow.flow.find(m_cfg, cmp_locations);

    for (auto cmp_location : cmp_locations) {
      unmap_location(res, cmp_location);
    }

    m_mutation.flush();
  }

 private:
  void unmap_location(const mf::result_t& res, mf::location_t cmp_location) {
    // The source index the switchmap lookup flows into.
    //
    // Src 0 for switch and if_src0, and src 1 for if_scr1.
    const src_index_t aget_src = cmp_location == m_flow.cmp_if_src1;

    // For each matching comparison...
    for (auto* insn_cmp : res.order(res.matching(cmp_location))) {
      auto cmp_it = m_cfg.find_insn(insn_cmp);
      always_assert(!cmp_it.is_end());

      // ...find the aget instrs supplying it. From each aget we find the
      // field being used to do the lookup, and can continue as long as
      // all of them use the identical switchmap. While we're doing this
      // we also gather up all the places an ordinal feeds into the map.
      auto insn_aget_or_m1_range =
          res.matching(cmp_location, insn_cmp, aget_src);
      const auto [lookup_field, insn_ordinal_list] =
          get_lookup_and_ordinals(res, insn_aget_or_m1_range);

      if (!lookup_field) {
        // No clear switchmap to undo. Unactionable in general.
        continue;
      }

      // Grab the inverse lookup from case-value to enum. Our lookup
      // instruction was constrained to only match on fields present
      // in generated_switch_cases, so this entry always exists.
      const auto case_to_enum_it = m_generated_switch_cases.find(lookup_field);

      always_assert(case_to_enum_it != m_generated_switch_cases.end());
      const auto& case_to_enum = case_to_enum_it->second;

      // Stash the ordinal sources in a new temporary register.
      const reg_t ordinal_reg = m_cfg.allocate_temp();
      for (IRInstruction* insn_ordi : insn_ordinal_list) {
        copy_ordinal(insn_ordi, ordinal_reg);
      }

      // Finally, update the comparison.
      if (cmp_location == m_flow.cmp_switch) {
        unmap_switch(insn_cmp, cmp_it, case_to_enum, ordinal_reg);
      } else {
        always_assert(cmp_location == m_flow.cmp_if_src0 ||
                      cmp_location == m_flow.cmp_if_src1);

        // Grab all the incoming const instructions.
        const src_index_t const_src = 1 - aget_src;

        const auto insn_kase_range =
            res.matching(cmp_location, insn_cmp, const_src);
        always_assert(insn_kase_range);

        unmap_if(insn_cmp, cmp_it, case_to_enum, ordinal_reg, aget_src,
                 const_src, insn_kase_range);
      }
    }
  }

  std::tuple<DexFieldRef*, std::vector<IRInstruction*>> get_lookup_and_ordinals(
      const mf::result_t& res, mf::result_t::src_range insn_aget_or_m1_range) {
    DexFieldRef* unique_lookup_field = nullptr;
    std::vector<IRInstruction*> insn_ordinal_list;

    for (IRInstruction* insn_aget_or_m1 : insn_aget_or_m1_range) {
      // Kotlin null enum "ordinal"; see top of file.
      if (opcode::is_const(insn_aget_or_m1->opcode())) {
        always_assert(insn_aget_or_m1->get_literal() == kKotlinNullOrdinal);

        insn_ordinal_list.push_back(insn_aget_or_m1);
        continue;
      }

      // Every lookup field must be *identical* to safely unmap.
      for (IRInstruction* insn_look :
           res.matching(m_flow.aget_or_m1, insn_aget_or_m1, 0)) {
        auto* lookup_field = insn_look->get_field();

        if (unique_lookup_field == nullptr) {
          unique_lookup_field = lookup_field;
        } else if (lookup_field != unique_lookup_field) {
          TRACE(ENUM, 1, "Mismatched switchmap lookup fields; %s is not %s",
                SHOW(lookup_field), SHOW(unique_lookup_field));

          return {nullptr, {}};
        }
      }

      // Remember where all the ordinal results are, for later copying.
      for (IRInstruction* insn_ordi :
           res.matching(m_flow.aget_or_m1, insn_aget_or_m1, 1)) {
        insn_ordinal_list.push_back(insn_ordi);
      }
    }

    always_assert(!unique_lookup_field || !insn_ordinal_list.empty());
    return std::make_tuple(unique_lookup_field, std::move(insn_ordinal_list));
  }

  void copy_ordinal(IRInstruction* insn_ordi, reg_t ordinal_reg) {
    auto ordi_it = m_cfg.find_insn(insn_ordi);
    always_assert(!ordi_it.is_end());

    // Kotlin null enum ordinal; see top of file.
    if (opcode::is_const(insn_ordi->opcode())) {
      always_assert(insn_ordi->get_literal() == kKotlinNullOrdinal);

      IRInstruction* ordinal_const = new IRInstruction(OPCODE_CONST);
      ordinal_const->set_dest(ordinal_reg);
      ordinal_const->set_literal(kKotlinNullOrdinal);

      m_mutation.insert_after(ordi_it, {ordinal_const});
      return;
    }

    auto ordi_move_result_it = m_cfg.move_result_of(ordi_it);
    always_assert(!ordi_move_result_it.is_end());

    const auto reg_ordinal = ordi_move_result_it->insn->dest();

    const auto move_ordinal_result = new IRInstruction(OPCODE_MOVE);
    move_ordinal_result->set_src(0, reg_ordinal);
    move_ordinal_result->set_dest(ordinal_reg);

    m_mutation.insert_after(ordi_move_result_it, {move_ordinal_result});
  }

  boost::optional<size_t> get_ordinal_for_case(
      const GeneratedSwitchCasetoField& case_to_enum, int64_t case_value) {
    // Turn the case value back into the enum ordinal.
    const auto case_enum_it = case_to_enum.find(case_value);
    if (case_enum_it == case_to_enum.end()) {
      // We don't actually have a full inverse mapping.
      return boost::none;
    }
    const auto case_enum = case_enum_it->second;

    const auto enum_ordinal_it = m_enum_field_to_ordinal.find(case_enum);
    if (enum_ordinal_it == m_enum_field_to_ordinal.end()) {
      // We don't actually have a full ordinal mapping.
      return boost::none;
    }
    const auto enum_ordinal = enum_ordinal_it->second;

    return enum_ordinal;
  }

  void unmap_switch(IRInstruction* switch_insn,
                    const cfg::InstructionIterator& switch_it,
                    const GeneratedSwitchCasetoField& case_to_enum,
                    reg_t ordinal_reg) {
    const auto* block = switch_it.block();
    const auto& succs = block->succs();

    // When unmapping a switch, we may rarely find partway through that
    // we don't have the inverse of every case. This is used to store an
    // undo stack on the off-chance we hit this case.
    std::vector<cfg::Edge::MaybeCaseKey> switch_old_cases;
    switch_old_cases.reserve(succs.size());

    const auto rollback = [&] {
      for (size_t undo = 0; undo != switch_old_cases.size(); ++undo) {
        succs[undo]->set_case_key(switch_old_cases[undo]);
      }
    };

    // When a Kotlin switch handles null (case -1), then case 0 will be
    // present to keep the switch packed. It goes to the same block as
    // the default case. Once we unmap, this case edge can be deleted
    // because an ordinal of 0 will take its place.
    cfg::Edge* default_edge = nullptr;
    cfg::Edge* obsolete_zero_edge = nullptr;

    for (cfg::Edge* succ : succs) {
      switch_old_cases.emplace_back(succ->case_key());

      if (!succ->case_key()) {
        // This is the default case, it remains unchanged.
        default_edge = succ;
        continue;
      }

      const int32_t case_value = *succ->case_key();
      if (case_value == 0) {
        // Kotlin null enum default case; see top of file.
        obsolete_zero_edge = succ;
        continue;
      } else if (case_value == kKotlinNullOrdinal) {
        // Kotlin null enum ordinal; see top of file.
        continue;
      }

      // Turn the case value back into the enum ordinal.
      const auto enum_ordinal_maybe =
          get_ordinal_for_case(case_to_enum, case_value);
      if (!enum_ordinal_maybe) {
        // We don't actually have a full mapping. Undo any
        // modifications we've made so far to roll back.
        rollback();
        return;
      }

      const size_t enum_ordinal = *enum_ordinal_maybe;
      succ->set_case_key(enum_ordinal);
    }

    if (obsolete_zero_edge) {
      // This edge is now overwritten with ordinal 0, and not needed.
      if (default_edge &&
          obsolete_zero_edge->target() == default_edge->target()) {
        m_cfg.delete_edge(obsolete_zero_edge);
      } else {
        TRACE(ENUM, 1, "Unexpected zero case value: %s", SHOW(switch_insn));

        rollback();
        return;
      }
    }

    // Success. The source is now the copied ordinal.
    switch_insn->set_src(0, ordinal_reg);
  }

  void unmap_if(IRInstruction* if_cmp_insn,
                const cfg::InstructionIterator& if_cmp_it,
                const GeneratedSwitchCasetoField& case_to_enum,
                reg_t ordinal_reg,
                reg_t aget_src,
                reg_t const_src,
                mf::result_t::src_range insn_kase_range) {
    // We allocate a new const register, and after each of the constants
    // in the range we insert a new unmapped const. (Updating the const
    // in place would be an error, since it could be used elsewhere.)
    //
    // If at any point we decide to roll back these changes, we can just
    // return. The new register and const instructions will be dead.
    reg_t new_const_reg = m_cfg.allocate_temp();

    for (IRInstruction* insn_kase : insn_kase_range) {
      const int64_t case_value = insn_kase->get_literal();
      if (case_value == 0) {
        TRACE(ENUM, 1, "Unexpected zero if case value: %s", SHOW(if_cmp_insn));

        return;
      }

      int32_t enum_ordinal;
      if (case_value == kKotlinNullOrdinal) {
        // Kotlin null enum ordinal; see top of file.
        enum_ordinal = kKotlinNullOrdinal;
      } else {
        // Turn the case value back into the enum ordinal.
        const auto enum_ordinal_maybe =
            get_ordinal_for_case(case_to_enum, case_value);
        if (!enum_ordinal_maybe) {
          // We don't actually have a full mapping.
          return;
        }

        enum_ordinal = *enum_ordinal_maybe;
      }

      auto kase_it = m_cfg.find_insn(insn_kase);
      always_assert(!kase_it.is_end());

      IRInstruction* ordinal_const = new IRInstruction(OPCODE_CONST);
      ordinal_const->set_dest(new_const_reg);
      ordinal_const->set_literal(enum_ordinal);

      m_mutation.insert_after(kase_it, {ordinal_const});
    }

    // Success. Update the if to compare with the ordinal.
    if_cmp_insn->set_src(aget_src, ordinal_reg);
    if_cmp_insn->set_src(const_src, new_const_reg);
  }

  const OptimizeEnumsUnmapMatchFlow& m_flow;
  const EnumFieldToOrdinal& m_enum_field_to_ordinal;
  const GeneratedSwitchCases& m_generated_switch_cases;

  cfg::ControlFlowGraph& m_cfg;
  cfg::CFGMutation m_mutation;
};

} // namespace

OptimizeEnumsUnmapMatchFlow::OptimizeEnumsUnmapMatchFlow(
    const GeneratedSwitchCases& generated_switch_cases) {
  // The flow is: an ordinal into any switchmap lookup that we have
  // the mapping for, which then goes to a comparison with a constant.
  DexMethod* java_enum_ordinal =
      resolve_method(DexMethod::get_method("Ljava/lang/Enum;.ordinal:()I"),
                     MethodSearch::Virtual);
  always_assert(java_enum_ordinal);

  auto m_invoke_ordinal = m::invoke_virtual_(m::has_method(
      m::resolve_method(MethodSearch::Virtual, m::equals(java_enum_ordinal))));
  auto m_lookup = m::sget_object_(
      m::has_field(m::in<DexFieldRef*>(generated_switch_cases)));
  auto m_minus1 =
      m::const_(m::has_literal(m::equals<int64_t>(kKotlinNullOrdinal)));

  // We allow multiple sources to the aget as well as multiple consts for
  // a comparison, hence the use of forall instead of unique. This doesn't
  // occur often, but there are cases where other passes leave such patterns.
  //
  // For nullable Kotlin enums, we must handle that possibility that the
  // switch source is either an aget switchmap or -1 for nulls.
  auto forall = mf::alias | mf::forall;

  kase = flow.insn(m::const_());
  lookup = flow.insn(m_lookup);
  ordinal = flow.insn(m_invoke_ordinal);
  aget_or_m1 = flow.insn(m::aget_() || m_minus1)
                   .src(0, lookup, forall)
                   .src(1, ordinal, forall);

  // See top of file for why IF_EQZ/IF_NEZ are omitted.
  cmp_switch = flow.insn(m::switch_()).src(0, aget_or_m1, forall);
  cmp_if_src0 = flow.insn(m::if_eq_() || m::if_ne_())
                    .src(0, aget_or_m1, forall)
                    .src(1, kase, forall);
  cmp_if_src1 = flow.insn(m::if_eq_() || m::if_ne_())
                    .src(0, kase, forall)
                    .src(1, aget_or_m1, forall);
}

OptimizeEnumsUnmap::OptimizeEnumsUnmap(
    const EnumFieldToOrdinal& enum_field_to_ordinal,
    const GeneratedSwitchCases& generated_switch_cases)
    : m_flow(generated_switch_cases),
      m_enum_field_to_ordinal(enum_field_to_ordinal),
      m_generated_switch_cases(generated_switch_cases) {}

void OptimizeEnumsUnmap::unmap_switchmaps(cfg::ControlFlowGraph& cfg) const {
  OptimizeEnumsUnmapCfg unmap_cfg(m_flow, m_enum_field_to_ordinal,
                                  m_generated_switch_cases, cfg);
  unmap_cfg.unmap_switchmaps();
}

} // namespace optimize_enums


text:
using NodaTime;
using TimeSimulator.Abstractions.Clock;
using TimeSimulator.Abstractions.Tests;
using TimeSimulator.Abstractions.Timer;

namespace TimeSimulator.NodaTime.Tests
{
    public class NodaBasedTimer : TimerTest<Instant, Duration>
    {
        protected override Timer<Instant, Duration> GenerateTimer(ICanAddTime<Duration> clockSubstitute) => new NodaTimer(clockSubstitute);

        protected override Duration IntervalInSeconds(int v) => Duration.FromSeconds(v);
    }
}


text:
/*
 * DO NOT EDIT.  THIS FILE IS GENERATED FROM ../../../dist/idl\nsISAXDTDHandler.idl
 */

#ifndef __gen_nsISAXDTDHandler_h__
#define __gen_nsISAXDTDHandler_h__

#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif

/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif

/* starting interface:    nsISAXDTDHandler */
#define NS_ISAXDTDHANDLER_IID_STR "4d01f225-6cc5-11da-be43-001422106990"

#define NS_ISAXDTDHANDLER_IID \
  {0x4d01f225, 0x6cc5, 0x11da, \
    { 0xbe, 0x43, 0x00, 0x14, 0x22, 0x10, 0x69, 0x90 }}

class NS_NO_VTABLE nsISAXDTDHandler : public nsISupports {
 public:

  NS_DECLARE_STATIC_IID_ACCESSOR(NS_ISAXDTDHANDLER_IID)

  /* void notationDecl (in AString name, in AString publicId, in AString systemId); */
  NS_IMETHOD NotationDecl(const nsAString & name, const nsAString & publicId, const nsAString & systemId) = 0;

  /* void unparsedEntityDecl (in AString name, in AString publicId, in AString systemId, in AString notationName); */
  NS_IMETHOD UnparsedEntityDecl(const nsAString & name, const nsAString & publicId, const nsAString & systemId, const nsAString & notationName) = 0;

};

  NS_DEFINE_STATIC_IID_ACCESSOR(nsISAXDTDHandler, NS_ISAXDTDHANDLER_IID)

/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSISAXDTDHANDLER \
  NS_IMETHOD NotationDecl(const nsAString & name, const nsAString & publicId, const nsAString & systemId) override; \
  NS_IMETHOD UnparsedEntityDecl(const nsAString & name, const nsAString & publicId, const nsAString & systemId, const nsAString & notationName) override;

/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSISAXDTDHANDLER(_to) \
  NS_IMETHOD NotationDecl(const nsAString & name, const nsAString & publicId, const nsAString & systemId) override { return _to NotationDecl(name, publicId, systemId); } \
  NS_IMETHOD UnparsedEntityDecl(const nsAString & name, const nsAString & publicId, const nsAString & systemId, const nsAString & notationName) override { return _to UnparsedEntityDecl(name, publicId, systemId, notationName); }

/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSISAXDTDHANDLER(_to) \
  NS_IMETHOD NotationDecl(const nsAString & name, const nsAString & publicId, const nsAString & systemId) override { return !_to ? NS_ERROR_NULL_POINTER : _to->NotationDecl(name, publicId, systemId); } \
  NS_IMETHOD UnparsedEntityDecl(const nsAString & name, const nsAString & publicId, const nsAString & systemId, const nsAString & notationName) override { return !_to ? NS_ERROR_NULL_POINTER : _to->UnparsedEntityDecl(name, publicId, systemId, notationName); }

#if 0
/* Use the code below as a template for the implementation class for this interface. */

/* Header file */
class nsSAXDTDHandler : public nsISAXDTDHandler
{
public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSISAXDTDHANDLER

  nsSAXDTDHandler();

private:
  ~nsSAXDTDHandler();

protected:
  /* additional members */
};

/* Implementation file */
NS_IMPL_ISUPPORTS(nsSAXDTDHandler, nsISAXDTDHandler)

nsSAXDTDHandler::nsSAXDTDHandler()
{
  /* member initializers and constructor code */
}

nsSAXDTDHandler::~nsSAXDTDHandler()
{
  /* destructor code */
}

/* void notationDecl (in AString name, in AString publicId, in AString systemId); */
NS_IMETHODIMP nsSAXDTDHandler::NotationDecl(const nsAString & name, const nsAString & publicId, const nsAString & systemId)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void unparsedEntityDecl (in AString name, in AString publicId, in AString systemId, in AString notationName); */
NS_IMETHODIMP nsSAXDTDHandler::UnparsedEntityDecl(const nsAString & name, const nsAString & publicId, const nsAString & systemId, const nsAString & notationName)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* End of implementation class template. */
#endif

#endif /* __gen_nsISAXDTDHandler_h__ */


text:
const path           = require('path');
const createTestCafe = require('../../../../../lib');

let testcafe = null;

createTestCafe()
    .then(function (tc) {
        testcafe = tc;

        return testcafe
            .createRunner()
            .browsers('chrome:headless')
            .src(path.join(__dirname, './testcafe-fixtures/index-test.js'))
            .filter(function (testName) {
                return testName === 'Should log error on browser disconnect';
            })
            .run();
    })
    .catch(function () {
        return testcafe.close();
    });


text:
'use strict';

var app = angular.module('brewGet.controllers.breweries', []);

/**
 * Brewery index
 * ROUTE /#!/
 * TEMPLATE /partials/breweries/index.html
 */
app.controller('breweries.index', ['$scope', 'Head', 'Brewery', function ($scope, Head, Brewery) {
  Head.title('Breweries');
  Head.description('Breweries');
  $scope.breweries = Brewery.query();
}]);

/**
 * Brewery show
 * ROUTE /#!/
 * TEMPLATE /partials/breweries/show.html
 */
app.controller('breweries.show', ['$scope', 'Head', 'Brewery', function ($scope, Head, Brewery) {
  Head.title('Brewery');
  Head.description('Brewery');
}]);

/**
 * Brewery new
 * ROUTE /#!/
 * TEMPLATE /partials/breweries/new.html
 */
app.controller('breweries.new', ['$scope', 'Head', 'Brewery', function ($scope, Head, Brewery) {
  Head.title('Add Brewery');
  Head.description('Add Brewery');
}]);

/**
 * Brewery edit
 * ROUTE /#!/
 * TEMPLATE /partials/breweries/edit.html
 */
app.controller('breweries.edit', ['$scope', 'Head', 'Brewery', function ($scope, Head, Brewery) {
  Head.title('Edit Brewery');
  Head.description('Edit Brewery');
}]);


text:
package com.alibaba.rocketmq.example.smoking;

import com.alibaba.rocketmq.client.store.DefaultLocalMessageStore;
import com.alibaba.rocketmq.client.store.LocalMessageStore;
import com.alibaba.rocketmq.common.message.Message;

import java.io.IOException;
import java.util.Arrays;

public class LocalLoad {
    public static void main(String[] args) throws IOException {
        final LocalMessageStore localMessageStore = new DefaultLocalMessageStore("Test");
        localMessageStore.start();

        final byte[] data = new byte[1024];
        Arrays.fill(data, (byte)'x');
        final Message message = new Message("TestTopic", data);
        Message[] messages;
        while (null != (messages = localMessageStore.pop(100))) {
            for (Message msg : messages) {
                System.out.println("Topic: " + message.getTopic().equals(msg.getTopic()));
                System.out.println("Body: " + Arrays.equals(message.getBody(), msg.getBody()));
            }
        }
        localMessageStore.close();
    }
}


text:
package org.apache.cassandra.io.sstable;

import java.io.File;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.TimeUnit;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Sets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.codahale.metrics.Counter;
import org.apache.cassandra.concurrent.ScheduledExecutors;
import org.apache.cassandra.db.lifecycle.Tracker;
import org.apache.cassandra.utils.FBUtilities;
import org.apache.cassandra.utils.concurrent.Blocker;

public class SSTableDeletingTask implements Runnable
{
    private static final Logger logger = LoggerFactory.getLogger(SSTableDeletingTask.class);

    // Deleting sstables is tricky because the mmapping might not have been finalized yet,
    // and delete will fail (on Windows) until it is (we only force the unmapping on SUN VMs).
    // Additionally, we need to make sure to delete the data file first, so on restart the others
    // will be recognized as GCable.
    private static final Set<SSTableDeletingTask> failedTasks = new CopyOnWriteArraySet<>();
    private static final Blocker blocker = new Blocker();

    private final Descriptor desc;
    private final Set<Component> components;
    private final long bytesOnDisk;
    private final Counter totalDiskSpaceUsed;

    /**
     * realDescriptor is the actual descriptor for the sstable, the descriptor inside
     * referent can be 'faked' as FINAL for early opened files. We need the real one
     * to be able to remove the files.
     */
    public SSTableDeletingTask(Descriptor realDescriptor, Set<Component> components, Counter totalDiskSpaceUsed, long bytesOnDisk)
    {
        this.desc = realDescriptor;
        this.bytesOnDisk = bytesOnDisk;
        this.totalDiskSpaceUsed = totalDiskSpaceUsed;
        switch (desc.type)
        {
            case FINAL:
                this.components = components;
                break;
            case TEMPLINK:
                this.components = Sets.newHashSet(Component.DATA, Component.PRIMARY_INDEX);
                break;
            default:
                throw new IllegalStateException();
        }
    }

    public void schedule()
    {
        ScheduledExecutors.nonPeriodicTasks.submit(this);
    }

    public void run()
    {
        blocker.ask();
        // If we can't successfully delete the DATA component, set the task to be retried later: see above
        File datafile = new File(desc.filenameFor(Component.DATA));
        if (!datafile.delete())
        {
            logger.error("Unable to delete {} (it will be removed on server restart; we'll also retry after GC)", datafile);
            failedTasks.add(this);
            return;
        }
        // let the remainder be cleaned up by delete
        SSTable.delete(desc, Sets.difference(components, Collections.singleton(Component.DATA)));
        if (totalDiskSpaceUsed != null)
            totalDiskSpaceUsed.dec(bytesOnDisk);
    }

    /**
     * Retry all deletions that failed the first time around (presumably b/c the sstable was still mmap'd.)
     * Useful because there are times when we know GC has been invoked; also exposed as an mbean.
     */
    public static void rescheduleFailedTasks()
    {
        for (SSTableDeletingTask task : failedTasks)
        {
            failedTasks.remove(task);
            task.schedule();
        }
    }

    /** for tests */
    @VisibleForTesting
    public static void waitForDeletions()
    {
        Runnable runnable = new Runnable()
        {
            public void run()
            {
            }
        };

        FBUtilities.waitOnFuture(ScheduledExecutors.nonPeriodicTasks.schedule(runnable, 0, TimeUnit.MILLISECONDS));
    }

    @VisibleForTesting
    public static void pauseDeletions(boolean stop)
    {
        blocker.block(stop);
    }
}


text:
/**
 * @flow
 */

import React, {Component} from 'react'
import {StyleSheet, Text, View, LayoutAnimation, Image} from 'react-native'
import reactMixin from 'react-mixin'
import TimerMixin from 'react-timer-mixin'

import ToggleButton from '../../components/ToggleButton'
import MuteButton from '../buttons/MuteButton'
import IconButton from '../../components/IconButton'
import Game from '../../classes/Game'
import Timer from '../Timer'

const START_NUMBER = 10
const WARNING_THRESHOLD = 5
const WIN_SCREEN_DELAY = 1500
const LOSE_SCREEN_DELAY = 1500

export default class PlayLayout extends Component {
  static get defaultProps () {
    return {
      demo: false,
      muted: false,
      buttonColors: [
        'lightsteelblue',
        'lightgreen',
        'lightsalmon',
        '#a5d9e5'
      ]
    }
  }

  static get propTypes () {
    return {
      ga: React.PropTypes.object,
      demo: React.PropTypes.bool,
      muted: React.PropTypes.bool,
      navigator: React.PropTypes.object,
      buttonColors: React.PropTypes.array,
      soundsManager: React.PropTypes.object,
      onMaxScoreUpdate: React.PropTypes.func
    }
  }

  constructor (props) {
    super(props)

    const {demo, buttonColors} = this.props

    this.game = new Game({
      targetNum: START_NUMBER - 1,
      onTimeOverCallback: this.updateGameState.bind(this),
      onTickCallback: this.onTimerTick.bind(this)
    })

    this.game.generateNext()

    this.state = {
      ...this.game.getState(),
      ...{demo, buttonColor: buttonColors[0]}
    }

    // weird
    this._demoPressSec = 0
    this._solution = this.game.solution

    this.props.ga.eventOpenApplication()
  }

  componentWillUnmount () {
    this.game.stopTimer()
  }

  incSum (value) {
    this.props.soundsManager.play('toggle_off')
    this.game.incSum(Number(value))
    if (this.state.demo) {
      this.setTimeout(this.updateGameState, 2 * WIN_SCREEN_DELAY)
    } else {
      this.updateGameState()
    }
  }

  decSum (value) {
    this.props.soundsManager.play('toggle_on')
    this.game.decSum(Number(value))
    this.updateGameState()
  }

  updateGameState () {
    if (this.state.gameOver) {
      return
    }

    this.setState({
      isWin: this.game.isWin,
      gameOver: this.game.gameOver
    })

    if (this.game.gameOver) {
      this.props.onMaxScoreUpdate(this.state.targetNum)

      if (this.game.isWin) {
        this.setTimeout(this.generateNewGame, WIN_SCREEN_DELAY)
      } else {
        this.props.ga.eventGameOver(this.state.targetNum)
        this.setTimeout(this.props.navigator.pop, LOSE_SCREEN_DELAY)
      }
    }
  }

  generateNewGame () {
    const {buttonColors} = this.props

    LayoutAnimation.configureNext({
      duration: 100,
      create: {
        type: LayoutAnimation.Types.spring,
        property: LayoutAnimation.Properties.scaleXY,
        springDamping: 0.5
      },
      update: {
        type: LayoutAnimation.Types.spring,
        springDamping: 0.5
      }
    })

    this.game.generateNext()
    this.setState({
      ...this.game.getState(),
      ...{
        demo: false,
        buttonColor: buttonColors[Math.floor(Math.random() * buttonColors.length)]
      }
    })
  }

  onTimerTick (timeout) {
    this.setState({timeout})
    if (this.state.timeout <= WARNING_THRESHOLD) {
      this.props.soundsManager.play('timeout')
    }
  }

  render () {
    const targetNumberTextStyle = [styles.targetNumberText]
    if (this.state.gameOver) {
      if (this.state.isWin) {
        targetNumberTextStyle.push(styles.targetNumberWinText)
      } else {
        targetNumberTextStyle.push(styles.targetNumberLoseText)
      }
    }

    return (
      <Image source={require('./img/background.png')} style={styles.container}>
        <View style={styles.topBar}>
          <IconButton
            name={'arrow-back'}
            onClick={this.props.navigator.pop} />
          <Timer
            demo={this.state.demo}
            timeout={this.state.timeout}
            warningThreshold={WARNING_THRESHOLD} />
          <MuteButton
            soundsManager={this.props.soundsManager}
            muted={this.props.muted} />
        </View>
        <View style={styles.targetNumberContainer}>
          <Text style={targetNumberTextStyle}>
            {this.state.targetNum}
          </Text>
        </View>
        {this.state.gameOver ? null : this.renderGridContainer()}
        <View style={styles.bottomBar} />
      </Image>
    )
  }

  renderGridContainer () {
    return (
      <View style={styles.gridContainer}>
        {this.renderGridRow(0)}
        {this.renderGridRow(1)}
        {this.renderGridRow(2)}
      </View>
    )
  }

  renderGridRow (rowIndex) {
    return (
      <View style={styles.gridRow}>
        {this.renderGridRowButton(3 * rowIndex + 0)}
        {this.renderGridRowButton(3 * rowIndex + 1)}
        {this.renderGridRowButton(3 * rowIndex + 2)}
      </View>
    )
  }

  renderGridRowButton (valuesIndex) {
    let demoPressSec = 0
    const {demo, buttonColor, gameOver} = this.state
    const value = this.state.values[valuesIndex]

    if (demo) {
      const index = this._solution.indexOf(value)
      if (index !== -1) {
        this._demoPressSec++
        this._solution = this._solution.filter((v, k) => (k !== index))
        demoPressSec = this._demoPressSec
      }
    }

    return (
      <ToggleButton
        value={value.toString()}
        onDown={this.incSum.bind(this)}
        onUp={this.decSum.bind(this)}
        disabled={gameOver}
        color={buttonColor}
        demoPressSec={demoPressSec}
        demo={demo} />
    )
  }
}

reactMixin.onClass(PlayLayout, TimerMixin)

const styles = StyleSheet.create({
  container: {
    flex: 1,
    width: null,
    height: null,
    resizeMode: Image.resizeMode.stretch
  },
  topBar: {
    height: 60,
    justifyContent: 'space-between',
    alignItems: 'center',
    flexDirection: 'row',
    paddingTop: 10,
    paddingLeft: 1,
    paddingRight: 3,
    marginBottom: 15
  },
  targetNumberContainer: {
    flex: 2,
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: 5
  },
  targetNumberText: {
    fontSize: 110,
    margin: 20,
    marginTop: 20,
    textShadowOffset: {width: 3, height: 3},
    textShadowRadius: 5,
    textShadowColor: '#aaaaaa'
  },
  targetNumberWinText: {
    color: 'lightgreen',
    marginTop: 0
  },
  targetNumberLoseText: {
    color: 'indianred',
    marginTop: 0
  },
  gridContainer: {
    flex: 5,
    margin: 10
  },
  gridRow: {
    flex: 1,
    flexDirection: 'row'
  },
  bottomBar: {
    height: 60,
    backgroundColor: 'lightgray',
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 10
  }
})


text:
"""
    Notifications API

    Notifications  # noqa: E501

    The version of the OpenAPI document: 2.1.0
    Contact: cloudsupport@telestream.net
    Generated by: https://openapi-generator.tech
"""

from __future__ import absolute_import

import unittest
import datetime

import telestream_cloud_notifications
from telestream_cloud_notifications.models.subscription import Subscription  # noqa: E501
from telestream_cloud_notifications.rest import ApiException

class TestSubscription(unittest.TestCase):
    """Subscription unit test stubs"""

    def setUp(self):
        pass

    def tearDown(self):
        pass

    def make_instance(self, include_optional):
        """Test Subscription
            include_option is a boolean, when False only required
            params are included, when True both required and
            optional params are included """
        # model = telestream_cloud_notifications.models.subscription.Subscription()  # noqa: E501
        if include_optional :
            return Subscription(
                id = '0',
                type = '0',
                topic = telestream_cloud_notifications.models.topic.topic(
                    account = '0',
                    service = '0',
                    event = '0',
                    project = '0',
                    factory = '0',
                    workflow = '0', ),
                params = telestream_cloud_notifications.models.params.params(
                    addresses = [
                        '0'
                        ],
                    url = '0',
                    method = 'GET',
                    retries = 56,
                    content_type = 'application/json',
                    topic_arn = '0',
                    role_arn = '0',
                    topic_endpoint = '0',
                    access_key = '0',
                    project_id = '0',
                    topic_name = '0', )
            )
        else :
            return Subscription(
                type = '0',
                topic = telestream_cloud_notifications.models.topic.topic(
                    account = '0',
                    service = '0',
                    event = '0',
                    project = '0',
                    factory = '0',
                    workflow = '0', ),
                params = telestream_cloud_notifications.models.params.params(
                    addresses = [
                        '0'
                        ],
                    url = '0',
                    method = 'GET',
                    retries = 56,
                    content_type = 'application/json',
                    topic_arn = '0',
                    role_arn = '0',
                    topic_endpoint = '0',
                    access_key = '0',
                    project_id = '0',
                    topic_name = '0', ),
        )

    def testSubscription(self):
        """Test Subscription"""
        inst_req_only = self.make_instance(include_optional=False)
        inst_req_and_optional = self.make_instance(include_optional=True)

if __name__ == '__main__':
    unittest.main()


text:
angular.module('smartCampUZApp')

    // include the 'navbar.html' into the <navbar> tag
    .directive('navbar', function () {
        return {
            restrict: 'E',
            templateUrl: 'templates/components/navbar.html',
            controller: 'navbarCtrl',
            scope: {}
        }
    })

    // include the 'loginForm.html' into the <login-form> tag
    .directive('leaftletMap', function () {
        return {
            restrict: 'E',
            templateUrl: 'templates/components/map.html',
            controller: 'mapCtrl',
            scope: {}
        }
    })

    // include the 'loginForm.html' into the <login-form> tag
    .directive('loginForm', function () {
        return {
            restrict: 'E',
            templateUrl: 'templates/components/loginForm.html',
            controller: 'loginFormCtrl',
            scope: {}
        }
    })

    // include the 'report.html' into the <report> tag
    .directive('report', function () {
        return {
            restrict: 'E',
            templateUrl: 'templates/components/report.html',
            controller: 'reportCtrl',
            scope: true
        }
    });


text:
import Dispatcher from '../classes/Dispatcher'

const fnsToDispatcher = (fns) => new Dispatcher({ fns })

export default fnsToDispatcher