text:
package io.netty.handler.codec.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.util.AsciiString;
import io.netty.util.CharsetUtil;

import static io.netty.handler.codec.http.HttpConstants.*;
import static io.netty.handler.codec.http.HttpObjectEncoder.CRLF_SHORT;

final class HttpHeadersEncoder {
    private static final int COLON_AND_SPACE_SHORT = (COLON << 8) | SP;

    private HttpHeadersEncoder() {
    }

    static void encoderHeader(CharSequence name, CharSequence value, ByteBuf buf) {
        final int nameLen = name.length();
        final int valueLen = value.length();
        final int entryLen = nameLen + valueLen + 4;
        buf.ensureWritable(entryLen);
        int offset = buf.writerIndex();
        writeAscii(buf, offset, name);
        offset += nameLen;
        ByteBufUtil.setShortBE(buf, offset, COLON_AND_SPACE_SHORT);
        offset += 2;
        writeAscii(buf, offset, value);
        offset += valueLen;
        ByteBufUtil.setShortBE(buf, offset, CRLF_SHORT);
        offset += 2;
        buf.writerIndex(offset);
    }

    private static void writeAscii(ByteBuf buf, int offset, CharSequence value) {
        if (value instanceof AsciiString) {
            ByteBufUtil.copy((AsciiString) value, 0, buf, offset, value.length());
        } else {
            buf.setCharSequence(offset, value, CharsetUtil.US_ASCII);
        }
    }
}


text:
type: section
layout: enonce-des-criteres-de-merite-ex5
title: Énoncé des critères de mérite EX-05
aliases: [/statement-of-merit-criteria-ex5/]
url: /enonce-des-criteres-de-merite-ex5/
---

redpajama_set_name: RedPajamaGithub


text:
layout:     post
title:      AWS Step Functions fail at scale
date:       2017-03-09 12:32:18
summary:    hidden limitations of step functions at scale
categories: aws data
---

AWS Lambda functions, each performing a well-defined task are a great way to implement a micro-service that can scale. Lambda Functions free you from thinking about how many requests per second your infrastructure needs to support. No need to worry about installing the right runtime or supported libariries. Simply package you function with its dependencies and specify the runtime: Java or Python.

So, when Amazon realses a service purported to orchestrate Lambda functions at scale, I get excited. Stringing together Lambda functions, each with a core, well-tested task coordinated to perform a much more complex task---amazing!

I'm pissed. After investing in a serverless architecture powered by Amazon's marvelous sounding Lambda functions orchestrated by their newly advertised service, Step Functions, I ran into a roadblock.
Articles such as this [aws blog post](https://aws.amazon.com/blogs/aws/new-aws-step-functions-build-distributed-applications-using-visual-workflows/)
tout AWS Step Functions as a service that "will let you run thousands of execution concurrently so you can scale to any desired level."

Surely, a simple process checking if a field is present in a DynamoDB record is supported?

Failings
bullet
bullet
bullet


text:
package org.deidentifier.arx.metric.v2;

import java.util.Set;

import org.deidentifier.arx.ARXConfiguration;
import org.deidentifier.arx.DataDefinition;
import org.deidentifier.arx.criteria.DPresence;
import org.deidentifier.arx.framework.data.Data;
import org.deidentifier.arx.framework.data.GeneralizationHierarchy;
import org.deidentifier.arx.metric.InformationLoss;
import org.deidentifier.arx.metric.Metric;

/**
 * This class provides an abstract skeleton for the implementation of single-dimensional metrics.
 *
 * @author Fabian Prasser
 * @author Florian Kohlmayer
 */
public abstract class AbstractMetricSingleDimensional extends Metric<ILSingleDimensional> {

    /** SVUID. */
    private static final long serialVersionUID = -1082954137578580790L;

    /** Row count. */
    private Double            tuples         = null;

    /**
     * Creates a new instance.
     *
     * @param monotonic
     * @param independent
     */
    protected AbstractMetricSingleDimensional(final boolean monotonic, final boolean independent) {
        super(monotonic, independent);
    }

    @Override
    public InformationLoss<?> createMaxInformationLoss() {
        return new ILSingleDimensional(Double.MAX_VALUE);
    }

    @Override
    public InformationLoss<?> createMinInformationLoss() {
        return new ILSingleDimensional(0d);
    }

    /**
     * Returns the number of rows in the dataset or subset.
     *
     * @return
     */
    protected Double getNumTuples() {
        return tuples;
    }

    @Override
    protected void initializeInternal(final DataDefinition definition,
                                      final Data input,
                                      final GeneralizationHierarchy[] hierarchies,
                                      final ARXConfiguration config) {

        // Store row count
        if (config.containsCriterion(DPresence.class)) {
            Set<DPresence> criterion = config.getCriteria(DPresence.class);
            if (criterion.size() > 1) { throw new IllegalArgumentException("Only one d-presence criterion supported"); }
            tuples = (double)criterion.iterator().next().getSubset().getArray().length;
        } else {
            tuples = (double)input.getDataLength();
        }
    }

    /**
     * Returns the number of rows in the dataset or subset.
     *
     * @param tuples
     */
    protected void setNumTuples(Double tuples) {
        this.tuples = tuples;
    }
}


text:
class Tile;

class Wall
{
public:
                            Wall(std::vector<glm::vec3> vertices);
    std::vector<glm::vec3>  getVerticies() const;
    Tile*                   getTile() const;
    glm::vec3               getNormal() const;
    void                    setNormal(glm::vec3 normal);
    int                     getTileID() const;
    void                    setTileID(int id);

private:
    std::vector<glm::vec3>	mVertices;
    Tile*                   mTile;
    int                     mTileID;
    glm::vec3               mNormal;
};


text:
<?php
require_once __DIR__.'/../vendor/autoload.php';

$connectionOptions = new \Nats\ConnectionOptions();
$connectionOptions->setHost('localhost')->setPort(4222)->setUser('foo')->setPass('bar');
$c = new Nats\Connection($connectionOptions);
$c->connect();
$c->close();


text:
namespace KinderChat
{
    public enum MessageStatus
    {
        //for outgoing:
        Unsent = 0,
        Sent,
        //for outgoing and incoming:
        Delivered,
        Seen
    }
}


text:
layout: default
title: Home
---

  {% for post in paginator.posts %}

        {{ post.title }}

    {{ post.date | date_to_string }}

    {{ post.content }}

  {% endfor %}

  {% if paginator.next_page %}
    Older
  {% else %}
    Older
  {% endif %}
  {% if paginator.previous_page %}
    {% if paginator.page == 2 %}
      Newer
    {% else %}
      Newer
    {% endif %}
  {% else %}
    Newer
  {% endif %}


text:
<?php
/**
 * @var yii\base\View $this
 * @var app\modules\users\models\User $model
 */

use yii\helpers\Html;
use yii\widgets\ActiveForm;

use app\modules\users\models\User;

$form = ActiveForm::begin(array('options' => array('class' => 'form-horizontal')));
echo $form->field($model, 'username')->textInput($model->isNewRecord ? array() : array('readonly' => true));
echo $form->field($model, 'realname')->textInput();
echo $form->field($model, 'email')->textInput();
if (!$model->isNewRecord) {
    if (Yii::$app->user->checkAccess('editProfile')) {
        echo $form->field($model, 'status')->dropDownList(array(
        	User::STATUS_ACTIVE => 'Вкл',
        	User::STATUS_INACTIVE => 'Выкл',
        	User::STATUS_DELETED => 'Забанен'
        ));
        echo $form->field($model, 'role')->dropDownList(array(
        	User::ROLE_USER => 'Пользователь',
        	User::ROLE_ADMIN => 'Администратор'
        ));
    }
// 	echo $form->field($model, 'oldpassword')->passwordInput();
}
echo $form->field($model, 'password')->passwordInput();
echo $form->field($model, 'repassword')->passwordInput();
?>

<div class="form-actions">
	<?php echo Html::submitButton($model->isNewRecord ? 'Создать' : 'Сохранить', array('class' => 'btn btn-primary')); ?>
</div>

<?php ActiveForm::end(); ?>


text:
/**
 * Module dependencies.
 */

var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var account = require('./routes/account');
var http = require('http');
var path = require('path');

var Mongoose = require('mongoose');
var MongoStore = require('connect-mongo') (express);
var db = require('./config/dbschema');
var flash = require('connect-flash');
var pass = require('./config/pass');
var passport = require('passport');

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(flash());
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('silibug condomworm'));
//app.use(express.session({ secret: 'keyboard cat' }));
app.use(express.session({ secret: 'woolybooger caddis',
	maxAge : new Date(Date.now() + 3600000),
	store: new MongoStore(
		{db:Mongoose.connection.db},
		function(err){
			console.log(err || ' connect-mongodb setup ok');
		})
}));
app.use(passport.initialize());
app.use(passport.session());
//app.use(passport.authenticate('remember-me'));
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
app.use('/public/zxcvbn', express.static('node_modules/zxcvbn/zxcvbn'));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

app.all('/secure', pass.ensureAuthenticated);
app.all('/secure/admin', pass.ensureAdmin);
app.get('/', routes.index);
app.get('/login', user.getlogin);
app.post('/login', user.postlogin);
app.get('/logout', user.logout);
// Signup pages
app.get('/signup', user.getsignup);
app.post('/signup', user.signup);
// Secure pages
app.get('/secure/account', user.account);

app.get('/secure/admin', user.admin);
//app.post('/login',
//	passport.authenticate('local', {sucessReturnToOrRedirect: '/',
//									failureRedirect: '/login',
//									failureFlash: 'Invalid username or password'}));

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});


text:
module AttrEncryptor
  # Contains information about this gem's version
  module Version
    MAJOR = 2
    MINOR = 0
    PATCH = 0

    # Returns a version string by joining <tt>MAJOR</tt>, <tt>MINOR</tt>, and <tt>PATCH</tt> with <tt>'.'</tt>
    #
    # Example
    #
    #   Version.string # '1.0.2'
    def self.string
      [MAJOR, MINOR, PATCH].join('.')
    end
  end
end


text:
set(LLVM_TARGETS_TO_BUILD Native CACHE STRING "")

set(PACKAGE_VENDOR Fuchsia CACHE STRING "")

set(LLVM_INCLUDE_EXAMPLES OFF CACHE BOOL "")
set(LLVM_INCLUDE_TESTS OFF CACHE BOOL "")
set(LLVM_INCLUDE_DOCS OFF CACHE BOOL "")
set(LLVM_ENABLE_BACKTRACES OFF CACHE BOOL "")
set(LLVM_ENABLE_PER_TARGET_RUNTIME_DIR ON CACHE BOOL "")
set(LLVM_ENABLE_TERMINFO OFF CACHE BOOL "")
set(LLVM_ENABLE_ZLIB OFF CACHE BOOL "")
set(CLANG_INCLUDE_TESTS OFF CACHE BOOL "")
set(CLANG_PLUGIN_SUPPORT OFF CACHE BOOL "")

set(LLVM_ENABLE_ASSERTIONS ON CACHE BOOL "")
set(CMAKE_BUILD_TYPE Release CACHE STRING "")

set(BOOTSTRAP_LLVM_ENABLE_LTO ON CACHE BOOL "")
if(NOT APPLE)
  set(BOOTSTRAP_LLVM_ENABLE_LLD ON CACHE BOOL "")
endif()

set(CLANG_DEFAULT_CXX_STDLIB libc++ CACHE STRING "")
set(CLANG_DEFAULT_RTLIB compiler-rt CACHE STRING "")

if(APPLE)
  set(COMPILER_RT_ENABLE_IOS OFF CACHE BOOL "")
  set(COMPILER_RT_ENABLE_TVOS OFF CACHE BOOL "")
  set(COMPILER_RT_ENABLE_WATCHOS OFF CACHE BOOL "")
elseif(UNIX)
  set(LIBUNWIND_ENABLE_SHARED OFF CACHE BOOL "")
  set(LIBUNWIND_USE_COMPILER_RT ON CACHE BOOL "")
  set(LIBUNWIND_INSTALL_LIBRARY OFF CACHE BOOL "")
  set(LIBCXXABI_USE_COMPILER_RT ON CACHE BOOL "")
  set(LIBCXXABI_ENABLE_SHARED OFF CACHE BOOL "")
  set(LIBCXXABI_USE_LLVM_UNWINDER ON CACHE BOOL "")
  set(LIBCXXABI_ENABLE_STATIC_UNWINDER ON CACHE BOOL "")
  set(LIBCXXABI_INSTALL_LIBRARY OFF CACHE BOOL "")
  set(LIBCXX_USE_COMPILER_RT ON CACHE BOOL "")
  set(LIBCXX_ENABLE_SHARED OFF CACHE BOOL "")
  set(LIBCXX_ENABLE_STATIC_ABI_LIBRARY ON CACHE BOOL "")
endif()

set(CLANG_BOOTSTRAP_TARGETS
  check-all
  check-llvm
  check-clang
  llvm-config
  test-suite
  test-depends
  llvm-test-depends
  clang-test-depends
  distribution
  install-distribution
  install-distribution-stripped
  clang CACHE STRING "")

get_cmake_property(variableNames VARIABLES)
foreach(variableName ${variableNames})
  if(variableName MATCHES "^STAGE2_")
    string(REPLACE "STAGE2_" "" new_name ${variableName})
    list(APPEND EXTRA_ARGS "-D${new_name}=${${variableName}}")
  endif()
endforeach()

# Setup the bootstrap build.
set(CLANG_ENABLE_BOOTSTRAP ON CACHE BOOL "")
set(CLANG_BOOTSTRAP_EXTRA_DEPS
  builtins
  runtimes
  CACHE STRING "")
set(CLANG_BOOTSTRAP_CMAKE_ARGS
  ${EXTRA_ARGS}
  -C ${CMAKE_CURRENT_LIST_DIR}/Fuchsia-stage2.cmake
  CACHE STRING "")


text:
_setting_directory=$(dirname $0)/support/.testcase
_config="${_setting_directory}/config"
function _prepare {
  mkdir -p ${_config}
}
function _cleanup {
  rm -r ${_setting_directory}
}


text:
import { Component } from 'vue'
import { mapActions, mapGetters } from 'vuex'

import CategoriesMenu from 'src/components/category/CategoriesMenu'
import Gallery from 'src/components/product/Gallery'
import ProductInfo from 'src/components/product/ProductInfo'
import VariantSelector from 'src/components/product/VariantSelector'

import { ADD_TO_CART } from 'src/infrastructure/store/modules/carts/actions'
import { GET_CATEGORIES } from 'src/infrastructure/store/modules/categories/getters'
import {
  GET_CURRENT_PRODUCT, GET_CURRENT_PRODUCT_TYPE, GET_CURRENT_PRODUCT_VARIANT,
  GET_CURRENT_PRODUCT_VARIANTS
} from 'src/infrastructure/store/modules/products/getters'
import { FETCH_CURRENT_PRODUCT } from 'src/infrastructure/store/modules/products/actions'

import computeVariantsAttributes from './variantsAttributes'
import { AddLineItem } from 'src/infrastructure/api_client/carts'

const noImagePlaceHolder = require('src/assets/images/no_image_placeholder.png')

export default {
  name: 'Product',

  data() {
    return {
      addToCartAlert: null
    }
  },

  computed: {
    ...mapGetters({
      categories: GET_CATEGORIES,
      product: GET_CURRENT_PRODUCT,
      variant: GET_CURRENT_PRODUCT_VARIANT,
      variants: GET_CURRENT_PRODUCT_VARIANTS,
      productType: GET_CURRENT_PRODUCT_TYPE
    }),

    // The 'variantsAttributes' is used by VariantSelector.
    // It only depends on 'variants' and 'productType'. It has two parts:
    // 1. attributesValues: has all combination attributes and their values, used to render variant selector
    // 2. skuAttributeMap: an object that has all skus and their combination attributes
    variantsAttributes(this: Component) {
      return computeVariantsAttributes(this['variants'], this['productType'])
    },

    // also passed to VariantSelector to compute visual states
    currentSku(this: Component) {
      if (this['variant']) {
        return this['variant'].sku
      }
    },

    attributes(this: Component) {
      if (!(this['variant'] && this['productType'])) return

      const attributesMap = {}
      for (let attr of this['variant'].attributes) {
        attributesMap[attr.name] = attr.value
      }

      const attributes = this['productType'].attributes
      .map((attr) => {
        return {
          name: attr.name,
          label: attr.label,
          type: attr.type,
          value: attributesMap[attr.name]
        }
      })

      return attributes
    },

    images(this: Component) {
      if (!(this['variant'] && this['product'])) return

      const thisVariantImages = this['variant'].images
      const masterVariantImages = this['product'].masterVariant.images

      let images
      if (thisVariantImages.length > 0) {
        images = thisVariantImages
      } else if (masterVariantImages.length > 0) {
        images = masterVariantImages.length // use master variant images as fallback
      } else {
        images = [noImagePlaceHolder] // use no image placeholder as fallback
      }

      // server only response fullsize images...
      return images.map(image => {
        return {
          href: image.url,
          thumbnail: image.url
        }
      })
    }
  },

  created(this: Component) {
    this['fetchProduct']()
  },

  watch: {
    '$route': function (this: Component) {
      this['fetchProduct']()
    }
  },

  methods: {
    ...mapActions({
      fetchProduct: FETCH_CURRENT_PRODUCT,
      addToCart: ADD_TO_CART
    }),

    handleAddToCart (this: Component) {
      this['addToCartAlert'] = null

      const payload: AddLineItem = {
        productId: this['product'].id,
        variantId: this['variant'].id,
        quantity: 1
      }
      this['addToCart'](payload)
      .then(() => {
        this['addToCartAlert'] = this['$t']('product.addToCartSuccess')
      })
      .catch(() => {
        this['addToCartAlert'] = this['$t']('product.addToCartError')
      })
    },

    handleSelectSku(this: Component, sku) {
      this['$router'].push({ name: 'products', params: { sku } })
    }
  },

  components: {
    CategoriesMenu,
    Gallery,
    ProductInfo,
    VariantSelector
  }
}


text:
namespace Mordor {

class Stream;

namespace HTTP {

class Connection
{
public:
    boost::shared_ptr<Stream> stream() { return m_stream; }

    static bool hasMessageBody(const GeneralHeaders &general,
        const EntityHeaders &entity,
        const std::string &method,
        Status status,
        bool includeEmpty = true);

    /// @note Be sure to lock the cacheMutex whenever you access the cache
    anymap &cache() { return m_cache; }
    boost::mutex &cacheMutex() { return m_cacheMutex; }

    /// lock cacheMutex and return a copy of value
    template <class TagType>
    typename TagType::value_type getCache(const TagType &key)
    {
        boost::mutex::scoped_lock lock(m_cacheMutex);
        return m_cache[key];
    }

    /// update cache with lock
    template <class TagType>
    void setCache(const TagType &key, const typename TagType::value_type& value)
    {
        boost::mutex::scoped_lock lock(m_cacheMutex);
        m_cache[key] = value;
    }

protected:
    Connection(boost::shared_ptr<Stream> stream);

    boost::shared_ptr<Stream> getStream(const GeneralHeaders &general,
        const EntityHeaders &entity,
        const std::string &method,
        Status status,
        boost::function<void ()> notifyOnEof,
        boost::function<void ()> notifyOnException,
        bool forRead);

protected:
    boost::shared_ptr<Stream> m_stream;

private:
    boost::mutex m_cacheMutex;
    anymap m_cache;
};

}}

#endif


text:
/*
 * @author max
 */
package com.intellij.openapi.wm.impl.welcomeScreen;

import com.intellij.icons.AllIcons;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationInfo;
import com.intellij.openapi.application.ApplicationNamesInfo;
import com.intellij.openapi.application.ex.ApplicationInfoEx;
import com.intellij.openapi.updateSettings.impl.CheckForUpdateAction;
import com.intellij.openapi.updateSettings.impl.UpdateSettings;
import com.intellij.openapi.util.DimensionService;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.wm.WelcomeScreen;
import com.intellij.ui.ScreenUtil;
import com.intellij.ui.components.labels.LinkLabel;
import com.intellij.ui.components.labels.LinkListener;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;

public class NewWelcomeScreen extends JPanel implements WelcomeScreen {

  public NewWelcomeScreen() {
    super(new BorderLayout());
    add(createHeaderPanel(), BorderLayout.NORTH);
    add(createFooterPanel(), BorderLayout.SOUTH);
    add(createInnerPanel(this), BorderLayout.CENTER);
  }

  private static WelcomePane createInnerPanel(WelcomeScreen screen) {
    WelcomeScreenGroup root = new WelcomeScreenGroup(null, "Root");

    ActionManager actionManager = ActionManager.getInstance();
    ActionGroup quickStart = (ActionGroup)actionManager.getAction(IdeActions.GROUP_WELCOME_SCREEN_QUICKSTART);
    for (AnAction child : quickStart.getChildren(null)) {
      root.add(child);
    }

    root.add(buildRootGroup(AllIcons.General.Configure, "Configure", IdeActions.GROUP_WELCOME_SCREEN_CONFIGURE));
    root.add(buildRootGroup(AllIcons.General.ReadHelp, "Docs and How-Tos", IdeActions.GROUP_WELCOME_SCREEN_DOC));

    return new WelcomePane(root, screen);
  }

  private static WelcomeScreenGroup buildRootGroup(Icon groupIcon, String groupText, String groupId) {
    WelcomeScreenGroup docs = new WelcomeScreenGroup(groupIcon, groupText);
    ActionGroup docsActions = (ActionGroup)ActionManager.getInstance().getAction(groupId);
    for (AnAction child : docsActions.getChildren(null)) {
      docs.add(child);
    }
    return docs;
  }

  private static JPanel createFooterPanel() {
    JLabel versionLabel = new JLabel(ApplicationNamesInfo.getInstance().getFullProductName() +
                             " " +
                             ApplicationInfo.getInstance().getFullVersion() +
                             " Build " +
                             ApplicationInfo.getInstance().getBuild().asStringWithoutProductCode());
    makeSmallFont(versionLabel);
    versionLabel.setForeground(WelcomeScreenColors.FOOTER_FOREGROUND);

    JPanel footerPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
    footerPanel.setBackground(WelcomeScreenColors.FOOTER_BACKGROUND);
    footerPanel.setBorder(new EmptyBorder(2, 5, 2, 5) {
      @Override
      public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
        g.setColor(WelcomeScreenColors.BORDER_COLOR);
        g.drawLine(x, y, x + width, y);
      }
    });
    footerPanel.add(versionLabel);
    footerPanel.add(makeSmallFont(new JLabel(".  ")));
    footerPanel.add(makeSmallFont(new LinkLabel("Check", null, new LinkListener() {
      @Override
      public void linkSelected(LinkLabel aSource, Object aLinkData) {
        CheckForUpdateAction.actionPerformed(null, true, null, UpdateSettings.getInstance());
      }
    })));
    footerPanel.add(makeSmallFont(new JLabel(" for updates now.")));
    return footerPanel;
  }

  private static JLabel makeSmallFont(JLabel label) {
    label.setFont(label.getFont().deriveFont((float)10));
    return label;
  }

  private static JPanel createHeaderPanel() {
    JPanel header = new JPanel(new BorderLayout());
    JLabel welcome = new JLabel("Welcome to " + ApplicationNamesInfo.getInstance().getFullProductName(),
                                IconLoader.getIcon(ApplicationInfoEx.getInstanceEx().getWelcomeScreenLogoUrl()),
                                SwingConstants.LEFT);
    welcome.setBorder(new EmptyBorder(10, 15, 10, 15));
    welcome.setFont(welcome.getFont().deriveFont((float) 32));
    welcome.setIconTextGap(20);
    welcome.setForeground(WelcomeScreenColors.WELCOME_HEADER_FOREGROUND);
    header.add(welcome);
    header.setBackground(WelcomeScreenColors.WELCOME_HEADER_BACKGROUND);

    header.setBorder(new BottomLineBorder());
    return header;
  }

  @Override
  public JComponent getWelcomePanel() {
    return this;
  }

  @Override
  public void setupFrame(JFrame frame) {
    frame.setResizable(false);
    frame.pack();
    Point location = DimensionService.getInstance().getLocation(WelcomeFrame.DIMENSION_KEY, null);
    Rectangle screenBounds = ScreenUtil.getScreenRectangle(location != null ? location : new Point(0, 0));
    frame.setLocation(new Point(
      screenBounds.x + (screenBounds.width - frame.getWidth()) / 2,
      screenBounds.y + (screenBounds.height - frame.getHeight()) / 3
    ));
  }

  @Override
  public void dispose() {
  }

  private static class WelcomeScreenGroup extends DefaultActionGroup {
    private WelcomeScreenGroup(Icon icon, String text, AnAction... actions) {
      super(text, true);
      for (AnAction action : actions) {
        add(action);
      }

      getTemplatePresentation().setText(text);
      getTemplatePresentation().setIcon(icon);
    }
  }
}


text:
from django.apps import AppConfig

class TroubleConfig(AppConfig):
    name = 'cbe.trouble'


text:
This directory includes following two files:

* `README.md` -- This file.
* `LICENCE` -- The licence file of [virtual-dom](https://github.com/Matt-Esch/virtual-dom).

The virtual-dom is a JavaScript library created and maintained by Matt-Esch.

The `cape.js` file in the `dist` directory of this package contains
the code of virtual-dom.


text:
package org.r10r.doctester;

import org.r10r.doctester.DocTester;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import org.junit.Assert;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import org.r10r.doctester.rendermachine.RenderMachine;
import org.hamcrest.CoreMatchers;

import static org.hamcrest.CoreMatchers.is;
import org.junit.AfterClass;
import static org.junit.Assert.assertThat;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;

public class DocTesterLifecycleTest extends DocTester {

    @Mock // A static mock to test lifecycle of class
    public static RenderMachine renderMachineMock = Mockito.mock(RenderMachine.class);

    @BeforeClass
    public void asserThatRenderEngineHasBeenInitialized() {
        Assert.assertNotNull(renderMachine);
        assertThat(renderMachine, CoreMatchers.equalTo(renderMachineMock));
    }

    @AfterClass
    public void asserThatRenderEngineHasBeenShutDownCorrectly() {
        Mockito.verify(renderMachineMock).finishAndWriteOut();
        Assert.assertNull(renderMachine);
    }

    @Override
    public RenderMachine getRenderMachine() {
        // to verify that something on renderMachineMock has been called
        return renderMachineMock;
    }

}


text:
package alluxio.fuse.auth;

import alluxio.client.file.FileSystem;
import alluxio.conf.AlluxioConfiguration;
import alluxio.conf.PropertyKey;
import alluxio.jnifuse.AbstractFuseFileSystem;

/**
 * Fuse Auth Policy Factory.
 */
public class AuthPolicyFactory {

  /**
   * Creates a new instance of {@link AuthPolicy}.
   *
   * @param fileSystem     the Alluxio file system
   * @param conf           alluxio configuration
   * @param fuseFileSystem the FuseFileSystem
   * @return AuthPolicy
   */
  public static AuthPolicy create(FileSystem fileSystem,
      AlluxioConfiguration conf,
      AbstractFuseFileSystem fuseFileSystem) {
    Class authPolicyClazz = conf.getClass(PropertyKey.FUSE_AUTH_POLICY_CLASS);
    try {
      return (AuthPolicy) authPolicyClazz.getConstructor(
          new Class[] {FileSystem.class, AlluxioConfiguration.class,
              AbstractFuseFileSystem.class})
          .newInstance(fileSystem, conf, fuseFileSystem);
    } catch (ReflectiveOperationException e) {
      throw new IllegalStateException(
          PropertyKey.FUSE_AUTH_POLICY_CLASS.getName() + " configured to invalid policy "
              + authPolicyClazz + ". Cannot create authenticate policy.", e);
    }
  }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Aspose.ThreeD;
using Aspose.ThreeD.Entities;
using Aspose.ThreeD.Formats;
using Aspose.ThreeD.Render;
using Aspose.ThreeD.Utilities;
using AssetBrowser.Controls;
using Microsoft.Win32;

namespace AssetBrowser
{
    public partial class MainForm : Form
    {
        private string originalTitle;
        private string currentFileName;
        private bool modified;
        private Scene scene = new Scene();
        private ContextMenuStrip contextMenu = new ContextMenuStrip();

        private RegistryKey ConfigKey = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Aspose\AssetBrowser");

        public MainForm()
        {
            InitializeComponent();
            originalTitle = Text;
            string currentPath = ConfigKey.GetValue("Directory", null) as string;
            if (string.IsNullOrEmpty(currentPath))
                currentPath = Directory.GetCurrentDirectory();
            fileSystemTree1.CurrentPath = currentPath;
            fileSystemTree1.DirectoryChanged += OnDirectoryChanged;
            renderView1.Scene = scene;
            sceneHierarchy.RenderView = renderView1;

            contextMenu.Items.Add("Perspective").Click += delegate(object sender, EventArgs e)
            {
                Camera c = (Camera) renderView1.SelectedViewport.Frustum;
                c.ProjectionType = ProjectionType.Perspective;
                OnMovementChanged(btnStandardMovement, null);
            };
            Func<Vector3, Vector3, bool> ortho = delegate(Vector3 pos, Vector3 up)
            {
                Camera c = (Camera) renderView1.SelectedViewport.Frustum;
                OnMovementChanged(btnStandardMovement, null);
                c.ProjectionType = ProjectionType.Orthographic;
                c.Direction = -pos;
                c.Up = up;
                c.ParentNode.Transform.Translation = pos * c.ParentNode.Transform.Translation.Length;
                return true;
            };
            contextMenu.Items.Add("Orthographic - Front").Click += delegate(object sender, EventArgs e)
            {
                ortho(new Vector3(1, 0, 0), Vector3.YAxis);
            };
            contextMenu.Items.Add("Orthographic - Back").Click += delegate(object sender, EventArgs e)
            {
                ortho(new Vector3(-1, 0, 0), Vector3.YAxis);
            };
            contextMenu.Items.Add("Orthographic - Left").Click += delegate(object sender, EventArgs e)
            {
                ortho(new Vector3(0, 0, 1), Vector3.YAxis);
            };
            contextMenu.Items.Add("Orthographic - Right").Click += delegate(object sender, EventArgs e)
            {
                ortho(new Vector3(0, 0, -1), Vector3.YAxis);
            };
            contextMenu.Items.Add("Orthographic - Top").Click += delegate(object sender, EventArgs e)
            {
                ortho(new Vector3(0, 1, 0), Vector3.XAxis);
            };
            contextMenu.Items.Add("Orthographic - Bottom").Click += delegate(object sender, EventArgs e)
            {
                ortho(new Vector3(0, -1, 0), Vector3.XAxis);
            };
            renderView1.ContextMenuStrip = contextMenu;

            if (File.Exists("Aspose.3D.lic"))
            {
                Aspose.ThreeD.License lic = new Aspose.ThreeD.License();
                lic.SetLicense("Aspose.3D.lic");
            }
            WindowState = FormWindowState.Maximized;
            renderView1.SceneUpdated("");
            sceneHierarchy.UpdateHierarchy(scene);
        }

        internal RenderView RenderView
        {
            get { return renderView1; }
        }

        internal SceneHierarchyTree SceneHierarchy
        {
            get { return sceneHierarchy; }
        }

        internal void RendererInitialized()
        {
            renderView1.Scene = scene;
            renderView1.SceneUpdated("");
            sceneHierarchy.UpdateHierarchy(scene);
        }
        internal void SceneUpdated()
        {
            sceneHierarchy.UpdateHierarchy(scene);
        }

        private void OnDirectoryChanged(object sender, EventArgs e)
        {
            ConfigKey.SetValue("Directory", fileSystemTree1.CurrentPath);
        }

        private void UpdateTitle()
        {
            if(modified)
                Text = string.Format("{0} - {1} *Modified", originalTitle, Path.GetFileName(currentFileName));
            else
                Text = string.Format("{0} - {1}", originalTitle, Path.GetFileName(currentFileName));
        }

        public async void OpenFile(string fileName)
        {
            FileFormat format = FileFormat.Detect(fileName);
            if (format == null)
            {
                MessageBox.Show(this, "Unsupported file format", "Open file", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            //create load option and allow user to modify the load options
            LoadOptions opt = format.CreateLoadOptions();
            if (opt != null && opt.GetType() != typeof(LoadOptions))
            {
                if (OptionDialog.ShowDialog(this, "Import Settings", opt) == DialogResult.Cancel)
                    return;
            }

            currentFileName = fileName;
            UpdateTitle();
            long elapsed = 0;
            try
            {
                lblStatus.Text = string.Format("Loading {0}", fileName);
                fileListView1.Enabled = false;
                propertyGrid1.SelectedObject = null;
                Stopwatch st = Stopwatch.StartNew();
                OnMovementChanged(btnStandardMovement, null);
                Console.WriteLine("Loading file {0}", fileName);
                //open the scene using user modified load option in background thread.
                await Task.Run(() => scene.Open(fileName, opt));
                elapsed = st.ElapsedMilliseconds;
                Console.WriteLine("Loaded in {0}ms", elapsed);

                renderView1.SceneUpdated(fileName);
                sceneHierarchy.UpdateHierarchy(scene);
            }
            catch (Exception e)
            {
                MessageBox.Show(this, "Cannot open file " + fileName + "\n" + e.Message, "Open file",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if(elapsed > 0)
                    lblStatus.Text = string.Format("Loaded in {0}ms, Ready.", elapsed);
                else
                    lblStatus.Text = "Ready.";
                fileListView1.Enabled = true;
            }

        }

        private void OnOpenSelectedFile(object sender, EventArgs e)
        {
            string fileName = fileListView1.SelectedFileName;
            if (fileName == null)
                return;
            OpenFile(fileName);
        }

        private void OnSceneObjectSelected(object sender, TreeViewEventArgs e)
        {
            propertyGrid1.SelectedObject = sceneHierarchy.SelectedObject;
        }

        private void OnPropertyChanged(object s, PropertyValueChangedEventArgs e)
        {
            renderView1.Invalidate();
        }

        private void OnChangeViewport(object sender, EventArgs e)
        {
            int viewports = 1;
            if (sender == btnViewport2)
                viewports = 2;
            else if (sender == btnViewport4)
                viewports = 4;
            btnViewport1.Checked = viewports == 1;
            btnViewport2.Checked = viewports == 2;
            btnViewport4.Checked = viewports == 4;
            renderView1.SetViewports(viewports);
        }

        private void OnTogglePostProcessing(object sender, EventArgs e)
        {
            List<string> postProcessingEffects = new List<string>();
            if(btnGrayscale.Checked)
                postProcessingEffects.Add("grayscale");
            if(btnEdgeDetection.Checked)
                postProcessingEffects.Add("edge-detection");
            if(btnPixelation.Checked)
                postProcessingEffects.Add("pixelation");
            if(btnBlur.Checked)
                postProcessingEffects.Add("blur");
            renderView1.SetPostProcessings(postProcessingEffects);
        }

        private void OnDoubleClickSceneObject(object sender, EventArgs e)
        {
            Camera camera = sceneHierarchy.SelectedObject as Camera;
            if (camera != null)
            {
                //switch to the selected camera
                renderView1.SetCamera(camera);
            }
        }

        private void OnExit(object sender, EventArgs e)
        {
            Close();
        }

        private void OnExport(object sender, EventArgs e)
        {
            FileFormat format;
            string fileName = GetSaveFileName(out format);
            if (format == null)
                return;
            //show options for exporting
            SaveOptions opt = format.CreateSaveOptions();
            if (OptionDialog.ShowDialog(this, "Export scene", opt) == DialogResult.Cancel)
                return;
            scene.Save(fileName, opt);

        }

        private string GetSaveFileName(out FileFormat format)
        {
            format = null;
            using (SaveFileDialog d = new SaveFileDialog())
            {
                d.Title = "Export scene";
                List<FileFormat> formats = new List<FileFormat>();
                StringBuilder filter = new StringBuilder();
                foreach (FieldInfo fi in typeof(FileFormat).GetFields(BindingFlags.Public | BindingFlags.Static))
                {
                    if (!typeof(FileFormat).IsAssignableFrom(fi.FieldType))
                        continue;
                    FileFormat f = fi.GetValue(null) as FileFormat;
                    formats.Add(f);
                    if (filter.Length > 0)
                        filter.Append("|");
                    filter.Append(string.Format("{0} {2} {3} (*{1})|*{1}", f.FileFormatType, f.Extension, f.ContentType, f.Version));
                }
                d.Filter = filter.ToString();
                if (d.ShowDialog(this) == DialogResult.Cancel)
                    return null;
                format = formats[d.FilterIndex - 1];
                return d.FileName;
            }
        }

        private void OnMovementChanged(object sender, EventArgs e)
        {

            if (sender == btnFPS)
                renderView1.ChangeMovement<FPSMovement>();
            else if(sender == btnOrbital)
                renderView1.ChangeMovement<OrbitalMovement>();
            else if(sender == btnStandardMovement)
                renderView1.ChangeMovement<StandardMovement>();

            btnFPS.Checked = sender == btnFPS;
            btnOrbital.Checked = sender == btnOrbital;
            btnStandardMovement.Checked = sender == btnStandardMovement;

        }

        private void OnSetExclusivePostProcessing(object sender, EventArgs e)
        {
            if (sender == btnFisheye)
            {
                PostProcessing fisheye = renderView1.Renderer.GetPostProcessing("fisheye");
                btnFisheye.Checked = !btnFisheye.Checked;
                renderView1.CubeBasedPostProcessing = btnFisheye.Checked ? fisheye : null;
            }

        }

        private void OnToggleFileSystem(object sender, EventArgs e)
        {
            var enabled = miFileSystem.Checked;
            leftContainer.Panel1Collapsed = enabled;
            mainContainer.Panel2Collapsed = enabled;

        }

        private void OnUpVectorChanged(object sender, EventArgs e)
        {
            mnUpY.Checked = sender == mnUpY;
            mnUpZ.Checked = sender == mnUpZ;
            if (mnUpY.Checked)
                renderView1.SetUpVector(Axis.YAxis);
            else if (mnUpZ.Checked)
                renderView1.SetUpVector(Axis.ZAxis);

            renderView1.Invalidate();
        }

        private void OnShowNormals(object sender, EventArgs e)
        {
            renderView1.NormalVisible = btnShowNormals.Checked;
            renderView1.Invalidate();
        }
    }
}


text:
class RandomImageGenerator
  def self.generate(string, scale: 10)
    image = Quilt::Identicon.new string, scale: scale
    tmp = Tempfile.new( [ 'quilt', ".png"])
    tmp.binmode
    tmp.write  image.to_blob
    tmp.rewind
    tmp
  end
end


text:
#ifndef EVENTS_H_
#define EVENTS_H_

#include <set>

enum class EventProcessCode { IGNORED, INTERCEPTED };

class MainWindow;
class QEvent;

class KeyboardState
{
  public:
    friend class MainWindow;

    enum class ModifierKey { Control, Alt, Shift };
    enum class Key { Left, Right, Up, Down, Plus, Minus };

    static bool is_modifier_key_pressed(ModifierKey key);

    static bool is_key_pressed(Key key);

  private:
    static void update_keyboard_state(const QEvent* event);

    static std::set<int> pressed_keys_;
};

#endif // EVENTS_H_


text:
package net.sf.jasperreports.olap;

import java.util.Map;

import net.sf.jasperreports.engine.JRDataset;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRValueParameter;
import net.sf.jasperreports.engine.JasperReportsContext;
import net.sf.jasperreports.engine.query.AbstractQueryExecuterFactory;
import net.sf.jasperreports.engine.query.JRQueryExecuter;

/**
 * @author Lucian Chirita (lucianc@users.sourceforge.net)
 * @version $Id: JRMondrianQueryExecuterFactory.java 7199 2014-08-27 13:58:10Z teodord $
 */
public class JRMondrianQueryExecuterFactory extends AbstractQueryExecuterFactory
{
	/**
	 * Built-in parameter holding the value of the Mondrian connection to be used for creating the query.
	 */
	public final static String PARAMETER_MONDRIAN_CONNECTION = "MONDRIAN_CONNECTION";

	private final static Object[] MONDRIAN_BUILTIN_PARAMETERS = {
		PARAMETER_MONDRIAN_CONNECTION,  "mondrian.olap.Connection",
		};

	public Object[] getBuiltinParameters()
	{
		return MONDRIAN_BUILTIN_PARAMETERS;
	}

	public JRQueryExecuter createQueryExecuter(
		JasperReportsContext jasperReportsContext,
		JRDataset dataset,
		Map<String,? extends JRValueParameter> parameters
		) throws JRException
	{
		return new JRMondrianQueryExecuter(jasperReportsContext, dataset, parameters);
	}

	public boolean supportsQueryParameterType(String className)
	{
		return true;
	}
}


text:
DROP TABLE IF EXISTS wf_group_users;

--

CREATE TABLE wf_group_users (
    id INT NOT NULL AUTO_INCREMENT,
    group_id INT NOT NULL,
    user_id INT NOT NULL,
    PRIMARY KEY (id),
    FOREIGN KEY (group_id) REFERENCES wf_groups_master(id),
    UNIQUE (group_id, user_id)
);


text:
using System;
using System.Diagnostics;
using System.Linq;
using NDesk.Options;
using RemotePlusLibrary.Core.IOC;
using RemotePlusLibrary.Extension;
using RemotePlusLibrary.SubSystem.Command;
using RemotePlusLibrary.SubSystem.Command.CommandClasses;
using RemotePlusServer.Core.ExtensionSystem;

namespace RemotePlusServer.Core.Commands
{
    [ExtensionModule]
    public class ProcessCommands : ServerCommandClass
    {
        [CommandHelp("Starts a process on the server.")]
        public CommandResponse ps(CommandRequest args, CommandPipeline pipe, ICommandEnvironment currentEnvironment)
        {
            currentEnvironment.WriteLine();
            bool waitForExit = false;
            bool showHelp = false;
            bool enterDebug = false;
            bool exitDebug = false;
            Process p = new Process();
            OptionSet set = new OptionSet()
                .Add("program|p=", "The process name to start. If shell execution has been disabled, you must specify a full path.", v => p.StartInfo.FileName = v)
                .Add("arguments|a=", "Arguments to pass into the process.", v => p.StartInfo.Arguments = v)
                .Add("DisableShellExecute|s", "Disables the OS to execute the program directly.", v => p.StartInfo.UseShellExecute = false)
                .Add("redirectStdOut|o", "Redirects StdOut to RemotePlus StdOut. NOTE: Shell execution will be disabled.", v =>
                {
                    p.StartInfo.UseShellExecute = false;
                    p.StartInfo.RedirectStandardOutput = true;
                    p.OutputDataReceived += (sender, e) =>
                    {
                        currentEnvironment.WriteLine(e.Data);
                    };
                })
                .Add("redirectStdError|r", "Redirects StdError to RemotePlus StdError. NOTE: Shell execution will be disabled.", v =>
                {
                    p.StartInfo.UseShellExecute = false;
                    p.StartInfo.RedirectStandardError = true;
                    p.ErrorDataReceived += (sender, e) =>
                    {
                        currentEnvironment.WriteLineError(e.Data);
                    };
                })
                .Add("admin|m", "Starts the process as an administrator.", v => p.StartInfo.Verb = "runas")
                .Add("redirectStdIn|i", "Redirects StdIn to RemotePlus StdIn. NOTE: Shell execution will be disabled.", v =>
                {
                    p.StartInfo.UseShellExecute = false;
                    p.StartInfo.RedirectStandardInput = true;
                })
                .Add("disableWindow|w", "Disables a window from appearing.", v => p.StartInfo.CreateNoWindow = true)
                .Add("waitForExit|e", "Waits for the process to exit before returning control back to the client.", v => waitForExit = true)
                .Add("enterDebug", "Puts the server process into debug mode. NOTE: Must have appropriate privileges.", v => enterDebug = true)
                .Add("exitDebug", "Puts the server process out of debug mode.", v => exitDebug = true)
                .Add("help|?", "Shows the help screen.", v => showHelp = true);
            set.Parse(args.Arguments.Select(a => a.ToString()));
            if (showHelp)
            {
                set.WriteOptionDescriptions(currentEnvironment.Out);
                return new CommandResponse((int)CommandStatus.Success);
            }
            if (enterDebug)
            {
                Process.EnterDebugMode();
                return new CommandResponse((int)CommandStatus.Success);
            }
            if (exitDebug)
            {
                Process.LeaveDebugMode();
                return new CommandResponse((int)CommandStatus.Success);
            }
            p.Start();
            if (p.StartInfo.RedirectStandardInput) p.StandardInput.Write(currentEnvironment.ReadToEnd());
            if (p.StartInfo.RedirectStandardOutput) p.BeginOutputReadLine();
            if (p.StartInfo.RedirectStandardError) p.BeginErrorReadLine();
            if (waitForExit)
            {
                var reg = args.CancellationToken.Register(() =>
                {
                    try
                    {
                        p.Kill();
                    }
                    catch (InvalidOperationException) { }
                });
                p.WaitForExit();
                reg.Dispose();
                return new CommandResponse(p.ExitCode);
            }
            else
            {
                return new CommandResponse((int)CommandStatus.Success);
            }
        }

        [CommandHelp("Enumerates and manipulates active processes.")]
        public CommandResponse process(CommandRequest args, CommandPipeline pipe,
            ICommandEnvironment currentEnvironment)
        {
            bool showHelp = false;
            string action = string.Empty;
            OptionSet options = new OptionSet()
                .Add("help|?", "Shows the help screen.", v => showHelp = true);
            options.Parse(args.Arguments.Select(a => a.ToString()));
            if (showHelp)
            {
                options.WriteOptionDescriptions(currentEnvironment.Out);
                return new CommandResponse((int)CommandStatus.Success);
            }

            switch (action)
            {
                default:
                    return new CommandResponse((int)CommandStatus.Success);
            }
        }
        public override void InitializeServices(IServiceCollection services)
        {
            Commands.Add("ps", ps);
            Commands.Add("process", process);
        }
    }
}


text:
package io.gmind7.devops.ldap.common;

import static org.junit.Assert.assertNotNull;
import static org.springframework.ldap.query.LdapQueryBuilder.query;
import io.gmind7.devops.ldap.common.LdapType;
import io.gmind7.spring.foundation.config.AbstractApplicationTest;

import java.util.List;

import javax.naming.NamingException;
import javax.naming.directory.Attributes;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ldap.core.AttributesMapper;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.query.LdapQuery;

public class LdapQueryTest extends AbstractApplicationTest {

	@Autowired
	private LdapTemplate ldapTemplate;

	@Test
	public void ldapQueryTest(){
		LdapQuery query = query().base(LdapType.BASE_DN.getValue()).attributes("sAMAccountName").where("objectclass").is("person").and("sAMAccountName").is("---");
		List<String> list = ldapTemplate.search(query,
		         new AttributesMapper<String>() {
		            public String mapFromAttributes(Attributes attrs) throws NamingException {
		               return (String) attrs.get("sAMAccountName").get();
		            }
		         });

		assertNotNull(list);
	}

}


text:
layout: post
title: Testing the new JetPack Compose Pt2
excerpt: A simple intro to testing basic Android interactions and updates using mockito in JetPack compose
tags:
  - JetPack Compose
  - mockito
  - Android
  - Kotlin
---
### Part 1
Look here for [Part 1](/android-compose-testing/) where I talk about testing loading data and UI updates from it

### __JetPack Compose__
In case you hadn't noticed there's yet another UI framework/toolkit, JetPack Compose! On the surface it has a lot more in common with Google's Flutter than the default Android View, it's written in code (by default Kotlin) and as such is able to generate previews a lot simpler than when you have the XML, you don't have to bind your ViewModels to the xml, you can just pass them into the functions!

### __Testing Android compose__
I want to test some basic UI interactions, we have a list in a ViewModel, clicking a fab add an item to the list and the UI updates to show the list, I won't go through setting up the activity etc, but essentially the activity grabs the viewmodel, call setContent with the theme>surface>initial composable. The initial composeable collects the players list as state and passes it and the addPlayer function to the PlayerList composable.

### Some code
```
class viewModel : ViewModel() {
    private val _players = MutableStateFlow(listOf<Player>())
    val players: StateFlow<List<Player>>
        get() = _players

    fun addPlayer(name: String) {
        _players.value = _players.value + Player(name)
    }
}
```
and our composable looks quite simple for this
```
@Composable
fun PlayerList(players: List<Player>, addPlayer: (String) -> Unit) {
    Scaffold(floatingActionButton = {
        FloatingActionButton(
            onClick = { addPlayer("Player #${players.size}") },
            content = { Icon(Icons.Filled.Add,    "Add new player") },
        )
    }) {
        ScrollableColumn(modifier = Modifier.fillMaxWidth()) {
            players.map { PlayerDisplay(player = it) }
        }
    }
}

@Composable
fun PlayerDisplay(player: Player) {
    Row() {
        Text(text = player.name, softWrap = false)
    }
}
```
and then in our composable test we mock the viewmodel and alter the return of the property
```
class PlayerScreensTest {
    @get:Rule
    val composeTestRule = createAndroidComposeRule<MainActivity>()

    @Test
    fun PlayerListTest() {
        composeTestRule.setContent {
            MyTheme {
                val players by composeTestRule.activity.viewModel.players.collectAsState()
                PlayerList(players, composeTestRule.activity.viewModel::addPlayer)
            }
        }

        composeTestRule.onNodeWithText("Player #0").assertDoesNotExist()
        composeTestRule.onNodeWithContentDescription("Add new player").performClick()
        composeTestRule.onNodeWithText("Player #0").assertIsDisplayed()
        composeTestRule.onNodeWithText("Player #1").assertDoesNotExist()
        composeTestRule.onNodeWithContentDescription("Add new player").performClick()
        composeTestRule.onNodeWithText("Player #0").assertIsDisplayed()
        composeTestRule.onNodeWithText("Player #1").assertIsDisplayed()
    }
}

```
this all looks good, but when running this throws an error
```
2 files found with path 'META-INF/AL2.0' from inputs
```

So now we need to update our apps build.gradle file
```
android {
    // Added to avoid this error -
    // Execution failed for task ':app:mergeDebugAndroidTestJavaResource'.
    // > A failure occurred while executing com.android.build.gradle.internal.tasks.MergeJavaResWorkAction
    // > 2 files found with path 'META-INF/AL2.0' from inputs:
    packagingOptions {
        exclude 'META-INF/AL2.0'
        exclude 'META-INF/LGPL2.1'
    }
}
```
we can then run our tests successfully!


text:
class CreateTaskAndUsers < ActiveRecord::Migration
  def change
    create_table :task_and_users do |t|
      t.references :task, index: true
      t.references :user, index: true

      t.timestamps
    end
  end
end


text:
//
// file DStringPool.hpp
//

//
//  This file is part of the internal implementation of the C++ XML DOM.
//  It should NOT be included or used directly by application programs.
//
//  Applications should include the file <xercesc/dom/deprecated/DOM.hpp> for the entire
//  DOM API, or DOM_*.hpp for individual DOM classes, where the class
//  name is substituded for the *.
//

#ifndef DStringPool_HEADER_GUARD_
#define DStringPool_HEADER_GUARD_

#include "DOMString.hpp"
#include <xercesc/util/XMLRegisterCleanup.hpp>
#include <xercesc/util/PlatformUtils.hpp>

XERCES_CPP_NAMESPACE_BEGIN

struct DStringPoolEntry;

//
// DStringPool is a hash table of DOMStrings.
//  Each DOM Document maintains a DStringPool containing a DOMString
//  for each Element tag name and Attribute Name that has been added
//  to the document.  When creating additional elements or attributes,
//  if the name has been seen before, the already existing string
//  will be reused.
//
class DStringPool : public XMemory
{
public:
    DStringPool(int  hashTableSize,
                MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager);
    ~DStringPool();

    const DOMString &getPooledString(const DOMString &in);
    const DOMString &getPooledString(const XMLCh *in);

    static const DOMString &getStaticString(const char *in
                                          , DOMString **loc
                                          , XMLRegisterCleanup::XMLCleanupFn fn
                                          , XMLRegisterCleanup &clnObj);

private:
    DStringPool(const DStringPool &other);      // Copy constructor and assignment
    DStringPool& operator = (const DStringPool &other); //  of DStringPool are not supported.

    DStringPoolEntry **fHashTable;
    int              fHashTableSize;
    MemoryManager*   fMemoryManager;
};

XERCES_CPP_NAMESPACE_END

#endif


text:
package jp.hotbrain.makecsv

/**
  * Created by hideki takada on 2016/09/10.
  */
object Main {
  def main(args: Array[String]): Unit = {
    try {
      if (null != args && 0 <= args.length) {
        args(0).toLowerCase() match {
          case "export" if 3 == args.length =>
            Environment.setConfigFile(args(1))
            encode(args(2))
            println("ok")
            System.exit(0)
          case "decode" if 4 == args.length =>
            Environment.setConfigFile(args(1))
            decode(args(2), args(3), ungzip = true)
            println("ok")
            System.exit(0)
          case "decrypt" if 4 == args.length =>
            Environment.setConfigFile(args(1))
            decode(args(2), args(3), ungzip = false)
            println("ok")
            System.exit(0)
          case _ =>
        }
      }
      println(
        """Usage:
          |  java -jar make_csv_assembly_1.0.0.jar export [encode.cnf] [export_file]
          |  java -jar make_csv_assembly_1.0.0.jar decode [decode.cnf] [import_file] [export_file]
          |  java -jar make_csv_assembly_1.0.0.jar decrypt [decode.cnf] [import_file] [export_file]
          |          |
          |[encode.cnf]
          |serial=201609101600
          |
          |file.aes.key=[KeyStr]
          |file.aes.iv=[IVStr]
          |
          |file.gzip=false
          |file.col_sep=,
          |file.row_sep=\n
          |file.charset=UTF-8
          |file.timezone=UTC
          |file.dtformat=yyyy/MM/dd HH:mm:ss
          |
          |db.con=jdbc:mysql://localhost/bspark?user=root&password=root&useSSL=false
          |db.sql=SELECT * FROM `master`
          |
          |[decode.cnf|decrypt.cnf]
          |file.serial=201609101700
          |
          |file.aes.key=[KeyStr]
          |file.aes.iv=[IVStr]
          |
          |file.gzip=false
          |
          | """.stripMargin)
    } catch {
      case ex: Throwable => println(ex); println
    }
  }

  private[this] def getXsvExportSetting: XsvExportSetting = {
    val constr = Environment.getValue("db.con").getOrElse(throw new Exception("no Sql Connection String"))
    val sqlstr = Environment.getValue("db.sql").getOrElse(throw new Exception("no Select Sql String"))
    XsvExportSetting(
      constr = constr,
      sqlstr = sqlstr,
      optColSep = Environment.getValue("file.col_sep"),
      optRowSep = Environment.getValue("file.row_sep"),
      optCharset = Environment.getValue("file.charset"),
      optTimeZone = Environment.getValue("file.timezone"),
      optDatetimeFormat = Environment.getValue("file.dtformat")
    )
  }

  private[this] def encode(exportFileName: String): Unit = {
    println(s"Encode: to $exportFileName")
    println
    val conf = getXsvExportSetting
    Encoder(
      fileName = exportFileName,
      aesParam = aesParam(),
      gzip = Environment.getValue("file.gzip", v => "true".equalsIgnoreCase(v)).getOrElse(false)
    ).encodeOf(conf)
  }

  private[this] def decode(importFileName: String, exportFileName: String, ungzip: Boolean): Unit = {
    println(s"Decode: $importFileName to $exportFileName")
    println
    val aes = aesParam()
    val gzip = ungzip && Environment.getValue("file.gzip", v => "true".equalsIgnoreCase(v)).getOrElse(false)
    if (aes.isEmpty && !gzip) {
      println("nothing to do")
    } else {
      DecodeSetting(
        importFileName = importFileName,
        aesParam = aes,
        gzip = gzip
      ).decodeTo(new Decoder(exportFileName))
    }
  }

  private[this] def aesParam(): Option[AesParam] = {
    val key = Environment.getValue("file.aes.key").map(_.trim).getOrElse("")
    val iv = Environment.getValue("file.aes.iv").map(_.trim).getOrElse("")
    if (key.isEmpty || iv.isEmpty) {
      None
    } else {
      Option(AesParam(Environment.getValue("serial").getOrElse("0"), key, iv))
    }
  }
}


text:
from typing import Any, Callable, Iterable, Iterator, Sequence, Tuple

from google.ads.googleads.v11.services.types import keyword_plan_idea_service

class GenerateKeywordIdeasPager:
    """A pager for iterating through ``generate_keyword_ideas`` requests.

    This class thinly wraps an initial
    :class:`google.ads.googleads.v11.services.types.GenerateKeywordIdeaResponse` object, and
    provides an ``__iter__`` method to iterate through its
    ``results`` field.

    If there are more pages, the ``__iter__`` method will make additional
    ``GenerateKeywordIdeas`` requests and continue to iterate
    through the ``results`` field on the
    corresponding responses.

    All the usual :class:`google.ads.googleads.v11.services.types.GenerateKeywordIdeaResponse`
    attributes are available on the pager. If multiple requests are made, only
    the most recent response is retained, and thus used for attribute lookup.
    """

    def __init__(
        self,
        method: Callable[
            ..., keyword_plan_idea_service.GenerateKeywordIdeaResponse
        ],
        request: keyword_plan_idea_service.GenerateKeywordIdeasRequest,
        response: keyword_plan_idea_service.GenerateKeywordIdeaResponse,
        metadata: Sequence[Tuple[str, str]] = (),
    ):
        """Instantiate the pager.

        Args:
            method (Callable): The method that was originally called, and
                which instantiated this pager.
            request (:class:`google.ads.googleads.v11.services.types.GenerateKeywordIdeasRequest`):
                The initial request object.
            response (:class:`google.ads.googleads.v11.services.types.GenerateKeywordIdeaResponse`):
                The initial response object.
            metadata (Sequence[Tuple[str, str]]): Strings which should be
                sent along with the request as metadata.
        """
        self._method = method
        self._request = keyword_plan_idea_service.GenerateKeywordIdeasRequest(
            request
        )
        self._response = response
        self._metadata = metadata

    def __getattr__(self, name: str) -> Any:
        return getattr(self._response, name)

    @property
    def pages(
        self,
    ) -> Iterable[keyword_plan_idea_service.GenerateKeywordIdeaResponse]:
        yield self._response
        while self._response.next_page_token:
            self._request.page_token = self._response.next_page_token
            self._response = self._method(
                self._request, metadata=self._metadata
            )
            yield self._response

    def __iter__(
        self,
    ) -> Iterator[keyword_plan_idea_service.GenerateKeywordIdeaResult]:
        for page in self.pages:
            yield from page.results

    def __repr__(self) -> str:
        return "{0}<{1!r}>".format(self.__class__.__name__, self._response)


text:
'use strict';

const models = require('./index');

/**
 * @class
 * Initializes a new instance of the USqlCredential class.
 * @constructor
 * A Data Lake Analytics catalog U-SQL credential item.
 *
 * @member {string} [name] the name of the credential.
 *
 */
class USqlCredential extends models['CatalogItem'] {
  constructor() {
    super();
  }

  /**
   * Defines the metadata of USqlCredential
   *
   * @returns {object} metadata of USqlCredential
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'USqlCredential',
      type: {
        name: 'Composite',
        className: 'USqlCredential',
        modelProperties: {
          computeAccountName: {
            required: false,
            serializedName: 'computeAccountName',
            type: {
              name: 'String'
            }
          },
          version: {
            required: false,
            serializedName: 'version',
            type: {
              name: 'String'
            }
          },
          name: {
            required: false,
            serializedName: 'credentialName',
            type: {
              name: 'String'
            }
          }
        }
      }
    };
  }
}

module.exports = USqlCredential;


text:
import random
import requests
import json
# Enter your won joke handy in case reddit goes down
PLIVO_JOKE="What do you get when you cross a snowman with a vampire? A frostbite"
def joke_from_reddit():
    random_joke = random.randint(0, 20)
    try:
        # Fetch a list of jokes from reddit
        data = requests.get("http://www.reddit.com/r/cleanjokes.json", timeout=4)
        data = json.loads(data.content)
        content = data['data']['children']
        # Select a random joke from the list
        joke = content[random_joke]
        joke_title = joke['data']['title']
        joke_selftext = joke['data']['selftext']

        # Return the title and joke
        return "%s %s" % (joke_title, joke_selftext)
    except Exception as e:
        return PLIVO_JOKE

if __name__ == "__main__":
print joke_from_reddit()


text:
<?xml version="1.0" encoding="UTF-8"?>
<Context reloadable="true">
	<ResourceLink name="jdbc/prototype" global="jdbc/prototype" type="javax.sql.DataSource"/>
</Context>


text:
namespace ash {

namespace device_sync {

// This class manages the device's enrollment with CryptAuth, periodically
// re-enrolling to keep the state on the server fresh. If an enrollment fails,
// the manager will schedule the next enrollment more aggressively to recover
// from the failure.
class CryptAuthEnrollmentManager {
 public:
  class Observer {
   public:
    // Called when an enrollment attempt is started.
    virtual void OnEnrollmentStarted() {}

    // Called when an enrollment attempt finishes with the |success| of the
    // attempt.
    virtual void OnEnrollmentFinished(bool success) {}

    virtual ~Observer() = default;
  };

  CryptAuthEnrollmentManager();

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

  virtual ~CryptAuthEnrollmentManager();

  void AddObserver(Observer* observer);
  void RemoveObserver(Observer* observer);

  // Begins scheduling periodic enrollment attempts.
  virtual void Start() = 0;

  // Skips the waiting period and requests an immediate enrollment.
  // |invocation_reason|: Specifies the reason that the enrollment was
  //                      triggered, which is uploaded to the server.
  // |session_id|: The session ID sent by CryptAuth v2 in a GCM message
  //               requesting enrollment. Null if enrollment was not triggered
  //               by a GCM message or if no session ID was included in the GCM
  //               message.
  // TODO(nohle): Change cryptauth::InvocationReason to
  // cryptauthv2::ClientMetadata::InvocationReason when CryptAuth v1 is
  // obsolete.
  virtual void ForceEnrollmentNow(
      cryptauth::InvocationReason invocation_reason,
      const absl::optional<std::string>& session_id) = 0;

  // Returns true if a successful enrollment has been recorded and this
  // enrollment has not expired.
  virtual bool IsEnrollmentValid() const = 0;

  // Returns the timestamp of the last successful enrollment. If no enrollment
  // has ever been made, then a null base::Time object will be returned.
  virtual base::Time GetLastEnrollmentTime() const = 0;

  // Returns the time to the next enrollment attempt.
  virtual base::TimeDelta GetTimeToNextAttempt() const = 0;

  // Returns true if an enrollment attempt is currently in progress.
  virtual bool IsEnrollmentInProgress() const = 0;

  // Returns true if the last enrollment failed and the manager is now
  // scheduling enrollments more aggressively to recover. If no enrollment has
  // ever been recorded, then this function will also return true.
  virtual bool IsRecoveringFromFailure() const = 0;

  // Returns the keypair used to enroll with CryptAuth. If no enrollment has
  // been completed, then an empty string will be returned.
  // Note: These keys are really serialized protocol buffer messages, and should
  // only be used by passing to SecureMessageDelegate.
  virtual std::string GetUserPublicKey() const = 0;
  virtual std::string GetUserPrivateKey() const = 0;

 protected:
  void NotifyEnrollmentStarted();
  void NotifyEnrollmentFinished(bool success);

 private:
  base::ObserverList<Observer>::Unchecked observers_;
};

}  // namespace device_sync

}  // namespace ash

// TODO(https://crbug.com/1164001): remove when the migration is finished.
namespace chromeos::device_sync {
using ::ash::device_sync::CryptAuthEnrollmentManager;
}

#endif  // ASH_SERVICES_DEVICE_SYNC_CRYPTAUTH_ENROLLMENT_MANAGER_H_


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

import os
import jinja2
import webapp2

JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
    extensions=['jinja2.ext.autoescape'],
    autoescape=True)

class MainPage(webapp2.RequestHandler):

    def choose_template_from_url(self, url):

        deeplink_class = ''

        if (url != '/'):
            deeplink_class = 'app-deeplink'

        return {
            'path': 'dist/index.html',
            'data': {
                'deeplink_class': deeplink_class
            }
        }

    def get(self, url):

        template_data = self.choose_template_from_url(url)
        template = JINJA_ENVIRONMENT.get_template(template_data['path'])
        self.response.write(template.render(template_data['data']))

app = webapp2.WSGIApplication([
    ('(.*)', MainPage),
], debug=False)


text:
#ifndef JPCONJMAIN_H
#define JPCONJMAIN_H

#include "about.h"
#include "conjframe.h"
#include "deconjframe.h"
#include "Func/edict2.h"
#include "UiHelper/export.h"
#include "jpconjhelp.h"
#include "UiHelper/jpconjtray.h"
#include "UiHelper/language.h"
#include "UiHelper/msg.h"
#include "preference.h"
#include "UiHelper/style.h"
#include "Func/tatoeba.h"
#include "UiHelper/icona.h"

#include "typeDefs.h"
#include "jpconj.h"

#include <QApplication>
#include <QDebug>
#include <QPrintDialog>
#include <QPrinter>
#include <QFileDialog>
#include <QHash>
#include <QMainWindow>
#include <QMap>
#include <QObject>
#include <QWebElement>
#include <QWebFrame>
#include <QWebView>
#include <QMessageBox>

namespace Ui {
class jpconjmain;
}

class jpconjmain : public QMainWindow
{
    Q_OBJECT

public:
    explicit jpconjmain(QWidget *parent = 0);
    ~jpconjmain();

private:
    Ui::jpconjmain *ui;
    About     *winAbout;
    Preference *winPref;
    FuncFrame *workfrm = NULL;
    bool hasContent;
    bool languageChanged;
    EdictType verbType;
    QString currentVerb;
    JpconjTray* trayIconSys;
    QString stylesheet;

    QAction *actionShow;

    void doInit();

    void chooseOperation(int type);

    void doExamples();

    //Functions related to actions slots
    void openAbout();
    void openPref();
    void doExport();
    void exportExamples(Export *exporter);
    void doPrint();
    void openHelp();
    void zoom(signed char sign);
    void createTryIcon();

    //HTML-related functions
    void setCSS(QWebView * webView, QString nameCSS);
    void setHTMLTranslation (bool rtl);

    void changeExamplesFont(QString font, QString jpfont, int size, int jpsize);
    void changeUiIcons();

protected:
    void changeEvent(QEvent* event);
    void closeEvent(QCloseEvent *event);

private slots:
    void changeStyle(QString styleID);
    void changeFont(QString font, QString jpfont, int size, int jpsize);
    void changeIcons();

    void workfrmOpen();
    void workfrmClose();
    void newVerb(QString verb);

    void on_actionClose_triggered();
    void on_actionAbout_triggered();
    void on_actionPreference_triggered();
    void on_actionHelpContent_triggered();
    void on_actionExportResult_triggered();
    void on_actionPrint_triggered();
    void on_actionZoomIn_triggered();
    void on_actionZoomOut_triggered();
    void on_actionNormalSize_triggered();
    void on_actionHide_triggered();
    void on_actionContactUs_triggered();
    void on_actionHomePage_triggered();
    void on_showConjugate_toggled(bool checked);
    void on_showUnconjugate_toggled(bool checked);
};

#endif // JPCONJMAIN_H


text:
const { Vec3 } = require('vec3')
const math = require('./math')
const euclideanMod = math.euclideanMod
const PI = Math.PI
const PI_2 = Math.PI * 2
const TO_RAD = PI / 180
const TO_DEG = 1 / TO_RAD
const FROM_NOTCH_BYTE = 360 / 256
// From wiki.vg: Velocity is believed to be in units of 1/8000 of a block per server tick (50ms)
const FROM_NOTCH_VEL = 1 / 8000

exports.toRadians = toRadians
exports.toDegrees = toDegrees
exports.fromNotchianYaw = fromNotchianYaw
exports.fromNotchianPitch = fromNotchianPitch
exports.fromNotchVelocity = fromNotchVelocity
exports.toNotchianYaw = yaw => toDegrees(PI - yaw)
exports.toNotchianPitch = pitch => toDegrees(-pitch)
exports.fromNotchianYawByte = yaw => fromNotchianYaw(yaw * FROM_NOTCH_BYTE)
exports.fromNotchianPitchByte = pitch => fromNotchianPitch(pitch * FROM_NOTCH_BYTE)

function toRadians (degrees) {
  return TO_RAD * degrees
}

function toDegrees (radians) {
  return TO_DEG * radians
}

function fromNotchianYaw (yaw) {
  return euclideanMod(PI - toRadians(yaw), PI_2)
}

function fromNotchianPitch (pitch) {
  return euclideanMod(toRadians(-pitch) + PI, PI_2) - PI
}

function fromNotchVelocity (vel) {
  return new Vec3(vel.x * FROM_NOTCH_VEL, vel.y * FROM_NOTCH_VEL, vel.z * FROM_NOTCH_VEL)
}


text:
<?php

//Latvian language file. An array is used to hold
//language code and translation
return array(
//Template translations
    'INTRO' => 'SUPPORT and DEVELOPMENT CENTER FOR FAMILIES',
    'ERROR_PAGE' => 'Sorry, failed to find page, that You\'re looking for. Try to use navigation buttons!',
//Navigation bar main buttons
'NAV_ABOUT_US' => 'About Us',
    'NAV_CONTACT' => 'Contacts',
    'NAV_GALLERY' => 'Gallery',
    'NAV_FAQ' => 'Questions',
    'NAV_EMPLOYEE' => 'Specialists',
    'NAV_WELCOME' => 'Home',
    'NAV_PSYCHOLOGY' => 'Psychologist\'s Services',
    'NAV_SAND' => 'Sand Therapy',
    'NAV_MONTESORI' => 'Montessori',
    'NAV_ORFF' => 'ORFF Therapy',
    'NAV_PHYSIOTHERAPY' => 'Physiotherapy',
    'NAV_ADDITIONAL' => 'Other Services',
    'NAV_PRICE' => 'Prices',
    'NAV_MASSAGE' => 'Massage',
    'NAV_MUSICAL_THERAPY' => 'Music Therapy',
    'NAV_SPEC_PEDAGOGUE' => 'Special pedagogue',
    'NAV_METHODICAL_MATERIALS' => 'Methodical Materials',
    'NAV_SAVE' => 'Save!',
    'NAV_BACK' => 'Back!',
    'NAV_ADMIN_PANEL'=>'Admin Panel',
    'GLOBAL_ARE_YOU_SURE_DELETE' => 'Are You sure You want to delete?',
    'LANG_CHANGE_SUCCESS' => 'Language changed successfully to ',
    'LATVIAN'=>'latvian',
    'ENGLISH'=>'english',
    //Translations for drop down buttons, using mark method to locate easier when translating:
    // NAV = navigation , PSYCH = PSYCHOLOGY, FOR_CHILDER = translation
    'NAV_PSYCH_CONSULTING' => 'Consulting',
    'NAV_PSYCH_DIAGNOSTICS' => 'Diagnostics',
    'NAV_PSYCH_LECTURES' => 'Lectures',

    'NAV_MON_ABOUT_MONTESORI' => 'About Montessori',
    'NAV_MON_ACTIVITIES' => 'Developing lessons',
    'NAV_MON_THERAPY' => 'Therapy',

//Employee view
    'EMPLOYEE_HEADER' => 'Specialists',
    'NO_EMPLOYEES_ADDED' => 'Specialist\'s list is empty',
    'EMPLOYEE_NAME' => 'Name',
    'EMPLOYEE_SURNAME' => 'Surname',
    'EMPLOYEE_EMAIL' => 'E-mail',
    'EMPLOYEE_PHONE_NUMBER' => 'Telephone Number',
    'EMPLOYEE_DESCRIPTION' => 'Description',
    'EMPLOYEE_AVATAR' => 'Picture',
    'EMPLOYEE_ADD_NEW' => 'Add new Specialist',
    'EMPLOYEE_EDIT' => 'Edit this Specialist',
    'EMPLOYEE_DELETE_CONFIRM' => 'Are You sure You want to delete this Entry?',
    'EMPLOYEE_KEEP_AVATAR' => 'Don\'t change Picture',
    'EMPLOYEE_UPLOAD_NEW_AVATAR' => 'Upload new Picture',
    'EMPLOYEE_IMAGE_UPLOAD_SUCCESS' => 'Picture uploaded succssesfuly',
    'EMPLOYEE_IMAGE_NOT_VALID' => 'Picture is not valid',
    'EMPLOYEE_ADD_SUCCESS' => 'Specialist is added successfully. ID:',
    'EMPLOYEE_ADD_ERROR' => 'Failed to add Specialist',
    'EMPLOYEE_FIND_ERROR' => 'Failed to find Specialist with ID:',
    'EMPLOYEE_DELETE' => 'Delete this Specialist',
    'EMPLOYEE_IMAGE_UPLOAD_FAILURE' => 'Failed to upload Picture',
    'EMPLOYEE_UPDATE_SUCCESS' => 'Entry is corrected',
    'EMPLOYEE_UPDATE_FAILURE' => 'Failed to correct the Entry',

//ImageGallery view
    'GALLERY_HEADER' => 'Gallery',
    'NO_IMAGES_ADDED' => 'No Image is found',
    'GALLERY_UPLOAD_NEW_IMAGE' => 'Upload new Image',
    'GALLERY_EDIT_DESCRIPTION' => 'Edit Images Description',
    'GALLERY_NEW_IMAGE' => 'Add new Image',
    'GALLERY_FILE_NAME' => 'Images File Name',
    'GALLERY_FILE_DESCRIPTION' => 'Images Description',
    'GALLERY_SAVE_IMAGE' => 'Image',

    'FAQ_HEADING' => 'Favorite answered Questions',
    'NO_FAQ_ADDED' => 'Favorite answered Questions List is empty.',
    'FAQ_ADD_NEW' => 'Add new Image.',
    'FAQ_VIEW_FULL' => 'Read all...',
    'FAQ_EDIT' => 'Edit Question',
    'FAQ_DELETE' => 'Delete Question',
    'FAQ_COULD_NOT_FIND_WITH_NR' => 'Failed to find Question with ID:',
    'FAQ_ADDED_NEW_WITH_NR' => 'Added new Question. ID:',
    'FAQ_COULD_NOT_SAVE' => 'Failed to save Question',
    'FAQ_EDITED_WITH_NR' => 'Question is corrected succssesfuly.',
    'FAQ_COULD_NOT_EDIT_WITH_NR' => 'Delete Question',
    'FAQ_DELETED_WITH_NR' => 'Question is deleted.',
    'FAQ_COULD_NOT_DELETE_WITH_NR:' => 'Failed to delete Question with ID:',

    'FAQ_QUESTION' => 'Question',
    'FAQ_ANSWER' => 'Answer',
//Form placeholder translations

    'PH_FORM_FAQ_ANSWER' => 'Youre Answer',
    'PH_FORM_FAQ_QUESTION' => 'Question',
    'PH_FORM_NAME' => 'Name',
    'PH_FORM_EMAIL' => 'E-mail Adress',
    'PH_FORM_SURNAME' => 'Surname',
    'PH_FORM_PHONENUMBER' => 'Telephone number',
    'PH_FORM_DESCRIPTION' => 'Short Description.',
//Ask form translations
    'ASK_YOUR_QUESTION' => 'Ask Youre Question',
    'ASK_HEADING' => 'Ask Youre Question.',
    'QUESTION_HAS_NOT_BEEN_SENT' => 'Failed to send the Question..',
    'QUESTION_HAS_BEEN_SENT' => 'Question is sent.',
    'ASK_VAL_ERROR_NAME' => 'Name',
    'ASK_VAL_ERROR_EMAIL' => 'E-mail',
    'ASK_VAL_ERROR_MESSAGE' => 'Message',
    'ASK_ERROR_WHILE_SENDING' => 'Sorry, failed to send Youre Question! Please, try again later!',
    'ASK_FORM_VAL_ERROR' => 'Fields are filled incorrect.',
    'ASK_NAME' => 'Name',
    'ASK_MESSAGE' => 'Message',
    'ASK_EMAIL' => 'E-mail',
    'ASK_SEND' => 'Send',
    'ASK_ERROR_WHILE_SENDING' => 'Answer',

    'MATERIAL_PRICE' => 'Price',
    'MATERIAL_HEADER' => 'Methodical Materials',
    'MATERIAL_EDIT' => 'Edit',
    'MATERIAL_DELETE' => 'Delete',
    'MATERIAL_ADD' => 'Add new',
    'MATERIAL_DELETE_FAILURE' => 'Failed to delete material. ID:',
    'MATERIAL_DELETED_SUCCESS' => 'Deleted material. ID:',
    'MATERIAL_UPDATE_FAILURE' => 'Failed to update material. ID:',
    'MATERIAL_UPDATE_SUCCESS' => 'Edited material. ID:',
    'MATERIAL_IMAGE_UPLOAD_FAILURE' => 'Could not upload image',
    'MATERIAL_IMAGE_NOT_VALID' => 'Picture not valid',
    'MATERIAL_IMAGE_UPLOAD_SUCCESS' => 'Picture uploaded successfully',
    'MATERIAL_COULD_NOT_FIND' => 'Could not find material. ID:',
    'MATERIAL_ADDED_FAILURE' => 'Failed to add material.',
    'MATERIAL_ADD_NEW' => 'Pievienot jaunu',
//    'MATERIAL_ADDED_FAILURE' => 'Price',
//    'MATERIAL_ADDED_FAILURE' => 'Price',
//    'MATERIAL_ADDED_FAILURE' => 'Price',
//    'MATERIAL_ADDED_FAILURE' => 'Price',

);


text:
#include <rthw.h>
#include <rtthread.h>
#include "board.h"
#include "uart.h"
#include <stdint.h>
#include <stdbool.h>
#include "r_pdl_cgc.h"
/* General RPDL function definitions */
#include "r_pdl_definitions.h"
#include "intrinsics.h"
#include "iorx62n.h"

/**
 * This is the timer interrupt service routine.
 *
 */
#pragma vector = VECT_CMT0_CMI0
__interrupt
void SysTick_Handler(void)
{
   // __enable_interrupt();
    /* enter interrupt */
    rt_interrupt_enter();

    rt_tick_increase();

    /* leave interrupt */
    rt_interrupt_leave();
}

void  rt_hw_systick_init(void)
{
    /* Enable compare match timer 0. */
    MSTP( CMT0 ) = 0;

    /* Interrupt on compare match. */
    CMT0.CMCR.BIT.CMIE = 1;

    /* Set the compare match value. */
    CMT0.CMCOR = ( unsigned short ) (((XTAL_FREQUENCY * PCLK_MUL) / RT_TICK_PER_SECOND)/8 -1);

    /* Divide the PCLK by 128. */
    CMT0.CMCR.BIT.CKS = 0;

    /* Enable the interrupt... */
    _IEN( _CMT0_CMI0 ) = 1;

    /* ...and set its priority to the application defined kernel priority. */
    _IPR( _CMT0_CMI0 ) = 4;

    /* Start the timer. */
    CMT.CMSTR0.BIT.STR0 = 1;
}

void rt_hw_system_freq_init(void)
{
   /* Declare error flag */
  bool err = true;

  /* Modify the MCU clocks, all are based off Epson 12 MHz clock */
  err &=     R_CGC_Set
    (
    12E6,
    96E6,
    48E6,
    24E6,
    PDL_NO_DATA
    );
  /*
  Clock Description              Frequency
  ----------------------------------------
  Input Clock Frequency..............12MHz
  Internal Clock Frequency...........96MHz
  Peripheral Clock Frequency.........48MHz
  External Bus Clock Frequency.......24MHz */

  /* Halt in while loop when RPDL errors detected */
  while (!err);
}

/**
 * This function will initial rx62n board
 */
void rt_hw_board_init()
{

    rt_hw_system_freq_init();
    rt_hw_systick_init();
    rt_hw_uart_init();
#ifdef RT_USING_CONSOLE
    rt_console_set_device(RT_CONSOLE_DEVICE_NAME);
#endif
}


text:
function signipairs(varargin)

% SIGNIPAIRS reports pairs that are significantly dependent.
% ----------------------------------
% signipairs(cvm, alpha, hypothesis)
% ----------------------------------
% Description: reports those pair of variables that pass the independence
%              test in a significant manner.
% Input:       {cvm} covmatrix instance.
%              <{alpha}> confidence level (def = 0.05).
%              <{hypothesis}> type of hypothesis testing
%                   (def = 'independence (t-test)').
% Output:      reports on the screen the list of significant pairs.

% © Liran Carmel
% Classification: Statistical computations
% Last revision date: 25-Jul-2006

% parse input line
[cvm idx alpha] = parse_input(varargin{:});

% check that test results are present
if isempty(idx)
    fprintf(1,'The required test was not performed.\n');
    return;
end

% get p_value
pv = cvm.p_value{idx};

% loop on all pairs
if get(cvm,'isroweqcol')
    ss = get(cvm,'sampleset');
    no_variables = nosamples(ss);
    for row = 1:(no_variables-1)
        for col = (row+1):no_variables
            if pv(row,col) < alpha
                fprintf(1,'%s and %s are not independent (P = %.4f)\n',...
                    char(ss(row)),char(ss(col)),pv(row,col));
            end
        end
    end
else
    ss_row = get(cvm,'row_sampleset');
    ss_col = get(cvm,'col_sampleset');
    for row = 1:nosamples(ss_row)
        for col = 1:nosamples(ss_col)
            if pv(row,col) < alpha
                fprintf(1,'%s and %s are not independent (P = %g)\n',...
                    char(ss(row)),char(ss(col)),pv(row,col));
            end
        end
    end
end

% #########################################################################
function [cvm, idx, alpha] = parse_input(varargin)

% PARSE_INPUT parses input line.
% ---------------------------------------
% [cvm idx alpha] = parse_input(varargin)
% ---------------------------------------
% Description: parses input line.
% Input:       {varargin} list of input parameters.
% Output:      {cvm} COVMATRIX object.
%              {idx} index of the p_value matrix corresponding to the
%                   desired test.
%              {alpha} condifence level.

% verify number of arguments
error(nargchk(1,3,nargin));

% first argument is always the COVMATRIX
cvm = varargin{1};
error(chkvar(cvm,{},'scalar',{mfilename,inputname(1),1}));

% set defaults
alpha = 0.05;
test = 'independence (t-test)';

% loop on the arguments
for ii = 2:nargin
    errmsg = {mfilename,'',ii};
    [msg1 is_char] = chkvar(varargin{ii},'char','vector',errmsg);
    if is_char
        test = varargin{ii};
    else
        [msg2 is_val] = chkvar(varargin{ii},'double',...
            {'scalar',{'eqgreater',0},{'eqlower',1}},errmsg);
        if is_val
            alpha = varargin{ii};
        else
            error('%s\n%s',msg1,msg2);
        end
    end
end

% compute index of appropriate p_value
idx = strmatch(test,cvm.hypothesis);


text:
<generic-table #employeeTable
               [gtClasses]="'table-sm'"
               [gtSettings]="configObject.settings"
               [gtFields]="configObject.fields"
               [gtData]="employeeData">
</generic-table>

  <gt-table-info class="form-text text-muted mb-2" [genericTable]="employeeTable"></gt-table-info>
  <gt-pagination [gtClasses]="'pagination-sm justify-content-center'" [genericTable]="employeeTable"></gt-pagination>


text:
using System.Globalization;

using Couchbase;
using Couchbase.Core.Exceptions;
using Couchbase.Core.Exceptions.KeyValue;
using Couchbase.KeyValue;

using Google.Protobuf;

using MediatR;

using vivego.KeyValue.Abstractions.Model;
using vivego.KeyValue.Clear;
using vivego.KeyValue.Delete;
using vivego.KeyValue.Features;
using vivego.KeyValue.Get;
using vivego.KeyValue.Set;

namespace vivego.KeyValue.Couchbase;

public readonly record struct DataDocument(byte[] Data);

public sealed class CouchbaseKeyValueStoreRequestHandler : IKeyValueStoreRequestHandler
{
	private readonly Task<KeyValueStoreFeatures> _features;
	private readonly Lazy<Task<ICouchbaseCollection>> _collection;

	public CouchbaseKeyValueStoreRequestHandler(
		Task<ICluster> clusterTask,
		CouchbaseKeyValueStoreRequestHandlerOptions options)
	{
		if (clusterTask is null) throw new ArgumentNullException(nameof(clusterTask));
		if (options is null) throw new ArgumentNullException(nameof(options));

		_features = Task.FromResult(new KeyValueStoreFeatures
		{
			SupportsEtag = true,
			SupportsTtl = true,
			MaximumDataSize = 1024L * 1024L * 20, // 20Mb
			MaximumKeyLength = 250
		});

		_collection = new Lazy<Task<ICouchbaseCollection>>(async () =>
		{
			ICluster cluster = await clusterTask.ConfigureAwait(false);
			IBucket bucket = await cluster.BucketAsync(options.BucketName).ConfigureAwait(false);
			IScope scope = await bucket.ScopeAsync(options.ScopeName).ConfigureAwait(false);
			ICouchbaseCollection collection = await scope.CollectionAsync(options.CollectionName).ConfigureAwait(false);
			return collection;
		}, true);
	}

	public async Task<string> Handle(SetRequest request, CancellationToken cancellationToken)
	{
		if (request.Entry is null) throw new ArgumentNullException(nameof(request.Entry));
		if (string.IsNullOrEmpty(request.Entry.Key)) throw new ArgumentException("Value cannot be null or empty.", nameof(request.Entry.Key));

		ICouchbaseCollection collection = await _collection.Value.ConfigureAwait(false);
		KeyValueEntry keyValueEntry = request.Entry.ConvertToKeyValueEntry(true);

		DataDocument content = new(keyValueEntry.ToByteArray());

		IMutationResult mutationResult;
		if (!string.IsNullOrEmpty(request.Entry.ETag))
		{
			if (ulong.TryParse(request.Entry.ETag, out ulong cas))
			{
				ReplaceOptions replaceOptions = new ReplaceOptions()
					.Cas(cas)
					.CancellationToken(cancellationToken);
				if (request.Entry.ExpiresInSeconds > 0)
				{
					replaceOptions.Expiry(TimeSpan.FromSeconds(request.Entry.ExpiresInSeconds));
				}

				mutationResult = await collection
					.ReplaceAsync(request.Entry.Key, content, replaceOptions)
					.ConfigureAwait(false);
			}
			else
			{
				return string.Empty;
			}
		}
		else
		{
			UpsertOptions upsertOptions = new UpsertOptions().CancellationToken(cancellationToken);
			if (request.Entry.ExpiresInSeconds > 0)
			{
				upsertOptions.Expiry(TimeSpan.FromSeconds(request.Entry.ExpiresInSeconds));
			}

			mutationResult = await collection
				.UpsertAsync(request.Entry.Key, content, upsertOptions)
				.ConfigureAwait(false);
		}

		return mutationResult.Cas.ToString(CultureInfo.InvariantCulture);
	}

	public async Task<KeyValueEntry> Handle(GetRequest request, CancellationToken cancellationToken)
	{
		if (string.IsNullOrEmpty(request.Key)) throw new ArgumentException("Value cannot be null or empty.", nameof(request.Key));

		try
		{
			ICouchbaseCollection collection = await _collection.Value.ConfigureAwait(false);
			IGetResult getResult = await collection
				.GetAsync(request.Key)
				.ConfigureAwait(false);

			DataDocument data = getResult.ContentAs<DataDocument>();
			KeyValueEntry keyValueEntry = KeyValueEntry.Parser.ParseFrom(data.Data);
			if (keyValueEntry.ExpiresAtUnixTimeSeconds > 0
				&& DateTimeOffset.UtcNow > DateTimeOffset.FromUnixTimeSeconds(keyValueEntry.ExpiresAtUnixTimeSeconds))
			{
				return KeyValueEntryExtensions.KeyValueNull;
			}

			return keyValueEntry;
		}
		catch (DocumentNotFoundException)
		{
			return KeyValueEntryExtensions.KeyValueNull;
		}
	}

	public async Task<bool> Handle(DeleteRequest request, CancellationToken cancellationToken)
	{
		if (request.Entry is null) throw new ArgumentNullException(nameof(request.Entry));
		if (string.IsNullOrEmpty(request.Entry.Key)) throw new ArgumentException("Value cannot be null or empty.", nameof(request.Entry.Key));

		ICouchbaseCollection collection = await _collection.Value.ConfigureAwait(false);

		RemoveOptions removeOptions = new RemoveOptions().CancellationToken(cancellationToken);
		if (!string.IsNullOrEmpty(request.Entry.ETag))
		{
			if (ulong.TryParse(request.Entry.ETag, out ulong cas))
			{
				removeOptions.Cas(cas);
			}
			else
			{
				return false;
			}
		}

		try
		{
			await collection
				.RemoveAsync(request.Entry.Key, removeOptions)
				.ConfigureAwait(false);
		}
		catch (InvalidArgumentException)
		{
			return false;
		}

		return true;
	}

	public Task<KeyValueStoreFeatures> Handle(FeaturesRequest request, CancellationToken cancellationToken)
	{
		return _features;
	}

	public Task<Unit> Handle(ClearRequest request, CancellationToken cancellationToken)
	{
		throw new NotImplementedException();
	}
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>G-Index</title>
<meta name="date" content="2017-07-09">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D F G I L M O P Q R S T U V

G

getCognome() - Method in class model.Moderatore

getCognome() - Method in class model.Utente

getData() - Method in class model.Livello

getEmail() - Method in class model.Moderatore

getEmail() - Method in class model.Utente

getGames() - Static method in class database.Dbms

Method used to retrieve all the information related to all the games in the
 system.

getId() - Method in class model.Gioco

getID() - Method in class model.Moderatore

getId() - Method in class model.Recensione

getID() - Method in class model.Utente

getListaUtenti() - Static method in class database.Dbms

Method used to fetch from the database all the information about the users.

getLivello() - Method in class model.Livello

getLivello() - Method in class model.Utente

getMedia(String) - Static method in class database.Dbms

Method used to get from the database the average score of a particular game

getMedia() - Method in class model.Gioco

getNome() - Method in class model.Gioco

getNome() - Method in class model.Moderatore

getNome() - Method in class model.Utente

getPuntiXP() - Method in class model.Utente

getRecensioni(int) - Static method in class database.Dbms

Method used to retrieve all the reviews about a specific game

getRecensioniNonApprovate() - Static method in class database.Dbms

Method used to fetch from the database all the review that haven't been
 approved yet.

getTesto() - Method in class model.Recensione

getTimeLine(String) - Static method in class database.Dbms

Method used to fetch all the information related to the user's timeline.

getUsername() - Method in class model.Moderatore

getUsername() - Method in class model.Utente

getValoreXP() - Method in class model.Gioco

giaVotato(String) - Static method in class database.Dbms

Method used to check if a user has already voted for a specific game

Gioco - Class in model

Class used to represent a game.

Gioco(int, String, int) - Constructor for class model.Gioco

Game constructor.

GiocoDAO - Class in model.dao

GiocoDAO() - Constructor for class model.dao.GiocoDAO

GiocoDAO_Interface - Interface in model.dao

giocoGiaVotato(int, int) - Static method in class controller.listaGiochiController

Method used to check if the currently logged in user has already voted this game.

giocoGiaVotato(int, int) - Method in class model.dao.GiocoDAO

Method used to check if the currently logged in user has already voted this game.

giocoGiaVotato(int, int) - Method in interface model.dao.GiocoDAO_Interface

gui - package gui

A B C D F G I L M O P Q R S T U V

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
Jean-Yves Franceschi

## Files
 - `cimg` folder: contains `cimg.h`, header file of library CImg for handling image storing.
 - `src` folder: contains the source files, with:
   - `main.cpp`: file where the tested scene is defined and the rendering step is launched;
   - `material.hpp`: defines the materials;
   - `mesh.hpp` and `mesh.cpp`: implement meshes and textures importation;
   - `object_container.hpp` and `object_container.cpp`: implement object lists and BVH;
   - `object.hpp` and `object.cpp`: implement all object types;
   - `scene.hpp` and `scene.cpp`: implement the scene;
   - `utils.hpp` and `utils.cpp`: define several useful tools for this project.
 - `examples` folder: contains several examples of main files and their corresponding result (these are the images produced for the report).
 - `car`, `lightning` and `triss` folders: contain all three models used in the examples and in the report.
 - `CMakeLists.txt`: CMake file to configure the project before compilation.
 - `Doxyfile`: configuration file for Doxygen.
 - `LICENSE`: MIT license.
 - `README.md`: this file.
 - `report.pdf`: report of this project.

## Dependencies
 - CMake v. 3.1 or above.
 - A C++ compiler supporting C++14 standard.
 - Assimp library, v. 3.3.1.
 - (Optional) Doxygen for a simple documentation of the project.

## Usage

### General usage
Given a file `main.cpp` in folder `src`, compilation is done with the following commands in a build folder:
`cmake [project root folder] && make -j` for Linux, or equivalent commands for another OS.

The executable is created is the project root folder, and is named `path_tracer`.

### Examples
In order to test one of the examples, one should copy their content to the main file in `src`, and compile again the project.

The program must be executed in the project root tree in order to work correctly (because of relative paths in the examples). However, this constraint does not hold for arbitrary executions of the program with other main files.

### Documentation
In order to produce the documentation of the code of this project, `make doc` should be executed in the build folder. It produces a `doc` folder in the root tree of the project, containing an HTML (`html/index.html`) and PDF (that should be compiled in folder `latex`) version of the documentation.